~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Jelmer Vernooij
  • Date: 2009-05-01 14:29:06 UTC
  • mto: This revision was merged to the branch mainline in revision 4321.
  • Revision ID: jelmer@samba.org-20090501142906-7zj8hcpp9igzuyi4
Add repository argument to 'repository' info hook, per Roberts review.

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
 
 
43
 
 
44
 
class _UTF8DirReaderFeature(features.Feature):
 
38
 
 
39
 
 
40
class _UTF8DirReaderFeature(tests.Feature):
45
41
 
46
42
    def _probe(self):
47
43
        try:
54
50
    def feature_name(self):
55
51
        return 'bzrlib._readdir_pyx'
56
52
 
57
 
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
58
 
 
59
 
term_ios_feature = features.ModuleAvailableFeature('termios')
60
 
 
61
 
 
62
 
def _already_unicode(s):
63
 
    return s
64
 
 
65
 
 
66
 
def _utf8_to_unicode(s):
67
 
    return s.decode('UTF-8')
68
 
 
69
 
 
70
 
def dir_reader_scenarios():
71
 
    # For each dir reader we define:
72
 
 
73
 
    # - native_to_unicode: a function converting the native_abspath as returned
74
 
    #   by DirReader.read_dir to its unicode representation
75
 
 
76
 
    # UnicodeDirReader is the fallback, it should be tested on all platforms.
77
 
    scenarios = [('unicode',
78
 
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
79
 
                       _native_to_unicode=_already_unicode))]
80
 
    # Some DirReaders are platform specific and even there they may not be
81
 
    # available.
82
 
    if UTF8DirReaderFeature.available():
83
 
        from bzrlib import _readdir_pyx
84
 
        scenarios.append(('utf8',
85
 
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
86
 
                               _native_to_unicode=_utf8_to_unicode)))
87
 
 
88
 
    if test__walkdirs_win32.win32_readdir_feature.available():
89
 
        try:
90
 
            from bzrlib import _walkdirs_win32
91
 
            scenarios.append(
92
 
                ('win32',
93
 
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
94
 
                      _native_to_unicode=_already_unicode)))
95
 
        except ImportError:
96
 
            pass
97
 
    return scenarios
98
 
 
99
 
 
100
 
load_tests = load_tests_apply_scenarios
101
 
 
102
 
 
103
 
class TestContainsWhitespace(tests.TestCase):
 
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
 
54
 
 
55
 
 
56
class TestOSUtils(tests.TestCaseInTempDir):
104
57
 
105
58
    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'))
 
59
        self.failUnless(osutils.contains_whitespace(u' '))
 
60
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
61
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
62
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
63
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
64
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
112
65
 
113
66
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
114
67
        # 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'))
118
 
 
119
 
 
120
 
class TestRename(tests.TestCaseInTempDir):
121
 
 
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)
 
68
        self.failIf(osutils.contains_whitespace(u''))
 
69
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
70
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
132
71
 
133
72
    def test_fancy_rename(self):
134
73
        # 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')
 
74
        def rename(a, b):
 
75
            osutils.fancy_rename(a, b,
 
76
                    rename_func=os.rename,
 
77
                    unlink_func=os.unlink)
 
78
 
 
79
        open('a', 'wb').write('something in a\n')
 
80
        rename('a', 'b')
 
81
        self.failIfExists('a')
 
82
        self.failUnlessExists('b')
139
83
        self.check_file_contents('b', 'something in a\n')
140
84
 
141
 
        self.create_file('a', 'new something in a\n')
142
 
        self._fancy_rename('b', 'a')
 
85
        open('a', 'wb').write('new something in a\n')
 
86
        rename('b', 'a')
143
87
 
144
88
        self.check_file_contents('a', 'something in a\n')
145
89
 
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
90
    def test_rename(self):
159
91
        # Rename should be semi-atomic on all platforms
160
 
        self.create_file('a', 'something in a\n')
 
92
        open('a', 'wb').write('something in a\n')
161
93
        osutils.rename('a', 'b')
162
 
        self.assertPathDoesNotExist('a')
163
 
        self.assertPathExists('b')
 
94
        self.failIfExists('a')
 
95
        self.failUnlessExists('b')
164
96
        self.check_file_contents('b', 'something in a\n')
165
97
 
166
 
        self.create_file('a', 'new something in a\n')
 
98
        open('a', 'wb').write('new something in a\n')
167
99
        osutils.rename('b', 'a')
168
100
 
169
101
        self.check_file_contents('a', 'something in a\n')
180
112
        shape = sorted(os.listdir('.'))
181
113
        self.assertEquals(['A', 'B'], shape)
182
114
 
183
 
 
184
 
class TestRandChars(tests.TestCase):
185
 
 
186
115
    def test_01_rand_chars_empty(self):
187
116
        result = osutils.rand_chars(0)
188
117
        self.assertEqual(result, '')
193
122
        self.assertEqual(type(result), str)
194
123
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
195
124
 
196
 
 
197
 
class TestIsInside(tests.TestCase):
198
 
 
199
125
    def test_is_inside(self):
200
126
        is_inside = osutils.is_inside
201
127
        self.assertTrue(is_inside('src', 'src/foo.c'))
230
156
                         (['src'], 'srccontrol/foo')]:
231
157
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
232
158
 
233
 
 
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
 
class TestRmTree(tests.TestCaseInTempDir):
254
 
 
255
159
    def test_rmtree(self):
