~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Jonathan Lange
  • Date: 2009-05-01 06:42:30 UTC
  • mto: This revision was merged to the branch mainline in revision 4320.
  • Revision ID: jml@canonical.com-20090501064230-kyk7v49xt8cevd25
Remove InstallFailed, it's not needed anymore.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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
    )
55
52
 
56
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
57
54
 
58
 
term_ios_feature = tests.ModuleAvailableFeature('termios')
59
 
 
60
 
 
61
 
def _already_unicode(s):
62
 
    return s
63
 
 
64
 
 
65
 
def _utf8_to_unicode(s):
66
 
    return s.decode('UTF-8')
67
 
 
68
 
 
69
 
def dir_reader_scenarios():
70
 
    # For each dir reader we define:
71
 
 
72
 
    # - native_to_unicode: a function converting the native_abspath as returned
73
 
    #   by DirReader.read_dir to its unicode representation
74
 
 
75
 
    # UnicodeDirReader is the fallback, it should be tested on all platforms.
76
 
    scenarios = [('unicode',
77
 
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
78
 
                       _native_to_unicode=_already_unicode))]
79
 
    # Some DirReaders are platform specific and even there they may not be
80
 
    # available.
81
 
    if UTF8DirReaderFeature.available():
82
 
        from bzrlib import _readdir_pyx
83
 
        scenarios.append(('utf8',
84
 
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
85
 
                               _native_to_unicode=_utf8_to_unicode)))
86
 
 
87
 
    if test__walkdirs_win32.win32_readdir_feature.available():
88
 
        try:
89
 
            from bzrlib import _walkdirs_win32
90
 
            scenarios.append(
91
 
                ('win32',
92
 
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
93
 
                      _native_to_unicode=_already_unicode)))
94
 
        except ImportError:
95
 
            pass
96
 
    return scenarios
97
 
 
98
 
 
99
 
def load_tests(basic_tests, module, loader):
100
 
    suite = loader.suiteClass()
101
 
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
102
 
        basic_tests, tests.condition_isinstance(TestDirReader))
103
 
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
104
 
    suite.addTest(remaining_tests)
105
 
    return suite
106
 
 
107
 
 
108
 
class TestContainsWhitespace(tests.TestCase):
 
55
 
 
56
class TestOSUtils(tests.TestCaseInTempDir):
109
57
 
110
58
    def test_contains_whitespace(self):
111
59
        self.failUnless(osutils.contains_whitespace(u' '))
121
69
        self.failIf(osutils.contains_whitespace(u'hellothere'))
122
70
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
123
71
 
124
 
 
125
 
class TestRename(tests.TestCaseInTempDir):
126
 
 
127
 
    def create_file(self, filename, content):
128
 
        f = open(filename, 'wb')
129
 
        try:
130
 
            f.write(content)
131
 
        finally:
132
 
            f.close()
133
 
 
134
 
    def _fancy_rename(self, a, b):
135
 
        osutils.fancy_rename(a, b, rename_func=os.rename,
136
 
                             unlink_func=os.unlink)
137
 
 
138
72
    def test_fancy_rename(self):
139
73
        # This should work everywhere
140
 
        self.create_file('a', 'something in a\n')
141
 
        self._fancy_rename('a', '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')
142
81
        self.failIfExists('a')
143
82
        self.failUnlessExists('b')
144
83
        self.check_file_contents('b', 'something in a\n')
145
84
 
146
 
        self.create_file('a', 'new something in a\n')
147
 
        self._fancy_rename('b', 'a')
 
85
        open('a', 'wb').write('new something in a\n')
 
86
        rename('b', 'a')
148
87
 
149
88
        self.check_file_contents('a', 'something in a\n')
150
89
 
151
 
    def test_fancy_rename_fails_source_missing(self):
152
 
        # An exception should be raised, and the target should be left in place
153
 
        self.create_file('target', 'data in target\n')
154
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
155
 
                          'missingsource', 'target')
156
 
        self.failUnlessExists('target')
157
 
        self.check_file_contents('target', 'data in target\n')
158
 
 
159
 
    def test_fancy_rename_fails_if_source_and_target_missing(self):
160
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
161
 
                          'missingsource', 'missingtarget')
162
 
 
163
90
    def test_rename(self):
164
91
        # Rename should be semi-atomic on all platforms
165
 
        self.create_file('a', 'something in a\n')
 
92
        open('a', 'wb').write('something in a\n')
166
93
        osutils.rename('a', 'b')
167
94
        self.failIfExists('a')
168
95
        self.failUnlessExists('b')
169
96
        self.check_file_contents('b', 'something in a\n')
170
97
 
171
 
        self.create_file('a', 'new something in a\n')
 
98
        open('a', 'wb').write('new something in a\n')
172
99
        osutils.rename('b', 'a')
173
100
 
174
101
        self.check_file_contents('a', 'something in a\n')
