~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Gordon Tyler
  • Date: 2010-01-14 15:24:04 UTC
  • mto: (5037.3.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5046.
  • Revision ID: gordon@doxxx.net-20100114152404-d64ik2afl96lcml0
Reverted changes to test_rules since the original should work now.

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
    errors,
30
30
    osutils,
31
31
    tests,
 
32
    trace,
32
33
    win32utils,
33
34
    )
34
35
from bzrlib.tests import (
52
53
 
53
54
UTF8DirReaderFeature = _UTF8DirReaderFeature()
54
55
 
 
56
term_ios_feature = tests.ModuleAvailableFeature('termios')
 
57
 
55
58
 
56
59
def _already_unicode(s):
57
60
    return s
58
61
 
59
62
 
60
 
def _fs_enc_to_unicode(s):
61
 
    return s.decode(osutils._fs_enc)
62
 
 
63
 
 
64
63
def _utf8_to_unicode(s):
65
64
    return s.decode('UTF-8')
66
65
 
83
82
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
84
83
                               _native_to_unicode=_utf8_to_unicode)))
85
84
 
86
 
    if test__walkdirs_win32.Win32ReadDirFeature.available():
 
85
    if test__walkdirs_win32.win32_readdir_feature.available():
87
86
        try:
88
87
            from bzrlib import _walkdirs_win32
89
 
            # TODO: check on windows, it may be that we need to use/add
90
 
            # safe_unicode instead of _fs_enc_to_unicode
91
88
            scenarios.append(
92
89
                ('win32',
93
90
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
94
 
                      _native_to_unicode=_fs_enc_to_unicode)))
 
91
                      _native_to_unicode=_already_unicode)))
95
92
        except ImportError:
96
93
            pass
97
94
    return scenarios
125
122
 
126
123
class TestRename(tests.TestCaseInTempDir):
127
124
 
 
125
    def create_file(self, filename, content):
 
126
        f = open(filename, 'wb')
 
127
        try:
 
128
            f.write(content)
 
129
        finally:
 
130
            f.close()
 
131
 
 
132
    def _fancy_rename(self, a, b):
 
133
        osutils.fancy_rename(a, b, rename_func=os.rename,
 
134
                             unlink_func=os.unlink)
 
135
 
128
136
    def test_fancy_rename(self):
129
137
        # This should work everywhere
130
 
        def rename(a, b):
131
 
            osutils.fancy_rename(a, b,
132
 
                    rename_func=os.rename,
133
 
                    unlink_func=os.unlink)
134
 
 
135
 
        open('a', 'wb').write('something in a\n')
136
 
        rename('a', 'b')
 
138
        self.create_file('a', 'something in a\n')
 
139
        self._fancy_rename('a', 'b')
137
140
        self.failIfExists('a')
138
141
        self.failUnlessExists('b')
139
142
        self.check_file_contents('b', 'something in a\n')
140
143
 
141
 
        open('a', 'wb').write('new something in a\n')
142
 
        rename('b', 'a')
 
144
        self.create_file('a', 'new something in a\n')
 
145
        self._fancy_rename('b', 'a')
143
146
 
144
147
        self.check_file_contents('a', 'something in a\n')
145
148
 
 
149
    def test_fancy_rename_fails_source_missing(self):
 
150
        # An exception should be raised, and the target should be left in place
 
151
        self.create_file('target', 'data in target\n')
 
152
        self.assertRaises((IOError, OSError), self._fancy_rename,
 
153
                          'missingsource', 'target')
 
154
        self.failUnlessExists('target')
 
155
        self.check_file_contents('target', 'data in target\n')
 
156
 
 
157
    def test_fancy_rename_fails_if_source_and_target_missing(self):
 
158
        self.assertRaises((IOError, OSError), self._fancy_rename,
 
159
                          'missingsource', 'missingtarget')
 
160
 
146
161
    def test_rename(self):
147
162
        # Rename should be semi-atomic on all platforms
148
 
        open('a', 'wb').write('something in a\n')
 
163
        self.create_file('a', 'something in a\n')
149
164
        osutils.rename('a', 'b')
150
165
        self.failIfExists('a')
151
166
        self.failUnlessExists('b')
152
167
        self.check_file_contents('b', 'something in a\n')
153
168
 
154
 
        open('a', 'wb').write('new something in a\n')
 
169
        self.create_file('a', 'new something in a\n')
155
170
        osutils.rename('b', 'a')
156
171
 
157
172
        self.check_file_contents('a', 'something in a\n')
240
255
        self.failIfExists('dir')
241
256
 
242
257
 
 
258
class TestDeleteAny(tests.TestCaseInTempDir):
 
