~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Andrew Bennetts
  • Date: 2009-08-07 04:17:51 UTC
  • mto: This revision was merged to the branch mainline in revision 4608.
  • Revision ID: andrew.bennetts@canonical.com-20090807041751-0vhb0y0g7k49hr45
Review comments from John.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
 
    trace,
34
32
    win32utils,
35
33
    )
36
34
from bzrlib.tests import (
37
 
    features,
38
35
    file_utils,
39
36
    test__walkdirs_win32,
40
37
    )
41
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
38
 
43
39
 
44
40
class _UTF8DirReaderFeature(tests.Feature):
56
52
 
57
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
58
54
 
59
 
term_ios_feature = tests.ModuleAvailableFeature('termios')
60
 
 
61
55
 
62
56
def _already_unicode(s):
63
57
    return s
64
58
 
65
59
 
 
60
def _fs_enc_to_unicode(s):
 
61
    return s.decode(osutils._fs_enc)
 
62
 
 
63
 
66
64
def _utf8_to_unicode(s):
67
65
    return s.decode('UTF-8')
68
66
 
85
83
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
86
84
                               _native_to_unicode=_utf8_to_unicode)))
87
85
 
88
 
    if test__walkdirs_win32.win32_readdir_feature.available():
 
86
    if test__walkdirs_win32.Win32ReadDirFeature.available():
89
87
        try:
90
88
            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
91
            scenarios.append(
92
92
                ('win32',
93
93
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
94
 
                      _native_to_unicode=_already_unicode)))
 
94
                      _native_to_unicode=_fs_enc_to_unicode)))
95
95
        except ImportError:
96
96
            pass
97
97
    return scenarios
98
98
 
99
99
 
100
 
load_tests = load_tests_apply_scenarios
 
100
def load_tests(basic_tests, module, loader):
 
101
    suite = loader.suiteClass()
 
102
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
 
103
        basic_tests, tests.condition_isinstance(TestDirReader))
 
104
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
 
105
    suite.addTest(remaining_tests)
 
106
    return suite
101
107
 
102
108
 
103
109
class TestContainsWhitespace(tests.TestCase):
104
110
 
105
111
    def test_contains_whitespace(self):
106
 
        self.assertTrue(osutils.contains_whitespace(u' '))
107
 
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
108
 
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
109
 
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
110
 
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
111
 
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
 
112
        self.failUnless(osutils.contains_whitespace(u' '))
 
113
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
114
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
115
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
116
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
117
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
112
118
 
113
119
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
114
120
        # is whitespace, but we do not.
115
 
        self.assertFalse(osutils.contains_whitespace(u''))
116
 
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
117
 
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
 
121
        self.failIf(osutils.contains_whitespace(u''))
 
122
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
123
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
118
124
 
119
125
 
120
126
class TestRename(tests.TestCaseInTempDir):
121
127
 
122
 
    def create_file(self, filename, content):
123
 
        f = open(filename, 'wb')
124
 
        try:
125
 
            f.write(content)
126
 
        finally:
127
 
            f.close()
128
 
 
129
 
    def _fancy_rename(self, a, b):
130
 
        osutils.fancy_rename(a, b, rename_func=os.rename,
131
 
                             unlink_func=os.unlink)
132
 
 
133
128
    def test_fancy_rename(self):
134
129
        # This should work everywhere
135
 
        self.create_file('a', 'something in a\n')
136
 
        self._fancy_rename('a', 'b')
137
 
        self.assertPathDoesNotExist('a')
138
 
        self.assertPathExists('b')
 
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')
 
137
        self.failIfExists('a')
 
138
        self.failUnlessExists('b')
139
139
        self.check_file_contents('b', 'something in a\n')
140
140
 
141
 
        self.create_file('a', 'new something in a\n')
142
 
        self._fancy_rename('b', 'a')
 
141
        open('a', 'wb').write('new something in a\n')
 
142
        rename('b', 'a')
143
143
 
144
144
        self.check_file_contents('a', 'something in a\n')
145
145
 
146
 
    def test_fancy_rename_fails_source_missing(self):
147
 
        # An exception should be raised, and the target should be left in place
148
 
        self.create_file('target', 'data in target\n')
149
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
150
 
                          'missingsource', 'target')
151
 
        self.assertPathExists('target')
152
 
        self.check_file_contents('target', 'data in target\n')