185
112
        shape = sorted(os.listdir('.'))
186
113
        self.assertEquals(['A', 'B'], shape)
187
114
 
188
 
 
189
 
class TestRandChars(tests.TestCase):
190
 
 
191
115
    def test_01_rand_chars_empty(self):
192
116
        result = osutils.rand_chars(0)
193
117
        self.assertEqual(result, '')
198
122
        self.assertEqual(type(result), str)
199
123
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
200
124
 
201
 
 
202
 
class TestIsInside(tests.TestCase):
203
 
 
204
125
    def test_is_inside(self):
205
126
        is_inside = osutils.is_inside
206
127
        self.assertTrue(is_inside('src', 'src/foo.c'))
235
156
                         (['src'], 'srccontrol/foo')]:
236
157
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
237
158
 
238
 
 
239
 
class TestRmTree(tests.TestCaseInTempDir):
240
 
 
241
159
    def test_rmtree(self):
242
160
        # Check to remove tree with read-only files/dirs
243
161
        os.mkdir('dir')
256
174
        self.failIfExists('dir/file')
257
175
        self.failIfExists('dir')
258
176
 
259
 
 
260
 
class TestDeleteAny(tests.TestCaseInTempDir):
261
 
 
262
 
    def test_delete_any_readonly(self):
263
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
264
 
        self.build_tree(['d/', 'f'])
265
 
        osutils.make_readonly('d')
266
 
        osutils.make_readonly('f')
267
 
 
268
 
        osutils.delete_any('f')
269
 
        osutils.delete_any('d')
270
 
 
271
 
 
272
 
class TestKind(tests.TestCaseInTempDir):
273
 
 
274
177
    def test_file_kind(self):
275
178
        self.build_tree(['file', 'dir/'])
276
179
        self.assertEquals('file', osutils.file_kind('file'))
306
209
                os.remove('socket')
307
210
 
308
211
    def test_kind_marker(self):
309
 
        self.assertEqual("", osutils.kind_marker("file"))
310
 
        self.assertEqual("/", osutils.kind_marker('directory'))
311
 
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
312
 
        self.assertEqual("@", osutils.kind_marker("symlink"))
313
 
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
314
 
        self.assertEqual("", osutils.kind_marker("fifo"))
315
 
        self.assertEqual("", osutils.kind_marker("socket"))
316
 
        self.assertEqual("", osutils.kind_marker("unknown"))
317
 
 
318
 
 
319
 
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'), '+')
320
216
 
321
217
    def test_get_umask(self):
322
218
        if sys.platform == 'win32':
335
231
        os.umask(0027)
336
232
        self.assertEqual(0027, osutils.get_umask())
337
233
 
338
 
 
339
 
class TestDateTime(tests.TestCase):
340
 
 
341
234
    def assertFormatedDelta(self, expected, seconds):
342
235
        """Assert osutils.format_delta formats as expected"""
343
236
        actual = osutils.format_delta(seconds)
384
277
        # Instead blackbox.test_locale should check for localized
385
278
        # dates once they do occur in output strings.
386
279
 
387
 
    def test_format_date_with_offset_in_original_timezone(self):
388
 
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
389
 
            osutils.format_date_with_offset_in_original_timezone(0))
390
 
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
391
 
            osutils.format_date_with_offset_in_original_timezone(100000))
392
 
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
393
 
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
394
 
 
395
 
    def test_local_time_offset(self):
396
 
        """Test that local_time_offset() returns a sane value."""
397
 
        offset = osutils.local_time_offset()
398
 
        self.assertTrue(isinstance(offset, int))
399
 
        # Test that the offset is no more than a eighteen hours in
400
 
        # either direction.
401
 
        # Time zone handling is system specific, so it is difficult to
402
 
        # do more specific tests, but a value outside of this range is
403
 
        # probably wrong.
404
 
        eighteen_hours = 18 * 3600
405
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
406
 
 
407
 
    def test_local_time_offset_with_timestamp(self):
408
 
        """Test that local_time_offset() works with a timestamp."""
409
 
        offset = osutils.local_time_offset(1000000000.1234567)
410
 
        self.assertTrue(isinstance(offset, int))
411
 
        eighteen_hours = 18 * 3600
412
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
413
 
 
414
 
 
415
 
class TestLinks(tests.TestCaseInTempDir):
416
 
 
417
280
    def test_dereference_path(self):
418
281
        self.requireFeature(tests.SymlinkFeature)
419
282
        cwd = osutils.realpath('.')
462
325
            osutils.make_readonly('dangling')
463
326
            osutils.make_writable('dangling')
464
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
 
465
334
    def test_host_os_dereferences_symlinks(self):
466
335
        osutils.host_os_dereferences_symlinks()
467
336
 
473
342
    def test_canonical_relpath_simple(self):
474
343
        f = file('MixedCaseName', 'w')
475
344
        f.close()