259
 
 
260
    def test_delete_any_readonly(self):
 
261
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
 
262
        self.build_tree(['d/', 'f'])
 
263
        osutils.make_readonly('d')
 
264
        osutils.make_readonly('f')
 
265
 
 
266
        osutils.delete_any('f')
 
267
        osutils.delete_any('d')
 
268
 
 
269
 
243
270
class TestKind(tests.TestCaseInTempDir):
244
271
 
245
272
    def test_file_kind(self):
353
380
        # Instead blackbox.test_locale should check for localized
354
381
        # dates once they do occur in output strings.
355
382
 
 
383
    def test_format_date_with_offset_in_original_timezone(self):
 
384
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
 
385
            osutils.format_date_with_offset_in_original_timezone(0))
 
386
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
 
387
            osutils.format_date_with_offset_in_original_timezone(100000))
 
388
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
 
389
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
 
390
 
356
391
    def test_local_time_offset(self):
357
392
        """Test that local_time_offset() returns a sane value."""
358
393
        offset = osutils.local_time_offset()
434
469
    def test_canonical_relpath_simple(self):
435
470
        f = file('MixedCaseName', 'w')
436
471
        f.close()
437
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
438
 
        real_base_dir = osutils.realpath(self.test_base_dir)
439
 
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
 
472
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
440
473
        self.failUnlessEqual('work/MixedCaseName', actual)
441
474
 
442
475
    def test_canonical_relpath_missing_tail(self):
443
476
        os.mkdir('MixedCaseParent')
444
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
445
 
        real_base_dir = osutils.realpath(self.test_base_dir)