153
 
 
154
 
    def test_fancy_rename_fails_if_source_and_target_missing(self):
155
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
156
 
                          'missingsource', 'missingtarget')
157
 
 
158
146
    def test_rename(self):
159
147
        # Rename should be semi-atomic on all platforms
160
 
        self.create_file('a', 'something in a\n')
 
148
        open('a', 'wb').write('something in a\n')
161
149
        osutils.rename('a', 'b')
162
 
        self.assertPathDoesNotExist('a')
163
 
        self.assertPathExists('b')
 
150
        self.failIfExists('a')
 
151
        self.failUnlessExists('b')
164
152
        self.check_file_contents('b', 'something in a\n')
165
153
 
166
 
        self.create_file('a', 'new something in a\n')
 
154
        open('a', 'wb').write('new something in a\n')
167
155
        osutils.rename('b', 'a')
168
156
 
169
157
        self.check_file_contents('a', 'something in a\n')
231
219
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
232
220
 
233
221
 
234
 
class TestLstat(tests.TestCaseInTempDir):
235
 
 
236
 
    def test_lstat_matches_fstat(self):
237
 
        # On Windows, lstat and fstat don't always agree, primarily in the
238
 
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
239
 
        # custom implementation.
240
 
        if sys.platform == 'win32':
241
 
            # We only have special lstat/fstat if we have the extension.
242
 
            # Without it, we may end up re-reading content when we don't have
243
 
            # to, but otherwise it doesn't effect correctness.
244
 
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
245
 
        f = open('test-file.txt', 'wb')
246
 
        self.addCleanup(f.close)
247
 
        f.write('some content\n')
248
 
        f.flush()
249
 
        self.assertEqualStat(osutils.fstat(f.fileno()),
250
 
                             osutils.lstat('test-file.txt'))
251
 
 
252
 
 
253
222
class TestRmTree(tests.TestCaseInTempDir):
254
223
 
255
224
    def test_rmtree(self):
267
236
 
268
237
        osutils.rmtree('dir')
269
238
 
270
 
        self.assertPathDoesNotExist('dir/file')
271
 
        self.assertPathDoesNotExist('dir')
 
239
        self.failIfExists('dir/file')
 
240
        self.failIfExists('dir')
272
241
 
273
242
 
274
243
class TestDeleteAny(tests.TestCaseInTempDir):
325
294
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
326
295
        self.assertEqual("@", osutils.kind_marker("symlink"))
327
296
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
328
 
        self.assertEqual("", osutils.kind_marker("fifo"))
329
 
        self.assertEqual("", osutils.kind_marker("socket"))
330
 
        self.assertEqual("", osutils.kind_marker("unknown"))
 
297
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
331
298
 
332
299
 
333
300
class TestUmask(tests.TestCaseInTempDir):
398
365
        # Instead blackbox.test_locale should check for localized
399
366
        # dates once they do occur in output strings.
400
367
 
401
 
    def test_format_date_with_offset_in_original_timezone(self):
402
 
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
403
 
            osutils.format_date_with_offset_in_original_timezone(0))
404
 
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
405
 
            osutils.format_date_with_offset_in_original_timezone(100000))
406
 
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
407
 
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
408
 
 
409
368
    def test_local_time_offset(self):
410
369
        """Test that local_time_offset() returns a sane value."""
411
370
        offset = osutils.local_time_offset()
487
446
    def test_canonical_relpath_simple(self):
488
447
        f = file('MixedCaseName', 'w')
489
448
        f.close()
490
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
491
 
        self.assertEqual('work/MixedCaseName', actual)
 
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')
 
452
        self.failUnlessEqual('work/MixedCaseName', actual)
492
453
 
493
454
    def test_canonical_relpath_missing_tail(self):
494
455
        os.mkdir('MixedCaseParent')
495
 
        actual = osutils.canonical_relpath(self.test_base_dir,
 
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,
496
459
                                           'mixedcaseparent/nochild')
497
 
        self.assertEqual('work/MixedCaseParent/nochild', actual)
498
 
 
499
 
 
500
 
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
501
 
 
502
 
    def assertRelpath(self, expected, base, path):
503
 
        actual = osutils._cicp_canonical_relpath(base, path)
504
 
        self.assertEqual(expected, actual)
505
 
 
506
 
    def test_simple(self):
507
 
        self.build_tree(['MixedCaseName'])
508
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
509
 
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
510
 
 
511
 
    def test_subdir_missing_tail(self):