476
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
 
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')
477
348
        self.failUnlessEqual('work/MixedCaseName', actual)
478
349
 
479
350
    def test_canonical_relpath_missing_tail(self):
480
351
        os.mkdir('MixedCaseParent')
481
 
        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,
482
355
                                           'mixedcaseparent/nochild')
483
356
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
484
357
 
485
358
 
486
 
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
487
 
 
488
 
    def assertRelpath(self, expected, base, path):
489
 
        actual = osutils._cicp_canonical_relpath(base, path)
490
 
        self.assertEqual(expected, actual)
491
 
 
492
 
    def test_simple(self):
493
 
        self.build_tree(['MixedCaseName'])
494
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
495
 
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
496
 
 
497
 
    def test_subdir_missing_tail(self):
498
 
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
499
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
500
 
        self.assertRelpath('MixedCaseParent/a_child', base,
501
 
                           'MixedCaseParent/a_child')
502
 
        self.assertRelpath('MixedCaseParent/a_child', base,
503
 
                           'MixedCaseParent/A_Child')
504
 
        self.assertRelpath('MixedCaseParent/not_child', base,
505
 
                           'MixedCaseParent/not_child')
506
 
 
507
 
    def test_at_root_slash(self):
508
 
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
509
 
        # check...
510
 
        if osutils.MIN_ABS_PATHLENGTH > 1:
511
 
            raise tests.TestSkipped('relpath requires %d chars'
512
 
                                    % osutils.MIN_ABS_PATHLENGTH)
513
 
        self.assertRelpath('foo', '/', '/foo')
514
 
 
515
 
    def test_at_root_drive(self):
516
 
        if sys.platform != 'win32':
517
 
            raise tests.TestNotApplicable('we can only test drive-letter relative'
518
 
                                          ' paths on Windows where we have drive'
519
 
                                          ' letters.')
520
 
        # see bug #322807
521
 
        # The specific issue is that when at the root of a drive, 'abspath'
522
 
        # returns "C:/" or just "/". However, the code assumes that abspath
523
 
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
524
 
        self.assertRelpath('foo', 'C:/', 'C:/foo')
525
 
        self.assertRelpath('foo', 'X:/', 'X:/foo')
526
 
        self.assertRelpath('foo', 'X:/', 'X://foo')
527
 
 
528
 
 
529
359
class TestPumpFile(tests.TestCase):
530
360
    """Test pumpfile method."""
531
361
 
691
521
        self.assertEqual("1234", output.getvalue())
692
522
 
693
523
 
694
 
class TestRelpath(tests.TestCase):
695
 
 
696
 
    def test_simple_relpath(self):
697
 
        cwd = osutils.getcwd()
698
 
        subdir = cwd + '/subdir'
699
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
700
 
 
701
 
    def test_deep_relpath(self):
702
 
        cwd = osutils.getcwd()
703
 
        subdir = cwd + '/sub/subsubdir'
704
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
705
 
 
706
 
    def test_not_relative(self):
707
 
        self.assertRaises(errors.PathNotChild,
708
 
                          osutils.relpath, 'C:/path', 'H:/path')
709
 
        self.assertRaises(errors.PathNotChild,
710
 
                          osutils.relpath, 'C:/', 'H:/path')
711
 
 
712
 
 
713
524
class TestSafeUnicode(tests.TestCase):
714
525
 
715
526
    def test_from_ascii_string(self):
862
673
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
863
674
        # relative path
864
675
        cwd = osutils.getcwd().rstrip('/')
865
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
676
        drive = osutils._nt_splitdrive(cwd)[0]
866
677
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
867
678
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
868
679
        # unicode path
886
697
    def test_minimum_path_selection(self):
887
698
        self.assertEqual(set(),
888
699
            osutils.minimum_path_selection([]))
889
 
        self.assertEqual(set(['a']),
890
 
            osutils.minimum_path_selection(['a']))
891
700
        self.assertEqual(set(['a', 'b']),
892
701
            osutils.minimum_path_selection(['a', 'b']))
893
702
        self.assertEqual(set(['a/', 'b']),
894
703
            osutils.minimum_path_selection(['a/', 'b']))
