~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Robert Collins
  • Date: 2010-05-06 07:48:22 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506074822-0bsgf2j4h8jx0xkk
Added ``bzrlib.tests.matchers`` as a place to put matchers, along with
our first in-tree matcher. See the module docstring for details.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
import os
22
22
import re
23
23
import socket
 
24
import stat
24
25
import sys
25
26
import time
26
27
 
27
28
from bzrlib import (
28
29
    errors,
29
 
    lazy_regex,
30
30
    osutils,
31
 
    symbol_versioning,
32
31
    tests,
33
32
    trace,
34
33
    win32utils,
38
37
    file_utils,
39
38
    test__walkdirs_win32,
40
39
    )
41
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
40
 
43
41
 
44
42
class _UTF8DirReaderFeature(tests.Feature):
97
95
    return scenarios
98
96
 
99
97
 
100
 
load_tests = load_tests_apply_scenarios
 
98
def load_tests(basic_tests, module, loader):
 
99
    suite = loader.suiteClass()
 
100
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
 
101
        basic_tests, tests.condition_isinstance(TestDirReader))
 
102
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
 
103
    suite.addTest(remaining_tests)
 
104
    return suite
101
105
 
102
106
 
103
107
class TestContainsWhitespace(tests.TestCase):
180
184
        shape = sorted(os.listdir('.'))
181
185
        self.assertEquals(['A', 'B'], shape)
182
186
 
 
187
    def test_rename_error(self):
 
188
        # We wrap os.rename to make it give an error including the filenames
 
189
        # https://bugs.launchpad.net/bzr/+bug/491763
 
190
        err = self.assertRaises(OSError, osutils.rename,
 
191
            'nonexistent', 'target')
 
192
        self.assertContainsString(str(err), 'nonexistent')
 
193
 
183
194
 
184
195
class TestRandChars(tests.TestCase):
185
196
 
857
868
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
858
869
        # relative path
859
870
        cwd = osutils.getcwd().rstrip('/')
860
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
871
        drive = osutils._nt_splitdrive(cwd)[0]
861
872
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
862
873
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
863
874
        # unicode path
1060
1071
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1061
1072
 
1062
1073
    def test_walkdirs_os_error(self):
1063
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
1074
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1064
1075
        # Pyrex readdir didn't raise useful messages if it had an error
1065
1076
        # reading the directory
1066
1077
        if sys.platform == 'win32':
1067
1078
            raise tests.TestNotApplicable(
1068
1079
                "readdir IOError not tested on win32")
1069
 
        self.requireFeature(features.not_running_as_root)
1070
1080
        os.mkdir("test-unreadable")
1071
1081
        os.chmod("test-unreadable", 0000)
1072
1082
        # must chmod it back so that it can be removed
1080
1090
        # Ensure the message contains the file name
1081
1091
        self.assertContainsRe(str(e), "\./test-unreadable")
1082
1092
 
1083
 
 
1084
 
    def test_walkdirs_encoding_error(self):
1085
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1086
 
        # walkdirs didn't raise a useful message when the filenames
1087
 
        # are not using the filesystem's encoding
1088
 
 
1089
 
        # require a bytestring based filesystem
1090
 
        self.requireFeature(tests.ByteStringNamedFilesystem)
1091
 
 
1092
 
        tree = [
1093
 
            '.bzr',
1094
 
            '0file',
1095
 
            '1dir/',
1096
 
            '1dir/0file',
1097
 
            '1dir/1dir/',
1098
 
            '1file'
1099
 
            ]
1100
 
 
1101
 
        self.build_tree(tree)
1102
 
 
1103
 
        # rename the 1file to a latin-1 filename
1104
 
        os.rename("./1file", "\xe8file")
1105
 
        if "\xe8file" not in os.listdir("."):
1106
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1107
 
 
1108
 
        self._save_platform_info()
1109
 
        win32utils.winver = None # Avoid the win32 detection code
1110
 
        osutils._fs_enc = 'UTF-8'
1111
 
 
1112
 
        # this should raise on error
1113
 
        def attempt():
1114
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1115
 
                pass
1116
 
 
1117
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1118
 
 
1119
1093
    def test__walkdirs_utf8(self):
