/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: John Arbash Meinel
  • Date: 2011-04-20 09:46:28 UTC
  • mfrom: (5609.33.4 2.3)
  • mto: (5609.33.5 2.3)
  • mto: This revision was merged to the branch mainline in revision 5811.
  • Revision ID: john@arbash-meinel.com-20110420094628-l0bafq1lwb6ib1v2
Merge lp:bzr/2.3 @ 5640 so we can update the release notes (aka NEWS)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
25
24
import sys
26
25
import time
27
26
 
28
27
from bzrlib import (
29
28
    errors,
 
29
    lazy_regex,
30
30
    osutils,
 
31
    symbol_versioning,
31
32
    tests,
32
33
    trace,
33
34
    win32utils,
37
38
    file_utils,
38
39
    test__walkdirs_win32,
39
40
    )
 
41
from bzrlib.tests.scenarios import load_tests_apply_scenarios
40
42
 
41
43
 
42
44
class _UTF8DirReaderFeature(tests.Feature):
95
97
    return scenarios
96
98
 
97
99
 
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
 
100
load_tests = load_tests_apply_scenarios
105
101
 
106
102
 
107
103
class TestContainsWhitespace(tests.TestCase):
310
306
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
311
307
        self.assertEqual("@", osutils.kind_marker("symlink"))
312
308
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
313
 
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
309
        self.assertEqual("", osutils.kind_marker("fifo"))
 
310
        self.assertEqual("", osutils.kind_marker("socket"))
 
311
        self.assertEqual("", osutils.kind_marker("unknown"))
314
312
 
315
313
 
316
314
class TestUmask(tests.TestCaseInTempDir):
859
857
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
860
858
        # relative path
861
859
        cwd = osutils.getcwd().rstrip('/')
862
 
        drive = osutils._nt_splitdrive(cwd)[0]
 
860
        drive = osutils.ntpath.splitdrive(cwd)[0]
863
861
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
864
862
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
865
863
        # unicode path
1082
1080
        # Ensure the message contains the file name
1083
1081
        self.assertContainsRe(str(e), "\./test-unreadable")
1084
1082
 
 
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
 
1085
1119
    def test__walkdirs_utf8(self):