895
704
        self.assertEqual(set(['a/', 'b']),
896
705
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
897
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
898
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
899
706
 
900
707
    def test_mkdtemp(self):
901
708
        tmpdir = osutils._win32_mkdtemp(dir='.')
957
764
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
958
765
 
959
766
 
960
 
class TestParentDirectories(tests.TestCaseInTempDir):
961
 
    """Test osutils.parent_directories()"""
962
 
 
963
 
    def test_parent_directories(self):
964
 
        self.assertEqual([], osutils.parent_directories('a'))
965
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
966
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
967
 
 
968
 
 
969
767
class TestMacFuncsDirs(tests.TestCaseInTempDir):
970
768
    """Test mac special functions that require directories."""
971
769
 
993
791
 
994
792
    def test_osutils_binding(self):
995
793
        from bzrlib.tests import test__chunks_to_lines
996
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
 
794
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
997
795
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
998
796
        else:
999
797
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1015
813
 
1016
814
class TestWalkDirs(tests.TestCaseInTempDir):
1017
815
 
1018
 
    def assertExpectedBlocks(self, expected, result):
1019
 
        self.assertEqual(expected,
1020
 
                         [(dirinfo, [line[0:3] for line in block])
1021
 
                          for dirinfo, block in result])
1022
 
 
1023
816
    def test_walkdirs(self):
1024
817
        tree = [
1025
818
            '.bzr',
1057
850
            result.append((dirdetail, dirblock))
1058
851
 
1059
852
        self.assertTrue(found_bzrdir)
1060
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
853
        self.assertEqual(expected_dirblocks,
 
854
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1061
855
        # you can search a subdir only, with a supplied prefix.
1062
856
        result = []
1063
857
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1064
858
            result.append(dirblock)
1065
 
        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])
1066
861
 
1067
862
    def test_walkdirs_os_error(self):
1068
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
863
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1069
864
        # Pyrex readdir didn't raise useful messages if it had an error
1070
865
        # reading the directory
1071
866
        if sys.platform == 'win32':
1072
867
            raise tests.TestNotApplicable(
1073
868
                "readdir IOError not tested on win32")
1074
 
        self.requireFeature(features.not_running_as_root)
1075
869
        os.mkdir("test-unreadable")
1076
870
        os.chmod("test-unreadable", 0000)
1077
871
        # must chmod it back so that it can be removed
1078
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
 
872
        self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
1079
873
        # The error is not raised until the generator is actually evaluated.
1080
874
        # (It would be ok if it happened earlier but at the moment it
1081
875
        # doesn't.)
1085
879
        # Ensure the message contains the file name
1086
880
        self.assertContainsRe(str(e), "\./test-unreadable")
1087
881
 
1088
 
 
1089
 
    def test_walkdirs_encoding_error(self):
1090
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1091
 
        # walkdirs didn't raise a useful message when the filenames
1092
 
        # are not using the filesystem's encoding
1093
 
 
1094
 
        # require a bytestring based filesystem
1095
 
        self.requireFeature(tests.ByteStringNamedFilesystem)
1096
 
 
1097
 
        tree = [
1098
 
            '.bzr',
1099
 
            '0file',
1100
 
            '1dir/',
1101
 
            '1dir/0file',
1102
 
            '1dir/1dir/',
1103
 
            '1file'
1104
 
            ]
1105
 
 
1106
 
        self.build_tree(tree)
1107
 
 
1108
 
        # rename the 1file to a latin-1 filename
1109
 
        os.rename("./1file", "\xe8file")
1110
 
 
1111
 
        self._save_platform_info()
1112
 
        win32utils.winver = None # Avoid the win32 detection code
1113
 
        osutils._fs_enc = 'UTF-8'
1114
 
 
1115
 
        # this should raise on error
1116
 
        def attempt():
1117
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1118
 
                pass
1119
 
 
1120
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1121
 
 
1122
882
    def test__walkdirs_utf8(self):
1123
883
        tree = [
1124
884
            '.bzr',
1156
916
            result.append((dirdetail, dirblock))
1157
917
 
1158
918
        self.assertTrue(found_bzrdir)
1159
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1160
 
 
 
919
        self.assertEqual(expected_dirblocks,
 
920
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1161
921
        # you can search a subdir only, with a supplied prefix.
1162
922
        result = []
1163
923
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1164
924
            result.append(dirblock)
1165
 
        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])
1166
927
 
1167
928
    def _filter_out_stat(self, result):
1168
929
        """Filter out the stat value from the walkdirs result"""
1174
935
            dirblock[:] = new_dirblock
1175
936
 
1176
937
    def _save_platform_info(self):
1177
 
        self.overrideAttr(win32utils, 'winver')
1178
 
        self.overrideAttr(osutils, '_fs_enc')
1179
 
        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)
1180
946
 
1181
 
    def assertDirReaderIs(self, expected):
 
947
    def assertReadFSDirIs(self, expected):
1182
948
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1183
949
        # Force it to redetect
1184
950
        osutils._selected_dir_reader = None
1191
957
        self._save_platform_info()
1192
958
        win32utils.winver = None # Avoid the win32 detection code
1193
959
        osutils._fs_enc = 'UTF-8'
1194
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
960
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1195
961
 
1196
962
    def test_force_walkdirs_utf8_fs_ascii(self):
1197
963
        self.requireFeature(UTF8DirReaderFeature)
1198
964
        self._save_platform_info()
1199
965
        win32utils.winver = None # Avoid the win32 detection code
1200
966
        osutils._fs_enc = 'US-ASCII'
1201
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
967
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1202
968
 
