/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: Jonathan Lange
  • Date: 2009-12-09 09:20:42 UTC
  • mfrom: (4881 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4907.
  • Revision ID: jml@canonical.com-20091209092042-s2zgqcf8f39yzxpj
Merge trunk.

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
TermIOSFeature = 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
 
86
85
    if test__walkdirs_win32.Win32ReadDirFeature.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')
365
380
        # Instead blackbox.test_locale should check for localized
366
381
        # dates once they do occur in output strings.
367
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
 
368
391
    def test_local_time_offset(self):
369
392
        """Test that local_time_offset() returns a sane value."""
370
393
        offset = osutils.local_time_offset()
446
469
    def test_canonical_relpath_simple(self):
447
470
        f = file('MixedCaseName', 'w')
448
471
        f.close()
449
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
450
 
        real_base_dir = osutils.realpath(self.test_base_dir)
451
 
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
 
472
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
452
473
        self.failUnlessEqual('work/MixedCaseName', actual)
453
474
 
454
475
    def test_canonical_relpath_missing_tail(self):
455
476
        os.mkdir('MixedCaseParent')
456
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
457
 
        real_base_dir = osutils.realpath(self.test_base_dir)
458
 
        actual = osutils.canonical_relpath(real_base_dir,
 
477
        actual = osutils.canonical_relpath(self.test_base_dir,
459
478
                                           'mixedcaseparent/nochild')
460
479
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
461
480
 
462
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
 
463
525
class TestPumpFile(tests.TestCase):
464
526
    """Test pumpfile method."""
465
527
 
625
687
        self.assertEqual("1234", output.getvalue())
626
688
 
627
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
 
628
709
class TestSafeUnicode(tests.TestCase):
629
710
 
630
711
    def test_from_ascii_string(self):
1554
1635
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1555
1636
        self.build_tree_contents([('foo', text)])
1556
1637
        expected_sha = osutils.sha_string(text)
1557
 
        f = open('foo')
 
1638
        f = open('foo', 'rb')
1558
1639
        self.addCleanup(f.close)
1559
1640
        size, sha = osutils.size_sha_file(f)
1560
1641
        self.assertEqual(38, size)
1776
1857
 
1777
1858
class TestConcurrency(tests.TestCase):
1778
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
 
1779
1867
    def test_local_concurrency(self):
1780
1868
        concurrency = osutils.local_concurrency()
1781
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 test_default_values(self):
 
1932
        self.assertEquals(80, osutils.default_terminal_width)
 
1933
 
 
1934
    def test_defaults_to_BZR_COLUMNS(self):
 
1935
        # BZR_COLUMNS is set by the test framework
 
1936
        self.assertEquals('80', os.environ['BZR_COLUMNS'])
 
1937
        os.environ['BZR_COLUMNS'] = '12'
 
1938
        self.assertEquals(12, osutils.terminal_width())
 
1939
 
 
1940
    def test_tty_default_without_columns(self):
 
1941
        del os.environ['BZR_COLUMNS']
 
1942
        del os.environ['COLUMNS']
 
1943
        orig_stdout = sys.stdout
 
1944
        def restore():
 
1945
            sys.stdout = orig_stdout
 
1946
        self.addCleanup(restore)
 
1947
 
 
1948
        class I_am_a_tty(object):
 
1949
            def isatty(self):
 
1950
                return True
 
1951
 
 
1952
        sys.stdout = I_am_a_tty()
 
1953
        self.assertEquals(None, osutils.terminal_width())
 
1954
 
 
1955
    def test_non_tty_default_without_columns(self):
 
1956
        del os.environ['BZR_COLUMNS']
 
1957
        del os.environ['COLUMNS']
 
1958
        orig_stdout = sys.stdout
 
1959
        def restore():
 
1960
            sys.stdout = orig_stdout
 
1961
        self.addCleanup(restore)
 
1962
        sys.stdout = None
 
1963
        self.assertEquals(None, osutils.terminal_width())
 
1964
 
 
1965
    def test_no_TIOCGWINSZ(self):
 
1966
        self.requireFeature(TermIOSFeature)
 
1967
        termios = TermIOSFeature.module
 
1968
        # bug 63539 is about a termios without TIOCGWINSZ attribute
 
1969
        try:
 
1970
            orig = termios.TIOCGWINSZ
 
1971
        except AttributeError:
 
1972
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
 
1973
            pass
 
1974
        else:
 
1975
            def restore():
 
1976
                termios.TIOCGWINSZ = orig
 
1977
            self.addCleanup(restore)
 
1978
            del termios.TIOCGWINSZ
 
1979
        del os.environ['BZR_COLUMNS']
 
1980
        del os.environ['COLUMNS']
 
1981
        self.assertIs(None, osutils.terminal_width())