512
 
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
513
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
514
 
        self.assertRelpath('MixedCaseParent/a_child', base,
515
 
                           'MixedCaseParent/a_child')
516
 
        self.assertRelpath('MixedCaseParent/a_child', base,
517
 
                           'MixedCaseParent/A_Child')
518
 
        self.assertRelpath('MixedCaseParent/not_child', base,
519
 
                           'MixedCaseParent/not_child')
520
 
 
521
 
    def test_at_root_slash(self):
522
 
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
523
 
        # check...
524
 
        if osutils.MIN_ABS_PATHLENGTH > 1:
525
 
            raise tests.TestSkipped('relpath requires %d chars'
526
 
                                    % osutils.MIN_ABS_PATHLENGTH)
527
 
        self.assertRelpath('foo', '/', '/foo')
528
 
 
529
 
    def test_at_root_drive(self):
530
 
        if sys.platform != 'win32':
531
 
            raise tests.TestNotApplicable('we can only test drive-letter relative'
532
 
                                          ' paths on Windows where we have drive'
533
 
                                          ' letters.')
534
 
        # see bug #322807
535
 
        # The specific issue is that when at the root of a drive, 'abspath'
536
 
        # returns "C:/" or just "/". However, the code assumes that abspath
537
 
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
538
 
        self.assertRelpath('foo', 'C:/', 'C:/foo')
539
 
        self.assertRelpath('foo', 'X:/', 'X:/foo')
540
 
        self.assertRelpath('foo', 'X:/', 'X://foo')
 
460
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
541
461
 
542
462
 
543
463
class TestPumpFile(tests.TestCase):
876
796
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
877
797
        # relative path
878
798
        cwd = osutils.getcwd().rstrip('/')
879
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
799
        drive = osutils._nt_splitdrive(cwd)[0]
880
800
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
881
801
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
882
802
        # unicode path
924
844
        b.close()
925
845
 
926
846
        osutils._win32_rename('b', 'a')
927
 
        self.assertPathExists('a')
928
 
        self.assertPathDoesNotExist('b')
 
847
        self.failUnlessExists('a')
 
848
        self.failIfExists('b')
929
849
        self.assertFileEqual('baz\n', 'a')
930
850
 
931
851
    def test_rename_missing_file(self):
1007
927
 
1008
928
    def test_osutils_binding(self):
1009
929
        from bzrlib.tests import test__chunks_to_lines
1010
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
 
930
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
1011
931
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1012
932
        else:
1013
933
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1079
999
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1080
1000
 
1081
1001
    def test_walkdirs_os_error(self):
1082
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
1002
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1083
1003
        # Pyrex readdir didn't raise useful messages if it had an error
1084
1004
        # reading the directory
1085
1005
        if sys.platform == 'win32':
1086
1006
            raise tests.TestNotApplicable(
1087
1007
                "readdir IOError not tested on win32")
1088
 
        self.requireFeature(features.not_running_as_root)
1089
1008
        os.mkdir("test-unreadable")
1090
1009
        os.chmod("test-unreadable", 0000)
1091
1010
        # must chmod it back so that it can be removed
1099
1018
        # Ensure the message contains the file name
1100
1019
        self.assertContainsRe(str(e), "\./test-unreadable")
1101
1020
 
1102
 
 
1103
 
    def test_walkdirs_encoding_error(self):
1104
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1105
 
        # walkdirs didn't raise a useful message when the filenames
1106
 
        # are not using the filesystem's encoding
1107
 
 
1108
 
        # require a bytestring based filesystem
1109
 
        self.requireFeature(tests.ByteStringNamedFilesystem)
1110
 
 
1111
 
        tree = [
1112
 
            '.bzr',
1113
 
            '0file',
1114
 
            '1dir/',
1115
 
            '1dir/0file',
1116
 
            '1dir/1dir/',
1117
 
            '1file'
1118
 
            ]
1119
 
 
1120
 
        self.build_tree(tree)
1121
 
 
1122
 
        # rename the 1file to a latin-1 filename
1123
 
        os.rename("./1file", "\xe8file")
1124
 
        if "\xe8file" not in os.listdir("."):
1125
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1126
 
 
1127
 
        self._save_platform_info()
1128
 
        win32utils.winver = None # Avoid the win32 detection code
1129
 
        osutils._fs_enc = 'UTF-8'
1130
 
 
1131
 
        # this should raise on error