1203
969
    def test_force_walkdirs_utf8_fs_ANSI(self):
1204
970
        self.requireFeature(UTF8DirReaderFeature)
1205
971
        self._save_platform_info()
1206
972
        win32utils.winver = None # Avoid the win32 detection code
1207
973
        osutils._fs_enc = 'ANSI_X3.4-1968'
1208
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
974
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1209
975
 
1210
976
    def test_force_walkdirs_utf8_fs_latin1(self):
1211
977
        self._save_platform_info()
1212
978
        win32utils.winver = None # Avoid the win32 detection code
1213
979
        osutils._fs_enc = 'latin1'
1214
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
980
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1215
981
 
1216
982
    def test_force_walkdirs_utf8_nt(self):
1217
983
        # Disabled because the thunk of the whole walkdirs api is disabled.
1218
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
984
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1219
985
        self._save_platform_info()
1220
986
        win32utils.winver = 'Windows NT'
1221
987
        from bzrlib._walkdirs_win32 import Win32ReadDir
1222
 
        self.assertDirReaderIs(Win32ReadDir)
 
988
        self.assertReadFSDirIs(Win32ReadDir)
1223
989
 
1224
990
    def test_force_walkdirs_utf8_98(self):
1225
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
991
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1226
992
        self._save_platform_info()
1227
993
        win32utils.winver = 'Windows 98'
1228
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
994
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1229
995
 
1230
996
    def test_unicode_walkdirs(self):
1231
997
        """Walkdirs should always return unicode paths."""
1379
1145
        self.assertEqual(expected_dirblocks, result)
1380
1146
 
1381
1147
    def test__walkdirs_utf8_win32readdir(self):
1382
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1148
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1383
1149
        self.requireFeature(tests.UnicodeFilenameFeature)
1384
1150
        from bzrlib._walkdirs_win32 import Win32ReadDir
1385
1151
        self._save_platform_info()
1436
1202
 
1437
1203
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1438
1204
        """make sure our Stat values are valid"""
1439
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1205
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1440
1206
        self.requireFeature(tests.UnicodeFilenameFeature)
1441
1207
        from bzrlib._walkdirs_win32 import Win32ReadDir
1442
1208
        name0u = u'0file-\xb6'
1460
1226
 
1461
1227
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1462
1228
        """make sure our Stat values are valid"""
1463
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1229
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1464
1230
        self.requireFeature(tests.UnicodeFilenameFeature)
1465
1231
        from bzrlib._walkdirs_win32 import Win32ReadDir
1466
1232
        name0u = u'0dir-\u062c\u0648'
1615
1381
        def cleanup():
1616
1382
            if 'BZR_TEST_ENV_VAR' in os.environ:
1617
1383
                del os.environ['BZR_TEST_ENV_VAR']
 
1384
 
1618
1385
        self.addCleanup(cleanup)
1619
1386
 
1620
1387
    def test_set(self):
1653
1420
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1654
1421
 
1655
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)
 
1443
 
 
1444
 
1656
1445
class TestSizeShaFile(tests.TestCaseInTempDir):
1657
1446
 
1658
1447
    def test_sha_empty(self):
1668
1457
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1669
1458
        self.build_tree_contents([('foo', text)])
1670
1459
        expected_sha = osutils.sha_string(text)
1671
 
        f = open('foo', 'rb')
 
1460
        f = open('foo')
1672
1461
        self.addCleanup(f.close)
1673
1462
        size, sha = osutils.size_sha_file(f)
1674
1463
        self.assertEqual(38, size)
1707
1496
 
1708
1497
class TestReCompile(tests.TestCase):
1709
1498
 
1710
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1711
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1712
 
            osutils.re_compile_checked, *args, **kwargs)
1713
 
 
1714
1499
    def test_re_compile_checked(self):
1715
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1500
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1716
1501
        self.assertTrue(r.match('aaaa'))
1717
1502
        self.assertTrue(r.match('aAaA'))
1718
1503
 
1719
1504
    def test_re_compile_checked_error(self):
1720
1505
        # like https://bugs.launchpad.net/bzr/+bug/251352
1721
 
 
1722
 
        # Due to possible test isolation error, re.compile is not lazy at
1723
 
        # this point. We re-install lazy compile.
1724
 
        lazy_regex.install_lazy_compile()