1120
1094
        tree = [
1121
1095
            '.bzr',
1704
1678
 
1705
1679
class TestReCompile(tests.TestCase):
1706
1680
 
1707
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1708
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1709
 
            osutils.re_compile_checked, *args, **kwargs)
1710
 
 
1711
1681
    def test_re_compile_checked(self):
1712
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1682
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1713
1683
        self.assertTrue(r.match('aaaa'))
1714
1684
        self.assertTrue(r.match('aAaA'))
1715
1685
 
1716
1686
    def test_re_compile_checked_error(self):
1717
1687
        # like https://bugs.launchpad.net/bzr/+bug/251352
1718
 
 
1719
 
        # Due to possible test isolation error, re.compile is not lazy at
1720
 
        # this point. We re-install lazy compile.
1721
 
        lazy_regex.install_lazy_compile()
1722
1688
        err = self.assertRaises(
1723
1689
            errors.BzrCommandError,
1724
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1690
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1725
1691
        self.assertEqual(
1726
 
            'Invalid regular expression in test case: '
1727
 
            '"*" nothing to repeat',
 
1692
            "Invalid regular expression in test case: '*': "
 
1693
            "nothing to repeat",
1728
1694
            str(err))
1729
1695
 
1730
1696
 
1731
1697
class TestDirReader(tests.TestCaseInTempDir):
1732
1698
 
1733
 
    scenarios = dir_reader_scenarios()
1734
 
 
1735
1699
    # Set by load_tests
1736
1700
    _dir_reader_class = None
1737
1701
    _native_to_unicode = None
1899
1863
        self.assertIsInstance(concurrency, int)
1900
1864
 
1901
1865
    def test_local_concurrency_environment_variable(self):
1902
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
 
1866
        os.environ['BZR_CONCURRENCY'] = '2'
1903
1867
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1904
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
 
1868
        os.environ['BZR_CONCURRENCY'] = '3'
1905
1869
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1906
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
 
1870
        os.environ['BZR_CONCURRENCY'] = 'foo'
1907
1871
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1908
1872
 
1909
1873
    def test_option_concurrency(self):
1910
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
 
1874
        os.environ['BZR_CONCURRENCY'] = '1'
1911
1875
        self.run_bzr('rocks --concurrency 42')
1912
 
        # Command line overrides environment variable
 
1876
        # Command line overrides envrionment variable
1913
1877
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1914
1878
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1915
1879
 
1953
1917
 
1954
1918
class TestTerminalWidth(tests.TestCase):
1955
1919
 
1956
 
    def setUp(self):
1957
 
        tests.TestCase.setUp(self)
1958
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1959
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1960
 
        self.addCleanup(self.restore_osutils_globals)
1961
 
        osutils._terminal_size_state = 'no_data'
1962
 
        osutils._first_terminal_size = None
1963
 
 
1964
 
    def restore_osutils_globals(self):
1965
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1966
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1967
 
 
1968
1920
    def replace_stdout(self, new):
1969
1921
        self.overrideAttr(sys, 'stdout', new)
1970
1922
 
1985
1937
    def test_defaults_to_BZR_COLUMNS(self):
1986
1938
        # BZR_COLUMNS is set by the test framework
1987
1939
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
1988
 
        self.overrideEnv('BZR_COLUMNS', '12')
 
1940
        os.environ['BZR_COLUMNS'] = '12'
1989
1941
        self.assertEqual(12, osutils.terminal_width())
1990
1942
 
1991
 
    def test_BZR_COLUMNS_0_no_limit(self):
1992
 
        self.overrideEnv('BZR_COLUMNS', '0')
1993
 
        self.assertEqual(None, osutils.terminal_width())
1994
 
 
1995
1943
    def test_falls_back_to_COLUMNS(self):
1996
 
        self.overrideEnv('BZR_COLUMNS', None)
 
1944
        del os.environ['BZR_COLUMNS']
1997
1945
        self.assertNotEqual('42', os.environ['COLUMNS'])
1998
1946
        self.set_fake_tty()
1999
 
        self.overrideEnv('COLUMNS', '42')
 
1947
        os.environ['COLUMNS'] = '42'
2000
1948
        self.assertEqual(42, osutils.terminal_width())
2001
1949
 
2002
1950
    def test_tty_default_without_columns(self):
2003
 
        self.overrideEnv('BZR_COLUMNS', None)
2004
 
        self.overrideEnv('COLUMNS', None)
 
1951
        del os.environ['BZR_COLUMNS']
 
1952
        del os.environ['COLUMNS']
2005
1953
 
2006
1954
        def terminal_size(w, h):
2007
1955
            return 42, 42
2014
1962
        self.assertEqual(42, osutils.terminal_width())
2015
1963
 
2016
1964
    def test_non_tty_default_without_columns(self):
2017
 
        self.overrideEnv('BZR_COLUMNS', None)
2018
 
        self.overrideEnv('COLUMNS', None)
 
1965
        del os.environ['BZR_COLUMNS']
 
1966
        del os.environ['COLUMNS']
2019
1967
        self.replace_stdout(None)
2020
1968
        self.assertEqual(None, osutils.terminal_width())
2021
1969
 
2031
1979
        else:
2032
1980
            self.overrideAttr(termios, 'TIOCGWINSZ')
2033
1981
            del termios.TIOCGWINSZ
2034
 
        self.overrideEnv('BZR_COLUMNS', None)
2035
 
        self.overrideEnv('COLUMNS', None)
 
1982
        del os.environ['BZR_COLUMNS']
 
1983
        del os.environ['COLUMNS']
2036
1984
        # Whatever the result is, if we don't raise an exception, it's ok.
2037
1985
        osutils.terminal_width()
2038
1986
 
2070
2018
        self.assertEquals(self.path, 'test_file')
2071
2019
        self.assertEquals(self.uid, s.st_uid)
2072
2020
        self.assertEquals(self.gid, s.st_gid)
2073
 
 
2074
 
class TestGetuserUnicode(tests.TestCase):
2075
 
 
2076
 
    def test_ascii_user(self):
2077
 
        self.overrideEnv('LOGNAME', 'jrandom')
2078
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2079
 
 
2080
 
    def test_unicode_user(self):
2081
 
        ue = osutils.get_user_encoding()
2082
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2083
 
        if uni_val is None:
2084
 
            raise tests.TestSkipped(
2085
 
                'Cannot find a unicode character that works in encoding %s'
2086
 
                % (osutils.get_user_encoding(),))
2087
 
        uni_username = u'jrandom' + uni_val
2088
 
        encoded_username = uni_username.encode(ue)
2089
 
        self.overrideEnv('LOGNAME', encoded_username)
2090
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2091
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
2092
 
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
2093
 
 
2094
 
class TestBackupNames(tests.TestCase):
2095
 
 
2096
 
    def setUp(self):
2097
 
        super(TestBackupNames, self).setUp()
2098
 
        self.backups = []
2099
 
 
2100
 
    def backup_exists(self, name):
2101
 
        return name in self.backups
2102
 
 
2103
 
    def available_backup_name(self, name):
2104
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2105
 
        self.backups.append(backup_name)
2106
 
        return backup_name
2107
 
 
2108
 
    def assertBackupName(self, expected, name):
2109
 
        self.assertEqual(expected, self.available_backup_name(name))
2110
 
 
2111
 
    def test_empty(self):
2112
 
        self.assertBackupName('file.~1~', 'file')
2113
 
 
2114
 
    def test_existing(self):
2115
 
        self.available_backup_name('file')
2116
 
        self.available_backup_name('file')
2117
 
        self.assertBackupName('file.~3~', 'file')
2118
 
        # Empty slots are found, this is not a strict requirement and may be
2119
 
        # revisited if we test against all implementations.
2120
 
        self.backups.remove('file.~2~')
2121
 
        self.assertBackupName('file.~2~', 'file')
2122
 
 
2123
 
 
2124
 
class TestFindExecutableInPath(tests.TestCase):
2125
 
 
2126
 
    def test_windows(self):
2127
 
        if sys.platform != 'win32':
2128
 
            raise tests.TestSkipped('test requires win32')
2129
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2130
 
        self.assertTrue(
2131
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2132
 
        self.assertTrue(
2133
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2134
 
        self.assertTrue(
2135
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2136
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2137
 
 
2138
 
    def test_other(self):
2139
 
        if sys.platform == 'win32':
2140
 
            raise tests.TestSkipped('test requires non-win32')
2141
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2142
 
        self.assertTrue(
2143
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)