1132
 
        def attempt():
1133
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1134
 
                pass
1135
 
 
1136
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1137
 
 
1138
1021
    def test__walkdirs_utf8(self):
1139
1022
        tree = [
1140
1023
            '.bzr',
1190
1073
            dirblock[:] = new_dirblock
1191
1074
 
1192
1075
    def _save_platform_info(self):
1193
 
        self.overrideAttr(win32utils, 'winver')
1194
 
        self.overrideAttr(osutils, '_fs_enc')
1195
 
        self.overrideAttr(osutils, '_selected_dir_reader')
 
1076
        cur_winver = win32utils.winver
 
1077
        cur_fs_enc = osutils._fs_enc
 
1078
        cur_dir_reader = osutils._selected_dir_reader
 
1079
        def restore():
 
1080
            win32utils.winver = cur_winver
 
1081
            osutils._fs_enc = cur_fs_enc
 
1082
            osutils._selected_dir_reader = cur_dir_reader
 
1083
        self.addCleanup(restore)
1196
1084
 
1197
1085
    def assertDirReaderIs(self, expected):
1198
1086
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1231
1119
 
1232
1120
    def test_force_walkdirs_utf8_nt(self):
1233
1121
        # Disabled because the thunk of the whole walkdirs api is disabled.
1234
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1122
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1235
1123
        self._save_platform_info()
1236
1124
        win32utils.winver = 'Windows NT'
1237
1125
        from bzrlib._walkdirs_win32 import Win32ReadDir
1238
1126
        self.assertDirReaderIs(Win32ReadDir)
1239
1127
 
1240
1128
    def test_force_walkdirs_utf8_98(self):
1241
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1129
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1242
1130
        self._save_platform_info()
1243
1131
        win32utils.winver = 'Windows 98'
1244
1132
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1395
1283
        self.assertEqual(expected_dirblocks, result)
1396
1284
 
1397
1285
    def test__walkdirs_utf8_win32readdir(self):
1398
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1286
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1399
1287
        self.requireFeature(tests.UnicodeFilenameFeature)
1400
1288
        from bzrlib._walkdirs_win32 import Win32ReadDir
1401
1289
        self._save_platform_info()
1452
1340
 
1453
1341
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1454
1342
        """make sure our Stat values are valid"""
1455
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1343
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1456
1344
        self.requireFeature(tests.UnicodeFilenameFeature)
1457
1345
        from bzrlib._walkdirs_win32 import Win32ReadDir
1458
1346
        name0u = u'0file-\xb6'
1476
1364
 
1477
1365
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1478
1366
        """make sure our Stat values are valid"""
1479
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1367
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1480
1368
        self.requireFeature(tests.UnicodeFilenameFeature)
1481
1369
        from bzrlib._walkdirs_win32 import Win32ReadDir
1482
1370
        name0u = u'0dir-\u062c\u0648'
1614
1502
                          ('d', 'source/b', 'target/b'),
1615
1503
                          ('f', 'source/b/c', 'target/b/c'),
1616
1504
                         ], processed_files)
1617
 
        self.assertPathDoesNotExist('target')
 
1505
        self.failIfExists('target')
1618
1506
        if osutils.has_symlinks():
1619
1507
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1620
1508
 
1631
1519
        def cleanup():
1632
1520
            if 'BZR_TEST_ENV_VAR' in os.environ:
1633
1521
                del os.environ['BZR_TEST_ENV_VAR']
 
1522
 
1634
1523
        self.addCleanup(cleanup)
1635
1524
 
1636
1525
    def test_set(self):
1666
1555
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1667
1556
        self.assertEqual('foo', old)
1668
1557
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1669
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
 
1558
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1670
1559
 
1671
1560
 
1672
1561
class TestSizeShaFile(tests.TestCaseInTempDir):
1684
1573
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1685
1574
        self.build_tree_contents([('foo', text)])
1686
1575
        expected_sha = osutils.sha_string(text)
1687
 
        f = open('foo', 'rb')
 
1576
        f = open('foo')
1688
1577
        self.addCleanup(f.close)
1689
1578
        size, sha = osutils.size_sha_file(f)
1690
1579
        self.assertEqual(38, size)
1723
1612
 
1724
1613
class TestReCompile(tests.TestCase):
1725
1614
 
1726
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1727
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1728
 
            osutils.re_compile_checked, *args, **kwargs)