1725
1506
        err = self.assertRaises(
1726
1507
            errors.BzrCommandError,
1727
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1508
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1728
1509
        self.assertEqual(
1729
 
            'Invalid regular expression in test case: '
1730
 
            '"*" nothing to repeat',
 
1510
            "Invalid regular expression in test case: '*': "
 
1511
            "nothing to repeat",
1731
1512
            str(err))
1732
 
 
1733
 
 
1734
 
class TestDirReader(tests.TestCaseInTempDir):
1735
 
 
1736
 
    # Set by load_tests
1737
 
    _dir_reader_class = None
1738
 
    _native_to_unicode = None
1739
 
 
1740
 
    def setUp(self):
1741
 
        tests.TestCaseInTempDir.setUp(self)
1742
 
        self.overrideAttr(osutils,
1743
 
                          '_selected_dir_reader', self._dir_reader_class())
1744
 
 
1745
 
    def _get_ascii_tree(self):
1746
 
        tree = [
1747
 
            '0file',
1748
 
            '1dir/',
1749
 
            '1dir/0file',
1750
 
            '1dir/1dir/',
1751
 
            '2file'
1752
 
            ]
1753
 
        expected_dirblocks = [
1754
 
                (('', '.'),
1755
 
                 [('0file', '0file', 'file'),
1756
 
                  ('1dir', '1dir', 'directory'),
1757
 
                  ('2file', '2file', 'file'),
1758
 
                 ]
1759
 
                ),
1760
 
                (('1dir', './1dir'),
1761
 
                 [('1dir/0file', '0file', 'file'),
1762
 
                  ('1dir/1dir', '1dir', 'directory'),
1763
 
                 ]
1764
 
                ),
1765
 
                (('1dir/1dir', './1dir/1dir'),
1766
 
                 [
1767
 
                 ]
1768
 
                ),
1769
 
            ]
1770
 
        return tree, expected_dirblocks
1771
 
 
1772
 
    def test_walk_cur_dir(self):
1773
 
        tree, expected_dirblocks = self._get_ascii_tree()
1774
 
        self.build_tree(tree)
1775
 
        result = list(osutils._walkdirs_utf8('.'))
1776
 
        # Filter out stat and abspath
1777
 
        self.assertEqual(expected_dirblocks,
1778
 
                         [(dirinfo, [line[0:3] for line in block])
1779
 
                          for dirinfo, block in result])
1780
 
 
1781
 
    def test_walk_sub_dir(self):
1782
 
        tree, expected_dirblocks = self._get_ascii_tree()
1783
 
        self.build_tree(tree)
1784
 
        # you can search a subdir only, with a supplied prefix.
1785
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1786
 
        # Filter out stat and abspath
1787
 
        self.assertEqual(expected_dirblocks[1:],
1788
 
                         [(dirinfo, [line[0:3] for line in block])
1789
 
                          for dirinfo, block in result])
1790
 
 
1791
 
    def _get_unicode_tree(self):
1792
 
        name0u = u'0file-\xb6'
1793
 
        name1u = u'1dir-\u062c\u0648'
1794
 
        name2u = u'2file-\u0633'
1795
 
        tree = [
1796
 
            name0u,
1797
 
            name1u + '/',
1798
 
            name1u + '/' + name0u,
1799
 
            name1u + '/' + name1u + '/',
1800
 
            name2u,
1801
 
            ]
1802
 
        name0 = name0u.encode('UTF-8')
1803
 
        name1 = name1u.encode('UTF-8')
1804
 
        name2 = name2u.encode('UTF-8')
1805
 
        expected_dirblocks = [
1806
 
                (('', '.'),
1807
 
                 [(name0, name0, 'file', './' + name0u),
1808
 
                  (name1, name1, 'directory', './' + name1u),
1809
 
                  (name2, name2, 'file', './' + name2u),
1810
 
                 ]
1811
 
                ),
1812
 
                ((name1, './' + name1u),
1813
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1814
 
                                                        + '/' + name0u),
1815
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1816
 
                                                            + '/' + name1u),
1817
 
                 ]
1818
 
                ),
1819
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1820
 
                 [
1821
 
                 ]
1822
 
                ),
1823
 
            ]
1824
 
        return tree, expected_dirblocks
1825
 
 
1826
 
    def _filter_out(self, raw_dirblocks):
1827
 
        """Filter out a walkdirs_utf8 result.
1828
 
 
1829
 
        stat field is removed, all native paths are converted to unicode
1830
 
        """
1831
 
        filtered_dirblocks = []
1832
 
        for dirinfo, block in raw_dirblocks:
1833
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1834
 
            details = []
1835
 
            for line in block:
1836
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1837
 
            filtered_dirblocks.append((dirinfo, details))
1838
 
        return filtered_dirblocks
1839
 
 
1840
 
    def test_walk_unicode_tree(self):
1841
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1842
 
        tree, expected_dirblocks = self._get_unicode_tree()
1843
 
        self.build_tree(tree)
1844
 
        result = list(osutils._walkdirs_utf8('.'))
1845
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1846
 
 
1847
 
    def test_symlink(self):
1848
 
        self.requireFeature(tests.SymlinkFeature)
1849
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1850
 
        target = u'target\N{Euro Sign}'
1851
 
        link_name = u'l\N{Euro Sign}nk'
1852
 
        os.symlink(target, link_name)
1853
 
        target_utf8 = target.encode('UTF-8')
1854
 
        link_name_utf8 = link_name.encode('UTF-8')