256
160
        # Check to remove tree with read-only files/dirs
257
161
        os.mkdir('dir')
267
171
 
268
172
        osutils.rmtree('dir')
269
173
 
270
 
        self.assertPathDoesNotExist('dir/file')
271
 
        self.assertPathDoesNotExist('dir')
272
 
 
273
 
 
274
 
class TestDeleteAny(tests.TestCaseInTempDir):
275
 
 
276
 
    def test_delete_any_readonly(self):
277
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
278
 
        self.build_tree(['d/', 'f'])
279
 
        osutils.make_readonly('d')
280
 
        osutils.make_readonly('f')
281
 
 
282
 
        osutils.delete_any('f')
283
 
        osutils.delete_any('d')
284
 
 
285
 
 
286
 
class TestKind(tests.TestCaseInTempDir):
 
174
        self.failIfExists('dir/file')
 
175
        self.failIfExists('dir')
287
176
 
288
177
    def test_file_kind(self):
289
178
        self.build_tree(['file', 'dir/'])
320
209
                os.remove('socket')
321
210
 
322
211
    def test_kind_marker(self):
323
 
        self.assertEqual("", osutils.kind_marker("file"))
324
 
        self.assertEqual("/", osutils.kind_marker('directory'))
325
 
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
326
 
        self.assertEqual("@", osutils.kind_marker("symlink"))
327
 
        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"))
331
 
 
332
 
 
333
 
class TestUmask(tests.TestCaseInTempDir):
 
212
        self.assertEqual(osutils.kind_marker('file'), '')
 
213
        self.assertEqual(osutils.kind_marker('directory'), '/')
 
214
        self.assertEqual(osutils.kind_marker('symlink'), '@')
 
215
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
334
216
 
335
217
    def test_get_umask(self):
336
218
        if sys.platform == 'win32':
349
231
        os.umask(0027)
350
232
        self.assertEqual(0027, osutils.get_umask())
351
233
 
352
 
 
353
 
class TestDateTime(tests.TestCase):
354
 
 
355
234
    def assertFormatedDelta(self, expected, seconds):
356
235
        """Assert osutils.format_delta formats as expected"""
357
236
        actual = osutils.format_delta(seconds)
398
277
        # Instead blackbox.test_locale should check for localized
399
278
        # dates once they do occur in output strings.
400
279
 
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
 
    def test_local_time_offset(self):
410
 
        """Test that local_time_offset() returns a sane value."""
411
 
        offset = osutils.local_time_offset()
412
 
        self.assertTrue(isinstance(offset, int))
413
 
        # Test that the offset is no more than a eighteen hours in
414
 
        # either direction.
415
 
        # Time zone handling is system specific, so it is difficult to
416
 
        # do more specific tests, but a value outside of this range is
417
 
        # probably wrong.
418
 
        eighteen_hours = 18 * 3600
419
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
420
 
 
421
 
    def test_local_time_offset_with_timestamp(self):
422
 
        """Test that local_time_offset() works with a timestamp."""
423
 
        offset = osutils.local_time_offset(1000000000.1234567)
424
 
        self.assertTrue(isinstance(offset, int))
425
 
        eighteen_hours = 18 * 3600
426
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
427
 
 
428
 
 
429
 
class TestLinks(tests.TestCaseInTempDir):
430
 
 
431
280
    def test_dereference_path(self):
432
 
        self.requireFeature(features.SymlinkFeature)
 
281
        self.requireFeature(tests.SymlinkFeature)
433
282
        cwd = osutils.realpath('.')
434
283
        os.mkdir('bar')
435
284
        bar_path = osutils.pathjoin(cwd, 'bar')
476
325
            osutils.make_readonly('dangling')
477
326
            osutils.make_writable('dangling')
478
327
 
 
328
    def test_kind_marker(self):
 
329
        self.assertEqual("", osutils.kind_marker("file"))
 
330
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
 
331
        self.assertEqual("@", osutils.kind_marker("symlink"))
 
332
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
333
 
479
334
    def test_host_os_dereferences_symlinks(self):
480
335
        osutils.host_os_dereferences_symlinks()
481
336
 
482
337
 
483
338
class TestCanonicalRelPath(tests.TestCaseInTempDir):
484
339
 
485
 
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
 
340
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
486
341
 
487
342
    def test_canonical_relpath_simple(self):
488
343
        f = file('MixedCaseName', 'w')
489
344
        f.close()
490
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
491
 
        self.assertEqual('work/MixedCaseName', actual)
 
345
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
346
        real_base_dir = osutils.realpath(self.test_base_dir)
 
347
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
 
348
        self.failUnlessEqual('work/MixedCaseName', actual)
492
349
 
493
350
    def test_canonical_relpath_missing_tail(self):
494
351
        os.mkdir('MixedCaseParent')