1729
 
 
1730
1615
    def test_re_compile_checked(self):
1731
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1616
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1732
1617
        self.assertTrue(r.match('aaaa'))
1733
1618
        self.assertTrue(r.match('aAaA'))
1734
1619
 
1735
1620
    def test_re_compile_checked_error(self):
1736
1621
        # like https://bugs.launchpad.net/bzr/+bug/251352
1737
 
 
1738
 
        # Due to possible test isolation error, re.compile is not lazy at
1739
 
        # this point. We re-install lazy compile.
1740
 
        lazy_regex.install_lazy_compile()
1741
1622
        err = self.assertRaises(
1742
1623
            errors.BzrCommandError,
1743
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1624
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1744
1625
        self.assertEqual(
1745
 
            'Invalid regular expression in test case: '
1746
 
            '"*" nothing to repeat',
 
1626
            "Invalid regular expression in test case: '*': "
 
1627
            "nothing to repeat",
1747
1628
            str(err))
1748
1629
 
1749
1630
 
1750
1631
class TestDirReader(tests.TestCaseInTempDir):
1751
1632
 
1752
 
    scenarios = dir_reader_scenarios()
1753
 
 
1754
1633
    # Set by load_tests
1755
1634
    _dir_reader_class = None
1756
1635
    _native_to_unicode = None
1757
1636
 
1758
1637
    def setUp(self):
1759
1638
        tests.TestCaseInTempDir.setUp(self)
1760
 
        self.overrideAttr(osutils,
1761
 
                          '_selected_dir_reader', self._dir_reader_class())
 
1639
 
 
1640
        # Save platform specific info and reset it
 
1641
        cur_dir_reader = osutils._selected_dir_reader
 
1642
 
 
1643
        def restore():
 
1644
            osutils._selected_dir_reader = cur_dir_reader
 
1645
        self.addCleanup(restore)
 
1646
 
 
1647
        osutils._selected_dir_reader = self._dir_reader_class()
1762
1648
 
1763
1649
    def _get_ascii_tree(self):
1764
1650
        tree = [
1897
1783
        os.symlink(self.target, self.link)
1898
1784
 
1899
1785
    def test_os_readlink_link_encoding(self):
1900
 
        self.assertEquals(self.target,  os.readlink(self.link))
 
1786
        if sys.version_info < (2, 6):
 
1787
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
 
1788
        else:
 
1789
            self.assertEquals(self.target,  os.readlink(self.link))
1901
1790
 
1902
1791
    def test_os_readlink_link_decoding(self):
1903
1792
        self.assertEquals(self.target.encode(osutils._fs_enc),
1906
1795
 
1907
1796
class TestConcurrency(tests.TestCase):
1908
1797
 
1909
 
    def setUp(self):
1910
 
        super(TestConcurrency, self).setUp()
1911
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
1912
 
 
1913
1798
    def test_local_concurrency(self):
1914
1799
        concurrency = osutils.local_concurrency()
1915
1800
        self.assertIsInstance(concurrency, int)
1916
 
 
1917
 
    def test_local_concurrency_environment_variable(self):
1918
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
1919
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1920
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
1921
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1922
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
1923
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1924
 
 
1925
 
    def test_option_concurrency(self):
1926
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
1927
 
        self.run_bzr('rocks --concurrency 42')
1928
 
        # Command line overrides environment variable
1929
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1930
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1931
 
 
1932
 
 
1933
 
class TestFailedToLoadExtension(tests.TestCase):
1934
 
 
1935
 
    def _try_loading(self):
1936
 
        try:
1937
 
            import bzrlib._fictional_extension_py
1938
 
        except ImportError, e:
1939
 
            osutils.failed_to_load_extension(e)
1940
 
            return True
1941
 
 
1942
 
    def setUp(self):
1943
 
        super(TestFailedToLoadExtension, self).setUp()
1944
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
1945
 
 
1946
 
    def test_failure_to_load(self):
1947
 
        self._try_loading()
1948
 
        self.assertLength(1, osutils._extension_load_failures)
1949
 
        self.assertEquals(osutils._extension_load_failures[0],
1950
 
            "No module named _fictional_extension_py")
1951
 
 
1952
 
    def test_report_extension_load_failures_no_warning(self):
1953
 
        self.assertTrue(self._try_loading())
1954
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1955
 
        # it used to give a Python warning; it no longer does
1956
 
        self.assertLength(0, warnings)
1957
 
 
1958
 
    def test_report_extension_load_failures_message(self):
1959
 
        log = StringIO()
1960
 
        trace.push_log_file(log)
1961
 
        self.assertTrue(self._try_loading())
1962
 
        osutils.report_extension_load_failures()
1963
 
        self.assertContainsRe(
1964
 
            log.getvalue(),
1965
 
            r"bzr: warning: some compiled extensions could not be loaded; "
1966
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1967
 
            )
1968
 
 
1969
 
 
1970
 
class TestTerminalWidth(tests.TestCase):
1971
 
 
1972
 
    def setUp(self):
1973
 
        tests.TestCase.setUp(self)
1974
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1975
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1976
 
        self.addCleanup(self.restore_osutils_globals)
1977
 
        osutils._terminal_size_state = 'no_data'
1978
 
        osutils._first_terminal_size = None
1979
 
 
1980
 
    def restore_osutils_globals(self):
1981
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1982
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1983
 
 
1984
 
    def replace_stdout(self, new):
1985
 
        self.overrideAttr(sys, 'stdout', new)
1986
 
 
1987
 
    def replace__terminal_size(self, new):
1988
 
        self.overrideAttr(osutils, '_terminal_size', new)
1989
 
 
1990
 
    def set_fake_tty(self):
1991
 
 
1992
 
        class I_am_a_tty(object):
1993
 
            def isatty(self):
1994
 
                return True
1995
 
 
1996
 
        self.replace_stdout(I_am_a_tty())
1997
 
 
1998
 
    def test_default_values(self):
1999
 
        self.assertEqual(80, osutils.default_terminal_width)
2000
 
 
2001
 
    def test_defaults_to_BZR_COLUMNS(self):
2002
 
        # BZR_COLUMNS is set by the test framework
2003
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2004
 
        self.overrideEnv('BZR_COLUMNS', '12')
2005
 
        self.assertEqual(12, osutils.terminal_width())
2006
 
 
2007
 
    def test_BZR_COLUMNS_0_no_limit(self):
2008
 
        self.overrideEnv('BZR_COLUMNS', '0')
2009
 
        self.assertEqual(None, osutils.terminal_width())
2010
 
 
2011
 
    def test_falls_back_to_COLUMNS(self):
2012
 
        self.overrideEnv('BZR_COLUMNS', None)
2013
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
2014
 
        self.set_fake_tty()
2015
 
        self.overrideEnv('COLUMNS', '42')
2016
 
        self.assertEqual(42, osutils.terminal_width())
2017
 
 
2018
 
    def test_tty_default_without_columns(self):
2019
 
        self.overrideEnv('BZR_COLUMNS', None)
2020
 
        self.overrideEnv('COLUMNS', None)
2021
 
 
2022
 
        def terminal_size(w, h):
2023
 
            return 42, 42
2024
 
 
2025
 
        self.set_fake_tty()
2026
 
        # We need to override the osutils definition as it depends on the
2027
 
        # running environment that we can't control (PQM running without a
2028
 
        # controlling terminal is one example).
2029
 
        self.replace__terminal_size(terminal_size)
2030
 
        self.assertEqual(42, osutils.terminal_width())
2031
 
 
2032
 
    def test_non_tty_default_without_columns(self):
2033
 
        self.overrideEnv('BZR_COLUMNS', None)
2034
 
        self.overrideEnv('COLUMNS', None)
2035
 
        self.replace_stdout(None)
2036
 
        self.assertEqual(None, osutils.terminal_width())
2037
 
 
2038
 
    def test_no_TIOCGWINSZ(self):
2039
 
        self.requireFeature(term_ios_feature)
2040
 
        termios = term_ios_feature.module
2041
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2042
 
        try:
2043
 
            orig = termios.TIOCGWINSZ
2044
 
        except AttributeError:
2045
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2046
 
            pass
2047
 
        else:
2048
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2049
 
            del termios.TIOCGWINSZ
2050
 
        self.overrideEnv('BZR_COLUMNS', None)
2051
 
        self.overrideEnv('COLUMNS', None)
2052
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2053
 
        osutils.terminal_width()
2054
 
 
2055
 
 
2056
 
class TestCreationOps(tests.TestCaseInTempDir):
2057
 
    _test_needs_features = [features.chown_feature]
2058
 
 
2059
 
    def setUp(self):
2060
 
        tests.TestCaseInTempDir.setUp(self)
2061
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2062
 
 
2063
 
        # params set by call to _dummy_chown
2064
 
        self.path = self.uid = self.gid = None
2065
 
 
2066
 
    def _dummy_chown(self, path, uid, gid):
2067
 
        self.path, self.uid, self.gid = path, uid, gid
2068
 
 
2069
 
    def test_copy_ownership_from_path(self):
2070
 
        """copy_ownership_from_path test with specified src."""
2071
 
        ownsrc = '/'
2072
 
        f = open('test_file', 'wt')
2073
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2074
 
 
2075
 
        s = os.stat(ownsrc)
2076
 
        self.assertEquals(self.path, 'test_file')
2077
 
        self.assertEquals(self.uid, s.st_uid)
2078
 
        self.assertEquals(self.gid, s.st_gid)
2079
 
 
2080
 
    def test_copy_ownership_nonesrc(self):
2081
 
        """copy_ownership_from_path test with src=None."""
2082
 
        f = open('test_file', 'wt')
2083
 
        # should use parent dir for permissions
2084
 
        osutils.copy_ownership_from_path('test_file')
2085
 
 
2086
 
        s = os.stat('..')
2087
 
        self.assertEquals(self.path, 'test_file')
2088
 
        self.assertEquals(self.uid, s.st_uid)
2089
 
        self.assertEquals(self.gid, s.st_gid)
2090
 
 
2091
 
 
2092
 
class TestGetuserUnicode(tests.TestCase):
2093
 
 
2094
 
    def test_ascii_user(self):
2095
 
        self.overrideEnv('LOGNAME', 'jrandom')
2096
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2097
 
 
2098
 
    def test_unicode_user(self):
2099
 
        ue = osutils.get_user_encoding()
2100
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2101
 
        if uni_val is None:
2102
 
            raise tests.TestSkipped(
2103
 
                'Cannot find a unicode character that works in encoding %s'
2104
 
                % (osutils.get_user_encoding(),))
2105
 
        uni_username = u'jrandom' + uni_val
2106
 
        encoded_username = uni_username.encode(ue)
2107
 
        self.overrideEnv('LOGNAME', encoded_username)
2108
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2109
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
2110
 
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
2111
 
 
2112
 
    def test_no_username_bug_660174(self):
2113
 
        self.requireFeature(features.win32_feature)
2114
 
        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
2115
 
            self.overrideEnv(name, None)
2116
 
        self.assertEqual(u'UNKNOWN', osutils.getuser_unicode())
2117
 
 
2118
 
 
2119
 
class TestBackupNames(tests.TestCase):
2120
 
 
2121
 
    def setUp(self):
2122
 
        super(TestBackupNames, self).setUp()
2123
 
        self.backups = []
2124
 
 
2125
 
    def backup_exists(self, name):
2126
 
        return name in self.backups
2127
 
 
2128
 
    def available_backup_name(self, name):
2129
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2130
 
        self.backups.append(backup_name)
2131
 
        return backup_name
2132
 
 
2133
 
    def assertBackupName(self, expected, name):
2134
 
        self.assertEqual(expected, self.available_backup_name(name))
2135
 
 
2136
 
    def test_empty(self):
2137
 
        self.assertBackupName('file.~1~', 'file')
2138
 
 
2139
 
    def test_existing(self):
2140
 
        self.available_backup_name('file')
2141
 
        self.available_backup_name('file')
2142
 
        self.assertBackupName('file.~3~', 'file')
2143
 
        # Empty slots are found, this is not a strict requirement and may be
2144
 
        # revisited if we test against all implementations.
2145
 
        self.backups.remove('file.~2~')
2146
 
        self.assertBackupName('file.~2~', 'file')
2147
 
 
2148
 
 
2149
 
class TestFindExecutableInPath(tests.TestCase):
2150
 
 
2151
 
    def test_windows(self):
2152
 
        if sys.platform != 'win32':
2153
 
            raise tests.TestSkipped('test requires win32')
2154
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2155
 
        self.assertTrue(
2156
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2157
 
        self.assertTrue(
2158
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2159
 
        self.assertTrue(
2160
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2161
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2162
 
 
2163
 
    def test_other(self):
2164
 
        if sys.platform == 'win32':
2165
 
            raise tests.TestSkipped('test requires non-win32')
2166
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2167
 
        self.assertTrue(
2168
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)