1855
 
        expected_dirblocks = [
1856
 
                (('', '.'),
1857
 
                 [(link_name_utf8, link_name_utf8,
1858
 
                   'symlink', './' + link_name),],
1859
 
                 )]
1860
 
        result = list(osutils._walkdirs_utf8('.'))
1861
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1862
 
 
1863
 
 
1864
 
class TestReadLink(tests.TestCaseInTempDir):
1865
 
    """Exposes os.readlink() problems and the osutils solution.
1866
 
 
1867
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1868
 
    unicode string will be returned if a unicode string is passed.
1869
 
 
1870
 
    But prior python versions failed to properly encode the passed unicode
1871
 
    string.
1872
 
    """
1873
 
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
1874
 
 
1875
 
    def setUp(self):
1876
 
        super(tests.TestCaseInTempDir, self).setUp()
1877
 
        self.link = u'l\N{Euro Sign}ink'
1878
 
        self.target = u'targe\N{Euro Sign}t'
1879
 
        os.symlink(self.target, self.link)
1880
 
 
1881
 
    def test_os_readlink_link_encoding(self):
1882
 
        if sys.version_info < (2, 6):
1883
 
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
1884
 
        else:
1885
 
            self.assertEquals(self.target,  os.readlink(self.link))
1886
 
 
1887
 
    def test_os_readlink_link_decoding(self):
1888
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
1889
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
1890
 
 
1891
 
 
1892
 
class TestConcurrency(tests.TestCase):
1893
 
 
1894
 
    def setUp(self):
1895
 
        super(TestConcurrency, self).setUp()
1896
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
1897
 
 
1898
 
    def test_local_concurrency(self):
1899
 
        concurrency = osutils.local_concurrency()
1900
 
        self.assertIsInstance(concurrency, int)
1901
 
 
1902
 
    def test_local_concurrency_environment_variable(self):
1903
 
        os.environ['BZR_CONCURRENCY'] = '2'
1904
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1905
 
        os.environ['BZR_CONCURRENCY'] = '3'
1906
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1907
 
        os.environ['BZR_CONCURRENCY'] = 'foo'
1908
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1909
 
 
1910
 
    def test_option_concurrency(self):
1911
 
        os.environ['BZR_CONCURRENCY'] = '1'
1912
 
        self.run_bzr('rocks --concurrency 42')
1913
 
        # Command line overrides envrionment variable
1914
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1915
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1916
 
 
1917
 
 
1918
 
class TestFailedToLoadExtension(tests.TestCase):
1919
 
 
1920
 
    def _try_loading(self):
1921
 
        try:
1922
 
            import bzrlib._fictional_extension_py
1923
 
        except ImportError, e:
1924
 
            osutils.failed_to_load_extension(e)
1925
 
            return True
1926
 
 
1927
 
    def setUp(self):
1928
 
        super(TestFailedToLoadExtension, self).setUp()
1929
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
1930
 
 
1931
 
    def test_failure_to_load(self):
1932
 
        self._try_loading()
1933
 
        self.assertLength(1, osutils._extension_load_failures)
1934
 
        self.assertEquals(osutils._extension_load_failures[0],
1935
 
            "No module named _fictional_extension_py")
1936
 
 
1937
 
    def test_report_extension_load_failures_no_warning(self):
1938
 
        self.assertTrue(self._try_loading())
1939
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1940
 
        # it used to give a Python warning; it no longer does
1941
 
        self.assertLength(0, warnings)
1942
 
 
1943
 
    def test_report_extension_load_failures_message(self):
1944
 
        log = StringIO()
1945
 
        trace.push_log_file(log)
1946
 
        self.assertTrue(self._try_loading())
1947
 
        osutils.report_extension_load_failures()
1948
 
        self.assertContainsRe(
1949
 
            log.getvalue(),
1950
 
            r"bzr: warning: some compiled extensions could not be loaded; "
1951
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1952
 
            )
1953
 
 
1954
 
 
1955
 
class TestTerminalWidth(tests.TestCase):
1956
 
 
1957
 
    def setUp(self):
1958
 
        tests.TestCase.setUp(self)
1959
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1960
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1961
 
        self.addCleanup(self.restore_osutils_globals)
1962
 
        osutils._terminal_size_state = 'no_data'
1963
 
        osutils._first_terminal_size = None
1964
 
 
1965
 
    def restore_osutils_globals(self):
1966
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1967
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1968
 
 
1969
 
    def replace_stdout(self, new):
1970
 
        self.overrideAttr(sys, 'stdout', new)
1971
 
 
1972
 
    def replace__terminal_size(self, new):
1973
 
        self.overrideAttr(osutils, '_terminal_size', new)
1974
 
 
1975
 
    def set_fake_tty(self):
1976
 
 
1977
 
        class I_am_a_tty(object):
1978
 
            def isatty(self):