1086
1120
        tree = [
1087
1121
            '.bzr',
1137
1171
            dirblock[:] = new_dirblock
1138
1172
 
1139
1173
    def _save_platform_info(self):
1140
 
        cur_winver = win32utils.winver
1141
 
        cur_fs_enc = osutils._fs_enc
1142
 
        cur_dir_reader = osutils._selected_dir_reader
1143
 
        def restore():
1144
 
            win32utils.winver = cur_winver
1145
 
            osutils._fs_enc = cur_fs_enc
1146
 
            osutils._selected_dir_reader = cur_dir_reader
1147
 
        self.addCleanup(restore)
 
1174
        self.overrideAttr(win32utils, 'winver')
 
1175
        self.overrideAttr(osutils, '_fs_enc')
 
1176
        self.overrideAttr(osutils, '_selected_dir_reader')
1148
1177
 
1149
1178
    def assertDirReaderIs(self, expected):
1150
1179
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1583
1612
        def cleanup():
1584
1613
            if 'BZR_TEST_ENV_VAR' in os.environ:
1585
1614
                del os.environ['BZR_TEST_ENV_VAR']
1586
 
 
1587
1615
        self.addCleanup(cleanup)
1588
1616
 
1589
1617
    def test_set(self):
1676
1704
 
1677
1705
class TestReCompile(tests.TestCase):
1678
1706
 
 
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
 
1679
1711
    def test_re_compile_checked(self):
1680
 
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
 
1712
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1681
1713
        self.assertTrue(r.match('aaaa'))
1682
1714
        self.assertTrue(r.match('aAaA'))
1683
1715
 
1684
1716
    def test_re_compile_checked_error(self):
1685
1717
        # 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()
1686
1722
        err = self.assertRaises(
1687
1723
            errors.BzrCommandError,
1688
 
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1724
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1689
1725
        self.assertEqual(
1690
 
            "Invalid regular expression in test case: '*': "
1691
 
            "nothing to repeat",
 
1726
            'Invalid regular expression in test case: '
 
1727
            '"*" nothing to repeat',
1692
1728
            str(err))
1693
1729
 
1694
1730
 
1695
1731
class TestDirReader(tests.TestCaseInTempDir):
1696
1732
 
 
1733
    scenarios = dir_reader_scenarios()
 
1734
 
1697
1735
    # Set by load_tests
1698
1736
    _dir_reader_class = None
1699
1737
    _native_to_unicode = None
1700
1738
 
1701
1739
    def setUp(self):
1702
1740
        tests.TestCaseInTempDir.setUp(self)
1703
 
 
1704
 
        # Save platform specific info and reset it
1705
 
        cur_dir_reader = osutils._selected_dir_reader
1706
 
 
1707
 
        def restore():
1708
 
            osutils._selected_dir_reader = cur_dir_reader
1709
 
        self.addCleanup(restore)
1710
 
 
1711
 
        osutils._selected_dir_reader = self._dir_reader_class()
 
1741
        self.overrideAttr(osutils,
 
1742
                          '_selected_dir_reader', self._dir_reader_class())
1712
1743
 
1713
1744
    def _get_ascii_tree(self):
1714
1745
        tree = [
1861
1892
 
1862
1893
    def setUp(self):
1863
1894
        super(TestConcurrency, self).setUp()
1864
 
        orig = osutils._cached_local_concurrency
1865
 
        def restore():
1866
 
            osutils._cached_local_concurrency = orig
1867
 
        self.addCleanup(restore)
 
1895
        self.overrideAttr(osutils, '_cached_local_concurrency')
1868
1896
 
1869
1897
    def test_local_concurrency(self):
1870
1898
        concurrency = osutils.local_concurrency()
1871
1899
        self.assertIsInstance(concurrency, int)
1872
1900
 
1873
1901
    def test_local_concurrency_environment_variable(self):
1874
 
        os.environ['BZR_CONCURRENCY'] = '2'
 
1902
        self.overrideEnv('BZR_CONCURRENCY', '2')
1875
1903
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1876
 
        os.environ['BZR_CONCURRENCY'] = '3'
 
1904
        self.overrideEnv('BZR_CONCURRENCY', '3')
1877
1905
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1878
 
        os.environ['BZR_CONCURRENCY'] = 'foo'
 
1906
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
1879
1907
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1880
1908
 
1881
1909
    def test_option_concurrency(self):
1882
 
        os.environ['BZR_CONCURRENCY'] = '1'
 
1910
        self.overrideEnv('BZR_CONCURRENCY', '1')
1883
1911
        self.run_bzr('rocks --concurrency 42')
1884
 
        # Command line overrides envrionment variable
 
1912
        # Command line overrides environment variable
1885
1913
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1886
1914
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1887
1915
 
1897
1925
 
1898
1926
    def setUp(self):
1899
1927
        super(TestFailedToLoadExtension, self).setUp()
1900
 
        self.saved_failures = osutils._extension_load_failures[:]
1901
 
        del osutils._extension_load_failures[:]
1902
 
        self.addCleanup(self.restore_failures)
1903
 
 
1904
 
    def restore_failures(self):
1905
 
        osutils._extension_load_failures = self.saved_failures
 
1928
        self.overrideAttr(osutils, '_extension_load_failures', [])
1906
1929
 
1907
1930
    def test_failure_to_load(self):
1908
1931
        self._try_loading()
1941
1964
    def restore_osutils_globals(self):
1942
1965
        osutils._terminal_size_state = self._orig_terminal_size_state
1943
1966
        osutils._first_terminal_size = self._orig_first_terminal_size
1944
 
        
 
1967
 
1945
1968
    def replace_stdout(self, new):
1946
 
        orig_stdout = sys.stdout
1947
 
        def restore():
1948
 
            sys.stdout = orig_stdout
1949
 
        self.addCleanup(restore)
1950
 
        sys.stdout = new
 
1969
        self.overrideAttr(sys, 'stdout', new)
1951
1970
 
1952
1971
    def replace__terminal_size(self, new):
1953
 
        orig__terminal_size = osutils._terminal_size
1954
 
        def restore():
1955
 
            osutils._terminal_size = orig__terminal_size
1956
 
        self.addCleanup(restore)
1957
 
        osutils._terminal_size = new
 
1972
        self.overrideAttr(osutils, '_terminal_size', new)
1958
1973
 
1959
1974
    def set_fake_tty(self):
1960
1975
 
1970
1985
    def test_defaults_to_BZR_COLUMNS(self):
1971
1986
        # BZR_COLUMNS is set by the test framework
1972
1987
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
1973
 
        os.environ['BZR_COLUMNS'] = '12'
 
1988
        self.overrideEnv('BZR_COLUMNS', '12')
1974
1989
        self.assertEqual(12, osutils.terminal_width())
1975
1990
 
 
1991
    def test_BZR_COLUMNS_0_no_limit(self):
 
1992
        self.overrideEnv('BZR_COLUMNS', '0')
 
1993
        self.assertEqual(None, osutils.terminal_width())
 
1994
 
1976
1995
    def test_falls_back_to_COLUMNS(self):
1977
 
        del os.environ['BZR_COLUMNS']
 
1996
        self.overrideEnv('BZR_COLUMNS', None)
1978
1997
        self.assertNotEqual('42', os.environ['COLUMNS'])
1979
1998
        self.set_fake_tty()
1980
 
        os.environ['COLUMNS'] = '42'
 
1999
        self.overrideEnv('COLUMNS', '42')
1981
2000
        self.assertEqual(42, osutils.terminal_width())
1982
2001
 
1983
2002
    def test_tty_default_without_columns(self):
1984
 
        del os.environ['BZR_COLUMNS']
1985
 
        del os.environ['COLUMNS']
 
2003
        self.overrideEnv('BZR_COLUMNS', None)
 
2004
        self.overrideEnv('COLUMNS', None)
1986
2005
 
1987
2006
        def terminal_size(w, h):
1988
2007
            return 42, 42
1995
2014
        self.assertEqual(42, osutils.terminal_width())
1996
2015
 
1997
2016
    def test_non_tty_default_without_columns(self):
1998
 
        del os.environ['BZR_COLUMNS']
1999
 
        del os.environ['COLUMNS']
 
2017
        self.overrideEnv('BZR_COLUMNS', None)
 
2018
        self.overrideEnv('COLUMNS', None)
2000
2019
        self.replace_stdout(None)
2001
2020
        self.assertEqual(None, osutils.terminal_width())
2002
2021
 
2010
2029
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2011
2030
            pass
2012
2031
        else:
2013
 
            def restore():
2014
 
                termios.TIOCGWINSZ = orig
2015
 
            self.addCleanup(restore)
 
2032
            self.overrideAttr(termios, 'TIOCGWINSZ')
2016
2033
            del termios.TIOCGWINSZ
2017
 
        del os.environ['BZR_COLUMNS']
2018
 
        del os.environ['COLUMNS']
 
2034
        self.overrideEnv('BZR_COLUMNS', None)
 
2035
        self.overrideEnv('COLUMNS', None)
2019
2036
        # Whatever the result is, if we don't raise an exception, it's ok.
2020
2037
        osutils.terminal_width()
 
2038
 
 
2039
class TestCreationOps(tests.TestCaseInTempDir):
 
2040
    _test_needs_features = [features.chown_feature]
 
2041
 
 
2042
    def setUp(self):
 
2043
        tests.TestCaseInTempDir.setUp(self)
 
2044
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
2045
 
 
2046
        # params set by call to _dummy_chown
 
2047
        self.path = self.uid = self.gid = None
 
2048
 
 
2049
    def _dummy_chown(self, path, uid, gid):
 
2050
        self.path, self.uid, self.gid = path, uid, gid
 
2051
 
 
2052
    def test_copy_ownership_from_path(self):
 
2053
        """copy_ownership_from_path test with specified src."""
 
2054
        ownsrc = '/'
 
2055
        f = open('test_file', 'wt')
 
2056
        osutils.copy_ownership_from_path('test_file', ownsrc)
 
2057
 
 
2058
        s = os.stat(ownsrc)
 
2059
        self.assertEquals(self.path, 'test_file')
 
2060
        self.assertEquals(self.uid, s.st_uid)
 
2061
        self.assertEquals(self.gid, s.st_gid)
 
2062
 
 
2063
    def test_copy_ownership_nonesrc(self):
 
2064
        """copy_ownership_from_path test with src=None."""
 
2065
        f = open('test_file', 'wt')
 
2066
        # should use parent dir for permissions
 
2067
        osutils.copy_ownership_from_path('test_file')
 
2068
 
 
2069
        s = os.stat('..')
 
2070
        self.assertEquals(self.path, 'test_file')
 
2071
        self.assertEquals(self.uid, s.st_uid)
 
2072
        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')