446
 
        actual = osutils.canonical_relpath(real_base_dir,
 
477
        actual = osutils.canonical_relpath(self.test_base_dir,
447
478
                                           'mixedcaseparent/nochild')
448
479
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
449
480
 
450
481
 
 
482
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
 
483
 
 
484
    def assertRelpath(self, expected, base, path):
 
485
        actual = osutils._cicp_canonical_relpath(base, path)
 
486
        self.assertEqual(expected, actual)
 
487
 
 
488
    def test_simple(self):
 
489
        self.build_tree(['MixedCaseName'])
 
490
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
 
491
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
 
492
 
 
493
    def test_subdir_missing_tail(self):
 
494
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
 
495
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
 
496
        self.assertRelpath('MixedCaseParent/a_child', base,
 
497
                           'MixedCaseParent/a_child')
 
498
        self.assertRelpath('MixedCaseParent/a_child', base,
 
499
                           'MixedCaseParent/A_Child')
 
500
        self.assertRelpath('MixedCaseParent/not_child', base,
 
501
                           'MixedCaseParent/not_child')
 
502
 
 
503
    def test_at_root_slash(self):
 
504
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
 
505
        # check...
 
506
        if osutils.MIN_ABS_PATHLENGTH > 1:
 
507
            raise tests.TestSkipped('relpath requires %d chars'
 
508
                                    % osutils.MIN_ABS_PATHLENGTH)
 
509
        self.assertRelpath('foo', '/', '/foo')
 
510
 
 
511
    def test_at_root_drive(self):
 
512
        if sys.platform != 'win32':
 
513
            raise tests.TestNotApplicable('we can only test drive-letter relative'
 
514
                                          ' paths on Windows where we have drive'
 
515
                                          ' letters.')
 
516
        # see bug #322807
 
517
        # The specific issue is that when at the root of a drive, 'abspath'
 
518
        # returns "C:/" or just "/". However, the code assumes that abspath
 
519
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
 
520
        self.assertRelpath('foo', 'C:/', 'C:/foo')
 
521
        self.assertRelpath('foo', 'X:/', 'X:/foo')
 
522
        self.assertRelpath('foo', 'X:/', 'X://foo')
 
523
 
 
524
 
451
525
class TestPumpFile(tests.TestCase):
452
526
    """Test pumpfile method."""
453
527
 
613
687
        self.assertEqual("1234", output.getvalue())
614
688
 
615
689
 
 
690
class TestRelpath(tests.TestCase):
 
691
 
 
692
    def test_simple_relpath(self):
 
693
        cwd = osutils.getcwd()
 
694
        subdir = cwd + '/subdir'
 
695
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
 
696
 
 
697
    def test_deep_relpath(self):
 
698
        cwd = osutils.getcwd()
 
699
        subdir = cwd + '/sub/subsubdir'
 
700
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
 
701
 
 
702
    def test_not_relative(self):
 
703
        self.assertRaises(errors.PathNotChild,
 
704
                          osutils.relpath, 'C:/path', 'H:/path')
 
705
        self.assertRaises(errors.PathNotChild,
 
706
                          osutils.relpath, 'C:/', 'H:/path')
 
707
 
 
708
 
616
709
class TestSafeUnicode(tests.TestCase):
617
710
 
618
711
    def test_from_ascii_string(self):
896
989
 
897
990
    def test_osutils_binding(self):
898
991
        from bzrlib.tests import test__chunks_to_lines
899
 
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
 
992
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
900
993
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
901
994
        else:
902
995
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1088
1181
 
1089
1182
    def test_force_walkdirs_utf8_nt(self):
1090
1183
        # Disabled because the thunk of the whole walkdirs api is disabled.
1091
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1184
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1092
1185
        self._save_platform_info()
1093
1186
        win32utils.winver = 'Windows NT'
1094
1187
        from bzrlib._walkdirs_win32 import Win32ReadDir
1095
1188
        self.assertDirReaderIs(Win32ReadDir)
1096
1189
 
1097
1190
    def test_force_walkdirs_utf8_98(self):
1098
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1191
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1099
1192
        self._save_platform_info()
1100
1193
        win32utils.winver = 'Windows 98'
1101
1194
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1252
1345
        self.assertEqual(expected_dirblocks, result)
1253
1346
 
1254
1347
    def test__walkdirs_utf8_win32readdir(self):
1255
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1348
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1256
1349
        self.requireFeature(tests.UnicodeFilenameFeature)
1257
1350
        from bzrlib._walkdirs_win32 import Win32ReadDir
1258
1351
        self._save_platform_info()
1309
1402
 
1310
1403
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1311
1404
        """make sure our Stat values are valid"""
1312
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1405
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1313
1406
        self.requireFeature(tests.UnicodeFilenameFeature)
1314
1407
        from bzrlib._walkdirs_win32 import Win32ReadDir
1315
1408
        name0u = u'0file-\xb6'
1333
1426
 
1334
1427
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1335
1428
        """make sure our Stat values are valid"""
1336
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1429
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1337
1430
        self.requireFeature(tests.UnicodeFilenameFeature)
1338
1431
        from bzrlib._walkdirs_win32 import Win32ReadDir
1339
1432
        name0u = u'0dir-\u062c\u0648'
1542
1635
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1543
1636
        self.build_tree_contents([('foo', text)])
1544
1637
        expected_sha = osutils.sha_string(text)
1545
 
        f = open('foo')
 
1638
        f = open('foo', 'rb')
1546
1639
        self.addCleanup(f.close)
1547
1640
        size, sha = osutils.size_sha_file(f)
1548
1641
        self.assertEqual(38, size)
1764
1857
 
1765
1858
class TestConcurrency(tests.TestCase):
1766
1859
 
 
1860
    def setUp(self):
 
1861
        super(TestConcurrency, self).setUp()
 
1862
        orig = osutils._cached_local_concurrency
 
1863
        def restore():
 
1864
            osutils._cached_local_concurrency = orig
 
1865
        self.addCleanup(restore)
 
1866
 
1767
1867
    def test_local_concurrency(self):
1768
1868
        concurrency = osutils.local_concurrency()
1769
1869
        self.assertIsInstance(concurrency, int)
 
1870
 
 
1871
    def test_local_concurrency_environment_variable(self):
 
1872
        os.environ['BZR_CONCURRENCY'] = '2'
 
1873
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
 
1874
        os.environ['BZR_CONCURRENCY'] = '3'
 
1875
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
 
1876
        os.environ['BZR_CONCURRENCY'] = 'foo'
 
1877
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
 
1878
 
 
1879
    def test_option_concurrency(self):
 
1880
        os.environ['BZR_CONCURRENCY'] = '1'
 
1881
        self.run_bzr('rocks --concurrency 42')
 
1882
        # Command line overrides envrionment variable
 
1883
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
 
1884
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
 
1885
 
 
1886
 
 
1887
class TestFailedToLoadExtension(tests.TestCase):
 
1888
 
 
1889
    def _try_loading(self):
 
1890
        try:
 
1891
            import bzrlib._fictional_extension_py
 
1892
        except ImportError, e:
 
1893
            osutils.failed_to_load_extension(e)
 
1894
            return True
 
1895
 
 
1896
    def setUp(self):
 
1897
        super(TestFailedToLoadExtension, self).setUp()
 
1898
        self.saved_failures = osutils._extension_load_failures[:]
 
1899
        del osutils._extension_load_failures[:]
 
1900
        self.addCleanup(self.restore_failures)
 
1901
 
 
1902
    def restore_failures(self):
 
1903
        osutils._extension_load_failures = self.saved_failures
 
1904
 
 
1905
    def test_failure_to_load(self):
 
1906
        self._try_loading()
 
1907
        self.assertLength(1, osutils._extension_load_failures)
 
1908
        self.assertEquals(osutils._extension_load_failures[0],
 
1909
            "No module named _fictional_extension_py")
 
1910
 
 
1911
    def test_report_extension_load_failures_no_warning(self):
 
1912
        self.assertTrue(self._try_loading())
 
1913
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
 
1914
        # it used to give a Python warning; it no longer does
 
1915
        self.assertLength(0, warnings)
 
1916
 
 
1917
    def test_report_extension_load_failures_message(self):
 
1918
        log = StringIO()
 
1919
        trace.push_log_file(log)
 
1920
        self.assertTrue(self._try_loading())
 
1921
        osutils.report_extension_load_failures()
 
1922
        self.assertContainsRe(
 
1923
            log.getvalue(),
 
1924
            r"bzr: warning: some compiled extensions could not be loaded; "
 
1925
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
 
1926
            )
 
1927
 
 
1928
 
 
1929
class TestTerminalWidth(tests.TestCase):
 
1930
 
 
1931
    def replace_stdout(self, new):
 
1932
        orig_stdout = sys.stdout
 
1933
        def restore():
 
1934
            sys.stdout = orig_stdout
 
1935
        self.addCleanup(restore)
 
1936
        sys.stdout = new
 
1937
 
 
1938
    def replace__terminal_size(self, new):
 
1939
        orig__terminal_size = osutils._terminal_size
 
1940
        def restore():
 
1941
            osutils._terminal_size = orig__terminal_size
 
1942
        self.addCleanup(restore)
 
1943
        osutils._terminal_size = new
 
1944
 
 
1945
    def set_fake_tty(self):
 
1946
 
 
1947
        class I_am_a_tty(object):
 
1948
            def isatty(self):
 
1949
                return True
 
1950
 
 
1951
        self.replace_stdout(I_am_a_tty())
 
1952
 
 
1953
    def test_default_values(self):
 
1954
        self.assertEqual(80, osutils.default_terminal_width)
 
1955
 
 
1956
    def test_defaults_to_BZR_COLUMNS(self):
 
1957
        # BZR_COLUMNS is set by the test framework
 
1958
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
 
1959
        os.environ['BZR_COLUMNS'] = '12'
 
1960
        self.assertEqual(12, osutils.terminal_width())
 
1961
 
 
1962
    def test_falls_back_to_COLUMNS(self):
 
1963
        del os.environ['BZR_COLUMNS']
 
1964
        self.assertNotEqual('42', os.environ['COLUMNS'])
 
1965
        self.set_fake_tty()
 
1966
        os.environ['COLUMNS'] = '42'
 
1967
        self.assertEqual(42, osutils.terminal_width())
 
1968
 
 
1969
    def test_tty_default_without_columns(self):
 
1970
        del os.environ['BZR_COLUMNS']
 
1971
        del os.environ['COLUMNS']
 
1972
 
 
1973
        def terminal_size(w, h):
 
1974
            return 42, 42
 
1975
 
 
1976
        self.set_fake_tty()
 
1977
        # We need to override the osutils definition as it depends on the
 
1978
        # running environment that we can't control (PQM running without a
 
1979
        # controlling terminal is one example).
 
1980
        self.replace__terminal_size(terminal_size)
 
1981
        self.assertEqual(42, osutils.terminal_width())
 
1982
 
 
1983
    def test_non_tty_default_without_columns(self):
 
1984
        del os.environ['BZR_COLUMNS']
 
1985
        del os.environ['COLUMNS']
 
1986
        self.replace_stdout(None)
 
1987
        self.assertEqual(None, osutils.terminal_width())
 
1988
 
 
1989
    def test_no_TIOCGWINSZ(self):
 
1990
        self.requireFeature(term_ios_feature)
 
1991
        termios = term_ios_feature.module
 
1992
        # bug 63539 is about a termios without TIOCGWINSZ attribute
 
1993
        try:
 
1994
            orig = termios.TIOCGWINSZ
 
1995
        except AttributeError:
 
1996
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
 
1997
            pass
 
1998
        else:
 
1999
            def restore():
 
2000
                termios.TIOCGWINSZ = orig
 
2001
            self.addCleanup(restore)
 
2002
            del termios.TIOCGWINSZ
 
2003
        del os.environ['BZR_COLUMNS']
 
2004
        del os.environ['COLUMNS']
 
2005
        # Whatever the result is, if we don't raise an exception, it's ok.
 
2006
        osutils.terminal_width()