1979
 
                return True
1980
 
 
1981
 
        self.replace_stdout(I_am_a_tty())
1982
 
 
1983
 
    def test_default_values(self):
1984
 
        self.assertEqual(80, osutils.default_terminal_width)
1985
 
 
1986
 
    def test_defaults_to_BZR_COLUMNS(self):
1987
 
        # BZR_COLUMNS is set by the test framework
1988
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
1989
 
        os.environ['BZR_COLUMNS'] = '12'
1990
 
        self.assertEqual(12, osutils.terminal_width())
1991
 
 
1992
 
    def test_falls_back_to_COLUMNS(self):
1993
 
        del os.environ['BZR_COLUMNS']
1994
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
1995
 
        self.set_fake_tty()
1996
 
        os.environ['COLUMNS'] = '42'
1997
 
        self.assertEqual(42, osutils.terminal_width())
1998
 
 
1999
 
    def test_tty_default_without_columns(self):
2000
 
        del os.environ['BZR_COLUMNS']
2001
 
        del os.environ['COLUMNS']
2002
 
 
2003
 
        def terminal_size(w, h):
2004
 
            return 42, 42
2005
 
 
2006
 
        self.set_fake_tty()
2007
 
        # We need to override the osutils definition as it depends on the
2008
 
        # running environment that we can't control (PQM running without a
2009
 
        # controlling terminal is one example).
2010
 
        self.replace__terminal_size(terminal_size)
2011
 
        self.assertEqual(42, osutils.terminal_width())
2012
 
 
2013
 
    def test_non_tty_default_without_columns(self):
2014
 
        del os.environ['BZR_COLUMNS']
2015
 
        del os.environ['COLUMNS']
2016
 
        self.replace_stdout(None)
2017
 
        self.assertEqual(None, osutils.terminal_width())
2018
 
 
2019
 
    def test_no_TIOCGWINSZ(self):
2020
 
        self.requireFeature(term_ios_feature)
2021
 
        termios = term_ios_feature.module
2022
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2023
 
        try:
2024
 
            orig = termios.TIOCGWINSZ
2025
 
        except AttributeError:
2026
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2027
 
            pass
2028
 
        else:
2029
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2030
 
            del termios.TIOCGWINSZ
2031
 
        del os.environ['BZR_COLUMNS']
2032
 
        del os.environ['COLUMNS']
2033
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2034
 
        osutils.terminal_width()
2035
 
 
2036
 
class TestCreationOps(tests.TestCaseInTempDir):
2037
 
    _test_needs_features = [features.chown_feature]
2038
 
 
2039
 
    def setUp(self):
2040
 
        tests.TestCaseInTempDir.setUp(self)
2041
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2042
 
 
2043
 
        # params set by call to _dummy_chown
2044
 
        self.path = self.uid = self.gid = None
2045
 
 
2046
 
    def _dummy_chown(self, path, uid, gid):
2047
 
        self.path, self.uid, self.gid = path, uid, gid
2048
 
 
2049
 
    def test_copy_ownership_from_path(self):
2050
 
        """copy_ownership_from_path test with specified src."""
2051
 
        ownsrc = '/'
2052
 
        f = open('test_file', 'wt')
2053
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2054
 
 
2055
 
        s = os.stat(ownsrc)
2056
 
        self.assertEquals(self.path, 'test_file')
2057
 
        self.assertEquals(self.uid, s.st_uid)
2058
 
        self.assertEquals(self.gid, s.st_gid)
2059
 
 
2060
 
    def test_copy_ownership_nonesrc(self):
2061
 
        """copy_ownership_from_path test with src=None."""
2062
 
        f = open('test_file', 'wt')
2063
 
        # should use parent dir for permissions
2064
 
        osutils.copy_ownership_from_path('test_file')
2065
 
 
2066
 
        s = os.stat('..')
2067
 
        self.assertEquals(self.path, 'test_file')
2068
 
        self.assertEquals(self.uid, s.st_uid)
2069
 
        self.assertEquals(self.gid, s.st_gid)
2070
 
 
2071
 
class TestGetuserUnicode(tests.TestCase):
2072
 
 
2073
 
    def test_ascii_user(self):
2074
 
        osutils.set_or_unset_env('LOGNAME', 'jrandom')
2075
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2076
 
 
2077
 
    def test_unicode_user(self):
2078
 
        ue = osutils.get_user_encoding()
2079
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2080
 
        if uni_val is None:
2081
 
            raise tests.TestSkipped(
2082
 
                'Cannot find a unicode character that works in encoding %s'
2083
 
                % (osutils.get_user_encoding(),))
2084
 
        uni_username = u'jrandom' + uni_val
2085
 
        encoded_username = uni_username.encode(ue)
2086
 
        osutils.set_or_unset_env('LOGNAME', encoded_username)
2087
 
        self.assertEqual(uni_username, osutils.getuser_unicode())