495
 
        actual = osutils.canonical_relpath(self.test_base_dir,
 
352
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
353
        real_base_dir = osutils.realpath(self.test_base_dir)
 
354
        actual = osutils.canonical_relpath(real_base_dir,
496
355
                                           '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')
 
356
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
541
357
 
542
358
 
543
359
class TestPumpFile(tests.TestCase):
705
521
        self.assertEqual("1234", output.getvalue())
706
522
 
707
523
 
708
 
class TestRelpath(tests.TestCase):
709
 
 
710
 
    def test_simple_relpath(self):
711
 
        cwd = osutils.getcwd()
712
 
        subdir = cwd + '/subdir'
713
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
714
 
 
715
 
    def test_deep_relpath(self):
716
 
        cwd = osutils.getcwd()
717
 
        subdir = cwd + '/sub/subsubdir'
718
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
719
 
 
720
 
    def test_not_relative(self):
721
 
        self.assertRaises(errors.PathNotChild,
722
 
                          osutils.relpath, 'C:/path', 'H:/path')
723
 
        self.assertRaises(errors.PathNotChild,
724
 
                          osutils.relpath, 'C:/', 'H:/path')
725
 
 
726
 
 
727
524
class TestSafeUnicode(tests.TestCase):
728
525
 
729
526
    def test_from_ascii_string(self):
876
673
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
877
674
        # relative path
878
675
        cwd = osutils.getcwd().rstrip('/')
879
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
676
        drive = osutils._nt_splitdrive(cwd)[0]
880
677
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
881
678
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
882
679
        # unicode path
888
685
    """Test win32 functions that create files."""
889
686
 
890
687
    def test_getcwd(self):
891
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
688
        self.requireFeature(tests.UnicodeFilenameFeature)
892
689
        os.mkdir(u'mu-\xb5')
893
690
        os.chdir(u'mu-\xb5')
894
691
        # TODO: jam 20060427 This will probably fail on Mac OSX because
900
697
    def test_minimum_path_selection(self):
901
698
        self.assertEqual(set(),
902
699
            osutils.minimum_path_selection([]))
903
 
        self.assertEqual(set(['a']),
904
 
            osutils.minimum_path_selection(['a']))
905
700
        self.assertEqual(set(['a', 'b']),
906
701
            osutils.minimum_path_selection(['a', 'b']))
907
702
        self.assertEqual(set(['a/', 'b']),
908
703
            osutils.minimum_path_selection(['a/', 'b']))
909
704
        self.assertEqual(set(['a/', 'b']),
910
705
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
911
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
912
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
913
706
 
914
707
    def test_mkdtemp(self):
915
708
        tmpdir = osutils._win32_mkdtemp(dir='.')
924
717
        b.close()
925
718
 
926
719
        osutils._win32_rename('b', 'a')
927
 
        self.assertPathExists('a')
928
 
        self.assertPathDoesNotExist('b')
 
720
        self.failUnlessExists('a')
 
721
        self.failIfExists('b')
929
722
        self.assertFileEqual('baz\n', 'a')
930
723
 
931
724
    def test_rename_missing_file(self):
971
764
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
972
765
 
973
766
 
974
 
class TestParentDirectories(tests.TestCaseInTempDir):
975
 
    """Test osutils.parent_directories()"""
976
 
 
977
 
    def test_parent_directories(self):
978
 
        self.assertEqual([], osutils.parent_directories('a'))
979
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
980
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
981
 
 
982
 
 
983
767
class TestMacFuncsDirs(tests.TestCaseInTempDir):
984
768
    """Test mac special functions that require directories."""
985
769
 
986
770
    def test_getcwd(self):
987
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
771
        self.requireFeature(tests.UnicodeFilenameFeature)
988
772
        os.mkdir(u'B\xe5gfors')
989
773
        os.chdir(u'B\xe5gfors')
990
774
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
991
775
 
992
776
    def test_getcwd_nonnorm(self):
993
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
777
        self.requireFeature(tests.UnicodeFilenameFeature)
994
778
        # Test that _mac_getcwd() will normalize this path
995
779
        os.mkdir(u'Ba\u030agfors')
996
780
        os.chdir(u'Ba\u030agfors')
1007
791
 
1008
792
    def test_osutils_binding(self):
1009
793
        from bzrlib.tests import test__chunks_to_lines
1010
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
 
794
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
1011
795
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1012
796
        else:
1013
797
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1029
813
 
1030
814
class TestWalkDirs(tests.TestCaseInTempDir):
1031
815
 
1032
 
    def assertExpectedBlocks(self, expected, result):
1033
 
        self.assertEqual(expected,
1034
 
                         [(dirinfo, [line[0:3] for line in block])
1035
 
                          for dirinfo, block in result])
1036
 
 
1037
816
    def test_walkdirs(self):
1038
817
        tree = [
1039
818
            '.bzr',
1071
850
            result.append((dirdetail, dirblock))
1072
851
 
1073
852
        self.assertTrue(found_bzrdir)
1074
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
853
        self.assertEqual(expected_dirblocks,
 
854
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1075
855
        # you can search a subdir only, with a supplied prefix.
1076
856
        result = []
1077
857
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1078
858
            result.append(dirblock)
1079
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
859
        self.assertEqual(expected_dirblocks[1:],
 
860
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1080
861
 
1081
862
    def test_walkdirs_os_error(self):
1082
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
863
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1083
864
        # Pyrex readdir didn't raise useful messages if it had an error
1084
865
        # reading the directory
1085
866
        if sys.platform == 'win32':
1086
867
            raise tests.TestNotApplicable(
1087
868
                "readdir IOError not tested on win32")
1088
 
        self.requireFeature(features.not_running_as_root)
1089
869
        os.mkdir("test-unreadable")
1090
870
        os.chmod("test-unreadable", 0000)
1091
871
        # must chmod it back so that it can be removed
1092
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
 
872
        self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
1093
873
        # The error is not raised until the generator is actually evaluated.
1094
874
        # (It would be ok if it happened earlier but at the moment it
1095
875
        # doesn't.)
1099
879
        # Ensure the message contains the file name
1100
880
        self.assertContainsRe(str(e), "\./test-unreadable")
1101
881
 
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(features.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
882
    def test__walkdirs_utf8(self):
1139
883
        tree = [
1140
884
            '.bzr',
1172
916
            result.append((dirdetail, dirblock))
1173
917
 
1174
918
        self.assertTrue(found_bzrdir)
1175
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1176
 
 
 
919
        self.assertEqual(expected_dirblocks,
 
920
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1177
921
        # you can search a subdir only, with a supplied prefix.
1178
922
        result = []
1179
923
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1180
924
            result.append(dirblock)
1181
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
925
        self.assertEqual(expected_dirblocks[1:],
 
926
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1182
927
 
1183
928
    def _filter_out_stat(self, result):
1184
929
        """Filter out the stat value from the walkdirs result"""
1190
935
            dirblock[:] = new_dirblock
1191
936
 
1192
937
    def _save_platform_info(self):
1193
 
        self.overrideAttr(win32utils, 'winver')
1194
 
        self.overrideAttr(osutils, '_fs_enc')
1195
 
        self.overrideAttr(osutils, '_selected_dir_reader')
 
938
        cur_winver = win32utils.winver
 
939
        cur_fs_enc = osutils._fs_enc
 
940
        cur_dir_reader = osutils._selected_dir_reader
 
941
        def restore():
 
942
            win32utils.winver = cur_winver
 
943
            osutils._fs_enc = cur_fs_enc
 
944
            osutils._selected_dir_reader = cur_dir_reader
 
945
        self.addCleanup(restore)
1196
946
 
1197
 
    def assertDirReaderIs(self, expected):
 
947
    def assertReadFSDirIs(self, expected):
1198
948
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1199
949
        # Force it to redetect
1200
950
        osutils._selected_dir_reader = None
1207
957
        self._save_platform_info()
1208
958
        win32utils.winver = None # Avoid the win32 detection code
1209
959
        osutils._fs_enc = 'UTF-8'
1210
 
        self.assertDirReaderIs(
1211
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
960
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1212
961
 
1213
962
    def test_force_walkdirs_utf8_fs_ascii(self):
1214
963
        self.requireFeature(UTF8DirReaderFeature)
1215
964
        self._save_platform_info()
1216
965
        win32utils.winver = None # Avoid the win32 detection code
1217
966
        osutils._fs_enc = 'US-ASCII'
1218
 
        self.assertDirReaderIs(
1219
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
967
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1220
968
 
1221
969
    def test_force_walkdirs_utf8_fs_ANSI(self):
1222
970
        self.requireFeature(UTF8DirReaderFeature)
1223
971
        self._save_platform_info()
1224
972
        win32utils.winver = None # Avoid the win32 detection code
1225
973
        osutils._fs_enc = 'ANSI_X3.4-1968'
1226
 
        self.assertDirReaderIs(
1227
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
974
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1228
975
 
1229
976
    def test_force_walkdirs_utf8_fs_latin1(self):
1230
977
        self._save_platform_info()
1231
978
        win32utils.winver = None # Avoid the win32 detection code
1232
979
        osutils._fs_enc = 'latin1'
1233
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
980
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1234
981
 
1235
982
    def test_force_walkdirs_utf8_nt(self):
1236
983
        # Disabled because the thunk of the whole walkdirs api is disabled.
1237
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
984
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1238
985
        self._save_platform_info()
1239
986
        win32utils.winver = 'Windows NT'
1240
987
        from bzrlib._walkdirs_win32 import Win32ReadDir
1241
 
        self.assertDirReaderIs(Win32ReadDir)
 
988
        self.assertReadFSDirIs(Win32ReadDir)
1242
989
 
1243
990
    def test_force_walkdirs_utf8_98(self):
1244
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
991
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1245
992
        self._save_platform_info()
1246
993
        win32utils.winver = 'Windows 98'
1247
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
994
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1248
995
 
1249
996
    def test_unicode_walkdirs(self):
1250
997
        """Walkdirs should always return unicode paths."""
1251
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
998
        self.requireFeature(tests.UnicodeFilenameFeature)
1252
999
        name0 = u'0file-\xb6'
1253
1000
        name1 = u'1dir-\u062c\u0648'
1254
1001
        name2 = u'2file-\u0633'
1291
1038
 
1292
1039
        The abspath portion might be in unicode or utf-8
1293
1040
        """
1294
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1041
        self.requireFeature(tests.UnicodeFilenameFeature)
1295
1042
        name0 = u'0file-\xb6'
1296
1043
        name1 = u'1dir-\u062c\u0648'
1297
1044
        name2 = u'2file-\u0633'
1352
1099
 
1353
1100
        The abspath portion should be in unicode
1354
1101
        """
1355
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1102
        self.requireFeature(tests.UnicodeFilenameFeature)
1356
1103
        # Use the unicode reader. TODO: split into driver-and-driven unit
1357
1104
        # tests.
1358
1105
        self._save_platform_info()
1398
1145
        self.assertEqual(expected_dirblocks, result)
1399
1146
 
1400
1147
    def test__walkdirs_utf8_win32readdir(self):
1401
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1402
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1148
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1149
        self.requireFeature(tests.UnicodeFilenameFeature)
1403
1150
        from bzrlib._walkdirs_win32 import Win32ReadDir
1404
1151
        self._save_platform_info()
1405
1152
        osutils._selected_dir_reader = Win32ReadDir()
1455
1202
 
1456
1203
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1457
1204
        """make sure our Stat values are valid"""
1458
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1459
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1205
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1206
        self.requireFeature(tests.UnicodeFilenameFeature)
1460
1207
        from bzrlib._walkdirs_win32 import Win32ReadDir
1461
1208
        name0u = u'0file-\xb6'
1462
1209
        name0 = name0u.encode('utf8')
1479
1226
 
1480
1227
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1481
1228
        """make sure our Stat values are valid"""
1482
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1483
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1229
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1230
        self.requireFeature(tests.UnicodeFilenameFeature)
1484
1231
        from bzrlib._walkdirs_win32 import Win32ReadDir
1485
1232
        name0u = u'0dir-\u062c\u0648'
1486
1233
        name0 = name0u.encode('utf8')
1586
1333
        self.assertEqual(['c'], os.listdir('target/b'))
1587
1334
 
1588
1335
    def test_copy_tree_symlinks(self):
1589
 
        self.requireFeature(features.SymlinkFeature)
 
1336
        self.requireFeature(tests.SymlinkFeature)
1590
1337
        self.build_tree(['source/'])
1591
1338
        os.symlink('a/generic/path', 'source/lnk')
1592
1339
        osutils.copy_tree('source', 'target')
1617
1364
                          ('d', 'source/b', 'target/b'),
1618
1365
                          ('f', 'source/b/c', 'target/b/c'),
1619
1366
                         ], processed_files)
1620
 
        self.assertPathDoesNotExist('target')
 
1367
        self.failIfExists('target')
1621
1368
        if osutils.has_symlinks():
1622
1369
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1623
1370
 
1634
1381
        def cleanup():
1635
1382
            if 'BZR_TEST_ENV_VAR' in os.environ:
1636
1383
                del os.environ['BZR_TEST_ENV_VAR']
 
1384
 
1637
1385
        self.addCleanup(cleanup)
1638
1386
 
1639
1387
    def test_set(self):
1669
1417
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1670
1418
        self.assertEqual('foo', old)
1671
1419
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1672
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
 
1420
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1421
 
 
1422
 
 
1423
class TestLocalTimeOffset(tests.TestCase):
 
1424
 
 
1425
    def test_local_time_offset(self):
 
1426
        """Test that local_time_offset() returns a sane value."""
 
1427
        offset = osutils.local_time_offset()
 
1428
        self.assertTrue(isinstance(offset, int))
 
1429
        # Test that the offset is no more than a eighteen hours in
 
1430
        # either direction.
 
1431
        # Time zone handling is system specific, so it is difficult to
 
1432
        # do more specific tests, but a value outside of this range is
 
1433
        # probably wrong.
 
1434
        eighteen_hours = 18 * 3600
 
1435
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1436
 
 
1437
    def test_local_time_offset_with_timestamp(self):
 
1438
        """Test that local_time_offset() works with a timestamp."""
 
1439
        offset = osutils.local_time_offset(1000000000.1234567)
 
1440
        self.assertTrue(isinstance(offset, int))
 
1441
        eighteen_hours = 18 * 3600
 
1442
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
1673
1443
 
1674
1444
 
1675
1445
class TestSizeShaFile(tests.TestCaseInTempDir):
1687
1457
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1688
1458
        self.build_tree_contents([('foo', text)])
1689
1459
        expected_sha = osutils.sha_string(text)
1690
 
        f = open('foo', 'rb')
 
1460
        f = open('foo')
1691
1461
        self.addCleanup(f.close)
1692
1462
        size, sha = osutils.size_sha_file(f)
1693
1463
        self.assertEqual(38, size)
1726
1496
 
1727
1497
class TestReCompile(tests.TestCase):
1728
1498
 
1729
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1730
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1731
 
            osutils.re_compile_checked, *args, **kwargs)
1732
 
 
1733
1499
    def test_re_compile_checked(self):
1734
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1500
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1735
1501
        self.assertTrue(r.match('aaaa'))
1736
1502
        self.assertTrue(r.match('aAaA'))
1737
1503
 
1738
1504
    def test_re_compile_checked_error(self):
1739
1505
        # like https://bugs.launchpad.net/bzr/+bug/251352
1740
 
 
1741
 
        # Due to possible test isolation error, re.compile is not lazy at
1742
 
        # this point. We re-install lazy compile.
1743
 
        lazy_regex.install_lazy_compile()
1744
1506
        err = self.assertRaises(
1745
1507
            errors.BzrCommandError,
1746
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1508
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1747
1509
        self.assertEqual(
1748
 
            'Invalid regular expression in test case: '
1749
 
            '"*" nothing to repeat',
 
1510
            "Invalid regular expression in test case: '*': "
 
1511
            "nothing to repeat",
1750
1512
            str(err))
1751
 
 
1752
 
 
1753
 
class TestDirReader(tests.TestCaseInTempDir):
1754
 
 
1755
 
    scenarios = dir_reader_scenarios()
1756
 
 
1757
 
    # Set by load_tests
1758
 
    _dir_reader_class = None
1759
 
    _native_to_unicode = None
1760
 
 
1761
 
    def setUp(self):
1762
 
        tests.TestCaseInTempDir.setUp(self)
1763
 
        self.overrideAttr(osutils,
1764
 
                          '_selected_dir_reader', self._dir_reader_class())
1765
 
 
1766
 
    def _get_ascii_tree(self):
1767
 
        tree = [
1768
 
            '0file',
1769
 
            '1dir/',
1770
 
            '1dir/0file',
1771
 
            '1dir/1dir/',
1772
 
            '2file'
1773
 
            ]
1774
 
        expected_dirblocks = [
1775
 
                (('', '.'),
1776
 
                 [('0file', '0file', 'file'),
1777
 
                  ('1dir', '1dir', 'directory'),
1778
 
                  ('2file', '2file', 'file'),
1779
 
                 ]
1780
 
                ),
1781
 
                (('1dir', './1dir'),
1782
 
                 [('1dir/0file', '0file', 'file'),
1783
 
                  ('1dir/1dir', '1dir', 'directory'),
1784
 
                 ]
1785
 
                ),
1786
 
                (('1dir/1dir', './1dir/1dir'),
1787
 
                 [
1788
 
                 ]
1789
 
                ),
1790
 
            ]
1791
 
        return tree, expected_dirblocks
1792
 
 
1793
 
    def test_walk_cur_dir(self):
1794
 
        tree, expected_dirblocks = self._get_ascii_tree()
1795
 
        self.build_tree(tree)
1796
 
        result = list(osutils._walkdirs_utf8('.'))
1797
 
        # Filter out stat and abspath
1798
 
        self.assertEqual(expected_dirblocks,
1799
 
                         [(dirinfo, [line[0:3] for line in block])
1800
 
                          for dirinfo, block in result])
1801
 
 
1802
 
    def test_walk_sub_dir(self):
1803
 
        tree, expected_dirblocks = self._get_ascii_tree()
1804
 
        self.build_tree(tree)
1805
 
        # you can search a subdir only, with a supplied prefix.
1806
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1807
 
        # Filter out stat and abspath
1808
 
        self.assertEqual(expected_dirblocks[1:],
1809
 
                         [(dirinfo, [line[0:3] for line in block])
1810
 
                          for dirinfo, block in result])
1811
 
 
1812
 
    def _get_unicode_tree(self):
1813
 
        name0u = u'0file-\xb6'
1814
 
        name1u = u'1dir-\u062c\u0648'
1815
 
        name2u = u'2file-\u0633'
1816
 
        tree = [
1817
 
            name0u,
1818
 
            name1u + '/',
1819
 
            name1u + '/' + name0u,
1820
 
            name1u + '/' + name1u + '/',
1821
 
            name2u,
1822
 
            ]
1823
 
        name0 = name0u.encode('UTF-8')
1824
 
        name1 = name1u.encode('UTF-8')
1825
 
        name2 = name2u.encode('UTF-8')
1826
 
        expected_dirblocks = [
1827
 
                (('', '.'),
1828
 
                 [(name0, name0, 'file', './' + name0u),
1829
 
                  (name1, name1, 'directory', './' + name1u),
1830
 
                  (name2, name2, 'file', './' + name2u),
1831
 
                 ]
1832
 
                ),
1833
 
                ((name1, './' + name1u),
1834
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1835
 
                                                        + '/' + name0u),
1836
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1837
 
                                                            + '/' + name1u),
1838
 
                 ]
1839
 
                ),
1840
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1841
 
                 [
1842
 
                 ]
1843
 
                ),
1844
 
            ]
1845
 
        return tree, expected_dirblocks
1846
 
 
1847
 
    def _filter_out(self, raw_dirblocks):
1848
 
        """Filter out a walkdirs_utf8 result.
1849
 
 
1850
 
        stat field is removed, all native paths are converted to unicode
1851
 
        """
1852
 
        filtered_dirblocks = []
1853
 
        for dirinfo, block in raw_dirblocks:
1854
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1855
 
            details = []
1856
 
            for line in block:
1857
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1858
 
            filtered_dirblocks.append((dirinfo, details))
1859
 
        return filtered_dirblocks
1860
 
 
1861
 
    def test_walk_unicode_tree(self):
1862
 
        self.requireFeature(features.UnicodeFilenameFeature)
1863
 
        tree, expected_dirblocks = self._get_unicode_tree()
1864
 
        self.build_tree(tree)
1865
 
        result = list(osutils._walkdirs_utf8('.'))
1866
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1867
 
 
1868
 
    def test_symlink(self):
1869
 
        self.requireFeature(features.SymlinkFeature)
1870
 
        self.requireFeature(features.UnicodeFilenameFeature)
1871
 
        target = u'target\N{Euro Sign}'
1872
 
        link_name = u'l\N{Euro Sign}nk'
1873
 
        os.symlink(target, link_name)
1874
 
        target_utf8 = target.encode('UTF-8')
1875
 
        link_name_utf8 = link_name.encode('UTF-8')
1876
 
        expected_dirblocks = [
1877
 
                (('', '.'),
1878
 
                 [(link_name_utf8, link_name_utf8,
1879
 
                   'symlink', './' + link_name),],
1880
 
                 )]
1881
 
        result = list(osutils._walkdirs_utf8('.'))
1882
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1883
 
 
1884
 
 
1885
 
class TestReadLink(tests.TestCaseInTempDir):
1886
 
    """Exposes os.readlink() problems and the osutils solution.
1887
 
 
1888
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1889
 
    unicode string will be returned if a unicode string is passed.
1890
 
 
1891
 
    But prior python versions failed to properly encode the passed unicode
1892
 
    string.
1893
 
    """
1894
 
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1895
 
 
1896
 
    def setUp(self):
1897
 
        super(tests.TestCaseInTempDir, self).setUp()
1898
 
        self.link = u'l\N{Euro Sign}ink'
1899
 
        self.target = u'targe\N{Euro Sign}t'
1900
 
        os.symlink(self.target, self.link)
1901
 
 
1902
 
    def test_os_readlink_link_encoding(self):
1903
 
        self.assertEquals(self.target,  os.readlink(self.link))
1904
 
 
1905
 
    def test_os_readlink_link_decoding(self):
1906
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
1907
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
1908
 
 
1909
 
 
1910
 
class TestConcurrency(tests.TestCase):
1911
 
 
1912
 
    def setUp(self):
1913
 
        super(TestConcurrency, self).setUp()
1914
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
1915
 
 
1916
 
    def test_local_concurrency(self):
1917
 
        concurrency = osutils.local_concurrency()
1918
 
        self.assertIsInstance(concurrency, int)
1919
 
 
1920
 
    def test_local_concurrency_environment_variable(self):
1921
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
1922
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1923
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
1924
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1925
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
1926
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1927
 
 
1928
 
    def test_option_concurrency(self):
1929
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
1930
 
        self.run_bzr('rocks --concurrency 42')
1931
 
        # Command line overrides environment variable
1932
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1933
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1934
 
 
1935
 
 
1936
 
class TestFailedToLoadExtension(tests.TestCase):
1937
 
 
1938
 
    def _try_loading(self):
1939
 
        try:
1940
 
            import bzrlib._fictional_extension_py
1941
 
        except ImportError, e:
1942
 
            osutils.failed_to_load_extension(e)
1943
 
            return True
1944
 
 
1945
 
    def setUp(self):
1946
 
        super(TestFailedToLoadExtension, self).setUp()
1947
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
1948
 
 
1949
 
    def test_failure_to_load(self):
1950
 
        self._try_loading()
1951
 
        self.assertLength(1, osutils._extension_load_failures)
1952
 
        self.assertEquals(osutils._extension_load_failures[0],
1953
 
            "No module named _fictional_extension_py")
1954
 
 
1955
 
    def test_report_extension_load_failures_no_warning(self):
1956
 
        self.assertTrue(self._try_loading())
1957
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1958
 
        # it used to give a Python warning; it no longer does
1959
 
        self.assertLength(0, warnings)
1960
 
 
1961
 
    def test_report_extension_load_failures_message(self):
1962
 
        log = StringIO()
1963
 
        trace.push_log_file(log)
1964
 
        self.assertTrue(self._try_loading())
1965
 
        osutils.report_extension_load_failures()
1966
 
        self.assertContainsRe(
1967
 
            log.getvalue(),
1968
 
            r"bzr: warning: some compiled extensions could not be loaded; "
1969
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1970
 
            )
1971
 
 
1972
 
 
1973
 
class TestTerminalWidth(tests.TestCase):
1974
 
 
1975
 
    def setUp(self):
1976
 
        tests.TestCase.setUp(self)
1977
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1978
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1979
 
        self.addCleanup(self.restore_osutils_globals)
1980
 
        osutils._terminal_size_state = 'no_data'
1981
 
        osutils._first_terminal_size = None
1982
 
 
1983
 
    def restore_osutils_globals(self):
1984
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1985
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1986
 
 
1987
 
    def replace_stdout(self, new):
1988
 
        self.overrideAttr(sys, 'stdout', new)
1989
 
 
1990
 
    def replace__terminal_size(self, new):
1991
 
        self.overrideAttr(osutils, '_terminal_size', new)
1992
 
 
1993
 
    def set_fake_tty(self):
1994
 
 
1995
 
        class I_am_a_tty(object):
1996
 
            def isatty(self):
1997
 
                return True
1998
 
 
1999
 
        self.replace_stdout(I_am_a_tty())
2000
 
 
2001
 
    def test_default_values(self):
2002
 
        self.assertEqual(80, osutils.default_terminal_width)
2003
 
 
2004
 
    def test_defaults_to_BZR_COLUMNS(self):
2005
 
        # BZR_COLUMNS is set by the test framework
2006
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2007
 
        self.overrideEnv('BZR_COLUMNS', '12')
2008
 
        self.assertEqual(12, osutils.terminal_width())
2009
 
 
2010
 
    def test_BZR_COLUMNS_0_no_limit(self):
2011
 
        self.overrideEnv('BZR_COLUMNS', '0')
2012
 
        self.assertEqual(None, osutils.terminal_width())
2013
 
 
2014
 
    def test_falls_back_to_COLUMNS(self):
2015
 
        self.overrideEnv('BZR_COLUMNS', None)
2016
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
2017
 
        self.set_fake_tty()
2018
 
        self.overrideEnv('COLUMNS', '42')
2019
 
        self.assertEqual(42, osutils.terminal_width())
2020
 
 
2021
 
    def test_tty_default_without_columns(self):
2022
 
        self.overrideEnv('BZR_COLUMNS', None)
2023
 
        self.overrideEnv('COLUMNS', None)
2024
 
 
2025
 
        def terminal_size(w, h):
2026
 
            return 42, 42
2027
 
 
2028
 
        self.set_fake_tty()
2029
 
        # We need to override the osutils definition as it depends on the
2030
 
        # running environment that we can't control (PQM running without a
2031
 
        # controlling terminal is one example).
2032
 
        self.replace__terminal_size(terminal_size)
2033
 
        self.assertEqual(42, osutils.terminal_width())
2034
 
 
2035
 
    def test_non_tty_default_without_columns(self):
2036
 
        self.overrideEnv('BZR_COLUMNS', None)
2037
 
        self.overrideEnv('COLUMNS', None)
2038
 
        self.replace_stdout(None)
2039
 
        self.assertEqual(None, osutils.terminal_width())
2040
 
 
2041
 
    def test_no_TIOCGWINSZ(self):
2042
 
        self.requireFeature(term_ios_feature)
2043
 
        termios = term_ios_feature.module
2044
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2045
 
        try:
2046
 
            orig = termios.TIOCGWINSZ
2047
 
        except AttributeError:
2048
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2049
 
            pass
2050
 
        else:
2051
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2052
 
            del termios.TIOCGWINSZ
2053
 
        self.overrideEnv('BZR_COLUMNS', None)
2054
 
        self.overrideEnv('COLUMNS', None)
2055
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2056
 
        osutils.terminal_width()
2057
 
 
2058
 
 
2059
 
class TestCreationOps(tests.TestCaseInTempDir):
2060
 
    _test_needs_features = [features.chown_feature]
2061
 
 
2062
 
    def setUp(self):
2063
 
        tests.TestCaseInTempDir.setUp(self)
2064
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2065
 
 
2066
 
        # params set by call to _dummy_chown
2067
 
        self.path = self.uid = self.gid = None
2068
 
 
2069
 
    def _dummy_chown(self, path, uid, gid):
2070
 
        self.path, self.uid, self.gid = path, uid, gid
2071
 
 
2072
 
    def test_copy_ownership_from_path(self):
2073
 
        """copy_ownership_from_path test with specified src."""
2074
 
        ownsrc = '/'
2075
 
        f = open('test_file', 'wt')
2076
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2077
 
 
2078
 
        s = os.stat(ownsrc)
2079
 
        self.assertEquals(self.path, 'test_file')
2080
 
        self.assertEquals(self.uid, s.st_uid)
2081
 
        self.assertEquals(self.gid, s.st_gid)
2082
 
 
2083
 
    def test_copy_ownership_nonesrc(self):
2084
 
        """copy_ownership_from_path test with src=None."""
2085
 
        f = open('test_file', 'wt')
2086
 
        # should use parent dir for permissions
2087
 
        osutils.copy_ownership_from_path('test_file')
2088
 
 
2089
 
        s = os.stat('..')
2090
 
        self.assertEquals(self.path, 'test_file')
2091
 
        self.assertEquals(self.uid, s.st_uid)
2092
 
        self.assertEquals(self.gid, s.st_gid)
2093
 
 
2094
 
 
2095
 
class TestGetuserUnicode(tests.TestCase):
2096
 
 
2097
 
    def test_ascii_user(self):
2098
 
        self.overrideEnv('LOGNAME', 'jrandom')
2099
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2100
 
 
2101
 
    def test_unicode_user(self):
2102
 
        ue = osutils.get_user_encoding()
2103
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2104
 
        if uni_val is None:
2105
 
            raise tests.TestSkipped(
2106
 
                'Cannot find a unicode character that works in encoding %s'
2107
 
                % (osutils.get_user_encoding(),))
2108
 
        uni_username = u'jrandom' + uni_val
2109
 
        encoded_username = uni_username.encode(ue)
2110
 
        self.overrideEnv('LOGNAME', encoded_username)
2111
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2112
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
2113
 
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
2114
 
 
2115
 
    def test_no_username_bug_660174(self):
2116
 
        self.requireFeature(features.win32_feature)
2117
 
        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
2118
 
            self.overrideEnv(name, None)
2119
 
        self.assertEqual(u'UNKNOWN', osutils.getuser_unicode())
2120
 
 
2121
 
 
2122
 
class TestBackupNames(tests.TestCase):
2123
 
 
2124
 
    def setUp(self):
2125
 
        super(TestBackupNames, self).setUp()
2126
 
        self.backups = []
2127
 
 
2128
 
    def backup_exists(self, name):
2129
 
        return name in self.backups
2130
 
 
2131
 
    def available_backup_name(self, name):
2132
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2133
 
        self.backups.append(backup_name)
2134
 
        return backup_name
2135
 
 
2136
 
    def assertBackupName(self, expected, name):
2137
 
        self.assertEqual(expected, self.available_backup_name(name))
2138
 
 
2139
 
    def test_empty(self):
2140
 
        self.assertBackupName('file.~1~', 'file')
2141
 
 
2142
 
    def test_existing(self):
2143
 
        self.available_backup_name('file')
2144
 
        self.available_backup_name('file')
2145
 
        self.assertBackupName('file.~3~', 'file')
2146
 
        # Empty slots are found, this is not a strict requirement and may be
2147
 
        # revisited if we test against all implementations.
2148
 
        self.backups.remove('file.~2~')
2149
 
        self.assertBackupName('file.~2~', 'file')
2150
 
 
2151
 
 
2152
 
class TestFindExecutableInPath(tests.TestCase):
2153
 
 
2154
 
    def test_windows(self):
2155
 
        if sys.platform != 'win32':
2156
 
            raise tests.TestSkipped('test requires win32')
2157
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2158
 
        self.assertTrue(
2159
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2160
 
        self.assertTrue(
2161
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2162
 
        self.assertTrue(
2163
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2164
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2165
 
 
2166
 
    def test_other(self):
2167
 
        if sys.platform == 'win32':
2168
 
            raise tests.TestSkipped('test requires non-win32')
2169
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2170
 
        self.assertTrue(
2171
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)