~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

(vila) Fix test failures blocking package builds. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2015 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
20
20
import errno
21
21
import os
22
22
import re
 
23
import select
23
24
import socket
24
 
import stat
25
25
import sys
 
26
import tempfile
26
27
import time
27
28
 
28
29
from bzrlib import (
29
30
    errors,
 
31
    lazy_regex,
30
32
    osutils,
 
33
    symbol_versioning,
31
34
    tests,
 
35
    trace,
32
36
    win32utils,
33
37
    )
34
38
from bzrlib.tests import (
 
39
    features,
35
40
    file_utils,
36
41
    test__walkdirs_win32,
37
42
    )
38
 
 
39
 
 
40
 
class _UTF8DirReaderFeature(tests.Feature):
 
43
from bzrlib.tests.scenarios import load_tests_apply_scenarios
 
44
 
 
45
 
 
46
class _UTF8DirReaderFeature(features.Feature):
41
47
 
42
48
    def _probe(self):
43
49
        try:
50
56
    def feature_name(self):
51
57
        return 'bzrlib._readdir_pyx'
52
58
 
53
 
UTF8DirReaderFeature = _UTF8DirReaderFeature()
 
59
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
 
60
 
 
61
term_ios_feature = features.ModuleAvailableFeature('termios')
54
62
 
55
63
 
56
64
def _already_unicode(s):
57
65
    return s
58
66
 
59
67
 
60
 
def _fs_enc_to_unicode(s):
61
 
    return s.decode(osutils._fs_enc)
62
 
 
63
 
 
64
68
def _utf8_to_unicode(s):
65
69
    return s.decode('UTF-8')
66
70
 
83
87
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
84
88
                               _native_to_unicode=_utf8_to_unicode)))
85
89
 
86
 
    if test__walkdirs_win32.Win32ReadDirFeature.available():
 
90
    if test__walkdirs_win32.win32_readdir_feature.available():
87
91
        try:
88
92
            from bzrlib import _walkdirs_win32
89
 
            # TODO: check on windows, it may be that we need to use/add
90
 
            # safe_unicode instead of _fs_enc_to_unicode
91
93
            scenarios.append(
92
94
                ('win32',
93
95
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
94
 
                      _native_to_unicode=_fs_enc_to_unicode)))
 
96
                      _native_to_unicode=_already_unicode)))
95
97
        except ImportError:
96
98
            pass
97
99
    return scenarios
98
100
 
99
101
 
100
 
def load_tests(basic_tests, module, loader):
101
 
    suite = loader.suiteClass()
102
 
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
103
 
        basic_tests, tests.condition_isinstance(TestDirReader))
104
 
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
105
 
    suite.addTest(remaining_tests)
106
 
    return suite
 
102
load_tests = load_tests_apply_scenarios
107
103
 
108
104
 
109
105
class TestContainsWhitespace(tests.TestCase):
110
106
 
111
107
    def test_contains_whitespace(self):
112
 
        self.failUnless(osutils.contains_whitespace(u' '))
113
 
        self.failUnless(osutils.contains_whitespace(u'hello there'))
114
 
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
115
 
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
116
 
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
117
 
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
 
108
        self.assertTrue(osutils.contains_whitespace(u' '))
 
109
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
 
110
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
 
111
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
 
112
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
 
113
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
118
114
 
119
115
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
120
116
        # is whitespace, but we do not.
121
 
        self.failIf(osutils.contains_whitespace(u''))
122
 
        self.failIf(osutils.contains_whitespace(u'hellothere'))
123
 
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
 
117
        self.assertFalse(osutils.contains_whitespace(u''))
 
118
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
 
119
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
124
120
 
125
121
 
126
122
class TestRename(tests.TestCaseInTempDir):
127
123
 
 
124
    def create_file(self, filename, content):
 
125
        f = open(filename, 'wb')
 
126
        try:
 
127
            f.write(content)
 
128
        finally:
 
129
            f.close()
 
130
 
 
131
    def _fancy_rename(self, a, b):
 
132
        osutils.fancy_rename(a, b, rename_func=os.rename,
 
133
                             unlink_func=os.unlink)
 
134
 
128
135
    def test_fancy_rename(self):
129
136
        # This should work everywhere
130
 
        def rename(a, b):
131
 
            osutils.fancy_rename(a, b,
132
 
                    rename_func=os.rename,
133
 
                    unlink_func=os.unlink)
134
 
 
135
 
        open('a', 'wb').write('something in a\n')
136
 
        rename('a', 'b')
137
 
        self.failIfExists('a')
138
 
        self.failUnlessExists('b')
 
137
        self.create_file('a', 'something in a\n')
 
138
        self._fancy_rename('a', 'b')
 
139
        self.assertPathDoesNotExist('a')
 
140
        self.assertPathExists('b')
139
141
        self.check_file_contents('b', 'something in a\n')
140
142
 
141
 
        open('a', 'wb').write('new something in a\n')
142
 
        rename('b', 'a')
 
143
        self.create_file('a', 'new something in a\n')
 
144
        self._fancy_rename('b', 'a')
143
145
 
144
146
        self.check_file_contents('a', 'something in a\n')
145
147
 
 
148
    def test_fancy_rename_fails_source_missing(self):
 
149
        # An exception should be raised, and the target should be left in place
 
150
        self.create_file('target', 'data in target\n')
 
151
        self.assertRaises((IOError, OSError), self._fancy_rename,
 
152
                          'missingsource', 'target')
 
153
        self.assertPathExists('target')
 
154
        self.check_file_contents('target', 'data in target\n')
 
155
 
 
156
    def test_fancy_rename_fails_if_source_and_target_missing(self):
 
157
        self.assertRaises((IOError, OSError), self._fancy_rename,
 
158
                          'missingsource', 'missingtarget')
 
159
 
146
160
    def test_rename(self):
147
161
        # Rename should be semi-atomic on all platforms
148
 
        open('a', 'wb').write('something in a\n')
 
162
        self.create_file('a', 'something in a\n')
149
163
        osutils.rename('a', 'b')
150
 
        self.failIfExists('a')
151
 
        self.failUnlessExists('b')
 
164
        self.assertPathDoesNotExist('a')
 
165
        self.assertPathExists('b')
152
166
        self.check_file_contents('b', 'something in a\n')
153
167
 
154
 
        open('a', 'wb').write('new something in a\n')
 
168
        self.create_file('a', 'new something in a\n')
155
169
        osutils.rename('b', 'a')
156
170
 
157
171
        self.check_file_contents('a', 'something in a\n')
168
182
        shape = sorted(os.listdir('.'))
169
183
        self.assertEquals(['A', 'B'], shape)
170
184
 
 
185
    def test_rename_exception(self):
 
186
        try:
 
187
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
 
188
        except OSError, e:
 
189
            self.assertEqual(e.old_filename, 'nonexistent_path')
 
190
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
 
191
            self.assertTrue('nonexistent_path' in e.strerror)
 
192
            self.assertTrue('different_nonexistent_path' in e.strerror)
 
193
 
171
194
 
172
195
class TestRandChars(tests.TestCase):
173
196
 
219
242
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
220
243
 
221
244
 
 
245
class TestLstat(tests.TestCaseInTempDir):
 
246
 
 
247
    def test_lstat_matches_fstat(self):
 
248
        # On Windows, lstat and fstat don't always agree, primarily in the
 
249
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
 
250
        # custom implementation.
 
251
        if sys.platform == 'win32':
 
252
            # We only have special lstat/fstat if we have the extension.
 
253
            # Without it, we may end up re-reading content when we don't have
 
254
            # to, but otherwise it doesn't effect correctness.
 
255
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
256
        f = open('test-file.txt', 'wb')
 
257
        self.addCleanup(f.close)
 
258
        f.write('some content\n')
 
259
        f.flush()
 
260
        self.assertEqualStat(osutils.fstat(f.fileno()),
 
261
                             osutils.lstat('test-file.txt'))
 
262
 
 
263
 
222
264
class TestRmTree(tests.TestCaseInTempDir):
223
265
 
224
266
    def test_rmtree(self):
236
278
 
237
279
        osutils.rmtree('dir')
238
280
 
239
 
        self.failIfExists('dir/file')
240
 
        self.failIfExists('dir')
 
281
        self.assertPathDoesNotExist('dir/file')
 
282
        self.assertPathDoesNotExist('dir')
241
283
 
242
284
 
243
285
class TestDeleteAny(tests.TestCaseInTempDir):
294
336
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
295
337
        self.assertEqual("@", osutils.kind_marker("symlink"))
296
338
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
297
 
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
339
        self.assertEqual("", osutils.kind_marker("fifo"))
 
340
        self.assertEqual("", osutils.kind_marker("socket"))
 
341
        self.assertEqual("", osutils.kind_marker("unknown"))
298
342
 
299
343
 
300
344
class TestUmask(tests.TestCaseInTempDir):
365
409
        # Instead blackbox.test_locale should check for localized
366
410
        # dates once they do occur in output strings.
367
411
 
 
412
    def test_format_date_with_offset_in_original_timezone(self):
 
413
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
 
414
            osutils.format_date_with_offset_in_original_timezone(0))
 
415
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
 
416
            osutils.format_date_with_offset_in_original_timezone(100000))
 
417
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
 
418
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
 
419
 
368
420
    def test_local_time_offset(self):
369
421
        """Test that local_time_offset() returns a sane value."""
370
422
        offset = osutils.local_time_offset()
385
437
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
386
438
 
387
439
 
 
440
class TestFdatasync(tests.TestCaseInTempDir):
 
441
 
 
442
    def do_fdatasync(self):
 
443
        f = tempfile.NamedTemporaryFile()
 
444
        osutils.fdatasync(f.fileno())
 
445
        f.close()
 
446
 
 
447
    @staticmethod
 
448
    def raise_eopnotsupp(*args, **kwargs):
 
449
        raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
 
450
 
 
451
    @staticmethod
 
452
    def raise_enotsup(*args, **kwargs):
 
453
        raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
 
454
 
 
455
    def test_fdatasync_handles_system_function(self):
 
456
        self.overrideAttr(os, "fdatasync")
 
457
        self.do_fdatasync()
 
458
 
 
459
    def test_fdatasync_handles_no_fdatasync_no_fsync(self):
 
460
        self.overrideAttr(os, "fdatasync")
 
461
        self.overrideAttr(os, "fsync")
 
462
        self.do_fdatasync()
 
463
 
 
464
    def test_fdatasync_handles_no_EOPNOTSUPP(self):
 
465
        self.overrideAttr(errno, "EOPNOTSUPP")
 
466
        self.do_fdatasync()
 
467
 
 
468
    def test_fdatasync_catches_ENOTSUP(self):
 
469
        enotsup = getattr(errno, "ENOTSUP", None)
 
470
        if enotsup is None:
 
471
            raise tests.TestNotApplicable("No ENOTSUP on this platform")
 
472
        self.overrideAttr(os, "fdatasync", self.raise_enotsup)
 
473
        self.do_fdatasync()
 
474
 
 
475
    def test_fdatasync_catches_EOPNOTSUPP(self):
 
476
        enotsup = getattr(errno, "EOPNOTSUPP", None)
 
477
        if enotsup is None:
 
478
            raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
 
479
        self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
 
480
        self.do_fdatasync()
 
481
 
 
482
 
388
483
class TestLinks(tests.TestCaseInTempDir):
389
484
 
390
485
    def test_dereference_path(self):
391
 
        self.requireFeature(tests.SymlinkFeature)
 
486
        self.requireFeature(features.SymlinkFeature)
392
487
        cwd = osutils.realpath('.')
393
488
        os.mkdir('bar')
394
489
        bar_path = osutils.pathjoin(cwd, 'bar')
441
536
 
442
537
class TestCanonicalRelPath(tests.TestCaseInTempDir):
443
538
 
444
 
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
 
539
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
445
540
 
446
541
    def test_canonical_relpath_simple(self):
447
542
        f = file('MixedCaseName', 'w')
448
543
        f.close()
449
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
450
 
        real_base_dir = osutils.realpath(self.test_base_dir)
451
 
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
452
 
        self.failUnlessEqual('work/MixedCaseName', actual)
 
544
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
 
545
        self.assertEqual('work/MixedCaseName', actual)
453
546
 
454
547
    def test_canonical_relpath_missing_tail(self):
455
548
        os.mkdir('MixedCaseParent')
456
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
457
 
        real_base_dir = osutils.realpath(self.test_base_dir)
458
 
        actual = osutils.canonical_relpath(real_base_dir,
 
549
        actual = osutils.canonical_relpath(self.test_base_dir,
459
550
                                           'mixedcaseparent/nochild')
460
 
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
 
551
        self.assertEqual('work/MixedCaseParent/nochild', actual)
 
552
 
 
553
 
 
554
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
 
555
 
 
556
    def assertRelpath(self, expected, base, path):
 
557
        actual = osutils._cicp_canonical_relpath(base, path)
 
558
        self.assertEqual(expected, actual)
 
559
 
 
560
    def test_simple(self):
 
561
        self.build_tree(['MixedCaseName'])
 
562
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
 
563
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
 
564
 
 
565
    def test_subdir_missing_tail(self):
 
566
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
 
567
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
 
568
        self.assertRelpath('MixedCaseParent/a_child', base,
 
569
                           'MixedCaseParent/a_child')
 
570
        self.assertRelpath('MixedCaseParent/a_child', base,
 
571
                           'MixedCaseParent/A_Child')
 
572
        self.assertRelpath('MixedCaseParent/not_child', base,
 
573
                           'MixedCaseParent/not_child')
 
574
 
 
575
    def test_at_root_slash(self):
 
576
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
 
577
        # check...
 
578
        if osutils.MIN_ABS_PATHLENGTH > 1:
 
579
            raise tests.TestSkipped('relpath requires %d chars'
 
580
                                    % osutils.MIN_ABS_PATHLENGTH)
 
581
        self.assertRelpath('foo', '/', '/foo')
 
582
 
 
583
    def test_at_root_drive(self):
 
584
        if sys.platform != 'win32':
 
585
            raise tests.TestNotApplicable('we can only test drive-letter relative'
 
586
                                          ' paths on Windows where we have drive'
 
587
                                          ' letters.')
 
588
        # see bug #322807
 
589
        # The specific issue is that when at the root of a drive, 'abspath'
 
590
        # returns "C:/" or just "/". However, the code assumes that abspath
 
591
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
 
592
        self.assertRelpath('foo', 'C:/', 'C:/foo')
 
593
        self.assertRelpath('foo', 'X:/', 'X:/foo')
 
594
        self.assertRelpath('foo', 'X:/', 'X://foo')
461
595
 
462
596
 
463
597
class TestPumpFile(tests.TestCase):
464
598
    """Test pumpfile method."""
465
599
 
466
600
    def setUp(self):
467
 
        tests.TestCase.setUp(self)
 
601
        super(TestPumpFile, self).setUp()
468
602
        # create a test datablock
469
603
        self.block_size = 512
470
604
        pattern = '0123456789ABCDEF'
738
872
        self.assertEqual(None, osutils.safe_file_id(None))
739
873
 
740
874
 
 
875
class TestSendAll(tests.TestCase):
 
876
 
 
877
    def test_send_with_disconnected_socket(self):
 
878
        class DisconnectedSocket(object):
 
879
            def __init__(self, err):
 
880
                self.err = err
 
881
            def send(self, content):
 
882
                raise self.err
 
883
            def close(self):
 
884
                pass
 
885
        # All of these should be treated as ConnectionReset
 
886
        errs = []
 
887
        for err_cls in (IOError, socket.error):
 
888
            for errnum in osutils._end_of_stream_errors:
 
889
                errs.append(err_cls(errnum))
 
890
        for err in errs:
 
891
            sock = DisconnectedSocket(err)
 
892
            self.assertRaises(errors.ConnectionReset,
 
893
                osutils.send_all, sock, 'some more content')
 
894
 
 
895
    def test_send_with_no_progress(self):
 
896
        # See https://bugs.launchpad.net/bzr/+bug/1047309
 
897
        # It seems that paramiko can get into a state where it doesn't error,
 
898
        # but it returns 0 bytes sent for requests over and over again.
 
899
        class NoSendingSocket(object):
 
900
            def __init__(self):
 
901
                self.call_count = 0
 
902
            def send(self, bytes):
 
903
                self.call_count += 1
 
904
                if self.call_count > 100:
 
905
                    # Prevent the test suite from hanging
 
906
                    raise RuntimeError('too many calls')
 
907
                return 0
 
908
        sock = NoSendingSocket()
 
909
        self.assertRaises(errors.ConnectionReset,
 
910
                          osutils.send_all, sock, 'content')
 
911
        self.assertEqual(1, sock.call_count)
 
912
 
 
913
 
 
914
class TestPosixFuncs(tests.TestCase):
 
915
    """Test that the posix version of normpath returns an appropriate path
 
916
       when used with 2 leading slashes."""
 
917
 
 
918
    def test_normpath(self):
 
919
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
 
920
        self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
 
921
        self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
 
922
 
 
923
 
741
924
class TestWin32Funcs(tests.TestCase):
742
925
    """Test that _win32 versions of os utilities return appropriate paths."""
743
926
 
744
927
    def test_abspath(self):
 
928
        self.requireFeature(features.win32_feature)
745
929
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
746
930
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
747
931
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
760
944
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
761
945
        self.assertEqual('path/to/foo',
762
946
                         osutils._win32_pathjoin('path/to/', 'foo'))
763
 
        self.assertEqual('/foo',
 
947
 
 
948
    def test_pathjoin_late_bugfix(self):
 
949
        if sys.version_info < (2, 7, 6):
 
950
            expected = '/foo'
 
951
        else:
 
952
            expected = 'C:/foo'
 
953
        self.assertEqual(expected,
764
954
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
765
 
        self.assertEqual('/foo',
 
955
        self.assertEqual(expected,
766
956
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
767
957
 
768
958
    def test_normpath(self):
788
978
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
789
979
 
790
980
    def test_win98_abspath(self):
 
981
        self.requireFeature(features.win32_feature)
791
982
        # absolute path
792
983
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
793
984
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
796
987
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
797
988
        # relative path
798
989
        cwd = osutils.getcwd().rstrip('/')
799
 
        drive = osutils._nt_splitdrive(cwd)[0]
 
990
        drive = osutils.ntpath.splitdrive(cwd)[0]
800
991
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
801
992
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
802
993
        # unicode path
808
999
    """Test win32 functions that create files."""
809
1000
 
810
1001
    def test_getcwd(self):
811
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1002
        self.requireFeature(features.UnicodeFilenameFeature)
812
1003
        os.mkdir(u'mu-\xb5')
813
1004
        os.chdir(u'mu-\xb5')
814
1005
        # TODO: jam 20060427 This will probably fail on Mac OSX because
844
1035
        b.close()
845
1036
 
846
1037
        osutils._win32_rename('b', 'a')
847
 
        self.failUnlessExists('a')
848
 
        self.failIfExists('b')
 
1038
        self.assertPathExists('a')
 
1039
        self.assertPathDoesNotExist('b')
849
1040
        self.assertFileEqual('baz\n', 'a')
850
1041
 
851
1042
    def test_rename_missing_file(self):
904
1095
    """Test mac special functions that require directories."""
905
1096
 
906
1097
    def test_getcwd(self):
907
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1098
        self.requireFeature(features.UnicodeFilenameFeature)
908
1099
        os.mkdir(u'B\xe5gfors')
909
1100
        os.chdir(u'B\xe5gfors')
910
1101
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
911
1102
 
912
1103
    def test_getcwd_nonnorm(self):
913
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1104
        self.requireFeature(features.UnicodeFilenameFeature)
914
1105
        # Test that _mac_getcwd() will normalize this path
915
1106
        os.mkdir(u'Ba\u030agfors')
916
1107
        os.chdir(u'Ba\u030agfors')
927
1118
 
928
1119
    def test_osutils_binding(self):
929
1120
        from bzrlib.tests import test__chunks_to_lines
930
 
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
 
1121
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
931
1122
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
932
1123
        else:
933
1124
            from bzrlib._chunks_to_lines_py import chunks_to_lines
999
1190
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1000
1191
 
1001
1192
    def test_walkdirs_os_error(self):
1002
 
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
 
1193
        # <https://bugs.launchpad.net/bzr/+bug/338653>
1003
1194
        # Pyrex readdir didn't raise useful messages if it had an error
1004
1195
        # reading the directory
1005
1196
        if sys.platform == 'win32':
1006
1197
            raise tests.TestNotApplicable(
1007
1198
                "readdir IOError not tested on win32")
 
1199
        self.requireFeature(features.not_running_as_root)
1008
1200
        os.mkdir("test-unreadable")
1009
1201
        os.chmod("test-unreadable", 0000)
1010
1202
        # must chmod it back so that it can be removed
1018
1210
        # Ensure the message contains the file name
1019
1211
        self.assertContainsRe(str(e), "\./test-unreadable")
1020
1212
 
 
1213
 
 
1214
    def test_walkdirs_encoding_error(self):
 
1215
        # <https://bugs.launchpad.net/bzr/+bug/488519>
 
1216
        # walkdirs didn't raise a useful message when the filenames
 
1217
        # are not using the filesystem's encoding
 
1218
 
 
1219
        # require a bytestring based filesystem
 
1220
        self.requireFeature(features.ByteStringNamedFilesystem)
 
1221
 
 
1222
        tree = [
 
1223
            '.bzr',
 
1224
            '0file',
 
1225
            '1dir/',
 
1226
            '1dir/0file',
 
1227
            '1dir/1dir/',
 
1228
            '1file'
 
1229
            ]
 
1230
 
 
1231
        self.build_tree(tree)
 
1232
 
 
1233
        # rename the 1file to a latin-1 filename
 
1234
        os.rename("./1file", "\xe8file")
 
1235
        if "\xe8file" not in os.listdir("."):
 
1236
            self.skip("Lack filesystem that preserves arbitrary bytes")
 
1237
 
 
1238
        self._save_platform_info()
 
1239
        win32utils.winver = None # Avoid the win32 detection code
 
1240
        osutils._fs_enc = 'UTF-8'
 
1241
 
 
1242
        # this should raise on error
 
1243
        def attempt():
 
1244
            for dirdetail, dirblock in osutils.walkdirs('.'):
 
1245
                pass
 
1246
 
 
1247
        self.assertRaises(errors.BadFilenameEncoding, attempt)
 
1248
 
1021
1249
    def test__walkdirs_utf8(self):
1022
1250
        tree = [
1023
1251
            '.bzr',
1073
1301
            dirblock[:] = new_dirblock
1074
1302
 
1075
1303
    def _save_platform_info(self):
1076
 
        cur_winver = win32utils.winver
1077
 
        cur_fs_enc = osutils._fs_enc
1078
 
        cur_dir_reader = osutils._selected_dir_reader
1079
 
        def restore():
1080
 
            win32utils.winver = cur_winver
1081
 
            osutils._fs_enc = cur_fs_enc
1082
 
            osutils._selected_dir_reader = cur_dir_reader
1083
 
        self.addCleanup(restore)
 
1304
        self.overrideAttr(win32utils, 'winver')
 
1305
        self.overrideAttr(osutils, '_fs_enc')
 
1306
        self.overrideAttr(osutils, '_selected_dir_reader')
1084
1307
 
1085
1308
    def assertDirReaderIs(self, expected):
1086
1309
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1094
1317
        self.requireFeature(UTF8DirReaderFeature)
1095
1318
        self._save_platform_info()
1096
1319
        win32utils.winver = None # Avoid the win32 detection code
1097
 
        osutils._fs_enc = 'UTF-8'
1098
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1320
        osutils._fs_enc = 'utf-8'
 
1321
        self.assertDirReaderIs(
 
1322
            UTF8DirReaderFeature.module.UTF8DirReader)
1099
1323
 
1100
1324
    def test_force_walkdirs_utf8_fs_ascii(self):
1101
1325
        self.requireFeature(UTF8DirReaderFeature)
1102
1326
        self._save_platform_info()
1103
1327
        win32utils.winver = None # Avoid the win32 detection code
1104
 
        osutils._fs_enc = 'US-ASCII'
1105
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1106
 
 
1107
 
    def test_force_walkdirs_utf8_fs_ANSI(self):
1108
 
        self.requireFeature(UTF8DirReaderFeature)
1109
 
        self._save_platform_info()
1110
 
        win32utils.winver = None # Avoid the win32 detection code
1111
 
        osutils._fs_enc = 'ANSI_X3.4-1968'
1112
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1328
        osutils._fs_enc = 'ascii'
 
1329
        self.assertDirReaderIs(
 
1330
            UTF8DirReaderFeature.module.UTF8DirReader)
1113
1331
 
1114
1332
    def test_force_walkdirs_utf8_fs_latin1(self):
1115
1333
        self._save_platform_info()
1116
1334
        win32utils.winver = None # Avoid the win32 detection code
1117
 
        osutils._fs_enc = 'latin1'
 
1335
        osutils._fs_enc = 'iso-8859-1'
1118
1336
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1119
1337
 
1120
1338
    def test_force_walkdirs_utf8_nt(self):
1121
1339
        # Disabled because the thunk of the whole walkdirs api is disabled.
1122
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1340
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1123
1341
        self._save_platform_info()
1124
1342
        win32utils.winver = 'Windows NT'
1125
1343
        from bzrlib._walkdirs_win32 import Win32ReadDir
1126
1344
        self.assertDirReaderIs(Win32ReadDir)
1127
1345
 
1128
1346
    def test_force_walkdirs_utf8_98(self):
1129
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1347
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1130
1348
        self._save_platform_info()
1131
1349
        win32utils.winver = 'Windows 98'
1132
1350
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1133
1351
 
1134
1352
    def test_unicode_walkdirs(self):
1135
1353
        """Walkdirs should always return unicode paths."""
1136
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1354
        self.requireFeature(features.UnicodeFilenameFeature)
1137
1355
        name0 = u'0file-\xb6'
1138
1356
        name1 = u'1dir-\u062c\u0648'
1139
1357
        name2 = u'2file-\u0633'
1176
1394
 
1177
1395
        The abspath portion might be in unicode or utf-8
1178
1396
        """
1179
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1397
        self.requireFeature(features.UnicodeFilenameFeature)
1180
1398
        name0 = u'0file-\xb6'
1181
1399
        name1 = u'1dir-\u062c\u0648'
1182
1400
        name2 = u'2file-\u0633'
1237
1455
 
1238
1456
        The abspath portion should be in unicode
1239
1457
        """
1240
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1458
        self.requireFeature(features.UnicodeFilenameFeature)
1241
1459
        # Use the unicode reader. TODO: split into driver-and-driven unit
1242
1460
        # tests.
1243
1461
        self._save_platform_info()
1283
1501
        self.assertEqual(expected_dirblocks, result)
1284
1502
 
1285
1503
    def test__walkdirs_utf8_win32readdir(self):
1286
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1287
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1504
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1505
        self.requireFeature(features.UnicodeFilenameFeature)
1288
1506
        from bzrlib._walkdirs_win32 import Win32ReadDir
1289
1507
        self._save_platform_info()
1290
1508
        osutils._selected_dir_reader = Win32ReadDir()
1340
1558
 
1341
1559
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1342
1560
        """make sure our Stat values are valid"""
1343
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1344
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1561
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1562
        self.requireFeature(features.UnicodeFilenameFeature)
1345
1563
        from bzrlib._walkdirs_win32 import Win32ReadDir
1346
1564
        name0u = u'0file-\xb6'
1347
1565
        name0 = name0u.encode('utf8')
1364
1582
 
1365
1583
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1366
1584
        """make sure our Stat values are valid"""
1367
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1368
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1585
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1586
        self.requireFeature(features.UnicodeFilenameFeature)
1369
1587
        from bzrlib._walkdirs_win32 import Win32ReadDir
1370
1588
        name0u = u'0dir-\u062c\u0648'
1371
1589
        name0 = name0u.encode('utf8')
1471
1689
        self.assertEqual(['c'], os.listdir('target/b'))
1472
1690
 
1473
1691
    def test_copy_tree_symlinks(self):
1474
 
        self.requireFeature(tests.SymlinkFeature)
 
1692
        self.requireFeature(features.SymlinkFeature)
1475
1693
        self.build_tree(['source/'])
1476
1694
        os.symlink('a/generic/path', 'source/lnk')
1477
1695
        osutils.copy_tree('source', 'target')
1502
1720
                          ('d', 'source/b', 'target/b'),
1503
1721
                          ('f', 'source/b/c', 'target/b/c'),
1504
1722
                         ], processed_files)
1505
 
        self.failIfExists('target')
 
1723
        self.assertPathDoesNotExist('target')
1506
1724
        if osutils.has_symlinks():
1507
1725
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1508
1726
 
1519
1737
        def cleanup():
1520
1738
            if 'BZR_TEST_ENV_VAR' in os.environ:
1521
1739
                del os.environ['BZR_TEST_ENV_VAR']
1522
 
 
1523
1740
        self.addCleanup(cleanup)
1524
1741
 
1525
1742
    def test_set(self):
1555
1772
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1556
1773
        self.assertEqual('foo', old)
1557
1774
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1558
 
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1775
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1559
1776
 
1560
1777
 
1561
1778
class TestSizeShaFile(tests.TestCaseInTempDir):
1573
1790
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1574
1791
        self.build_tree_contents([('foo', text)])
1575
1792
        expected_sha = osutils.sha_string(text)
1576
 
        f = open('foo')
 
1793
        f = open('foo', 'rb')
1577
1794
        self.addCleanup(f.close)
1578
1795
        size, sha = osutils.size_sha_file(f)
1579
1796
        self.assertEqual(38, size)
1612
1829
 
1613
1830
class TestReCompile(tests.TestCase):
1614
1831
 
 
1832
    def _deprecated_re_compile_checked(self, *args, **kwargs):
 
1833
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
 
1834
            osutils.re_compile_checked, *args, **kwargs)
 
1835
 
1615
1836
    def test_re_compile_checked(self):
1616
 
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
 
1837
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1617
1838
        self.assertTrue(r.match('aaaa'))
1618
1839
        self.assertTrue(r.match('aAaA'))
1619
1840
 
1620
1841
    def test_re_compile_checked_error(self):
1621
1842
        # like https://bugs.launchpad.net/bzr/+bug/251352
 
1843
 
 
1844
        # Due to possible test isolation error, re.compile is not lazy at
 
1845
        # this point. We re-install lazy compile.
 
1846
        lazy_regex.install_lazy_compile()
1622
1847
        err = self.assertRaises(
1623
1848
            errors.BzrCommandError,
1624
 
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1849
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1625
1850
        self.assertEqual(
1626
 
            "Invalid regular expression in test case: '*': "
1627
 
            "nothing to repeat",
 
1851
            'Invalid regular expression in test case: '
 
1852
            '"*" nothing to repeat',
1628
1853
            str(err))
1629
1854
 
1630
1855
 
1631
1856
class TestDirReader(tests.TestCaseInTempDir):
1632
1857
 
 
1858
    scenarios = dir_reader_scenarios()
 
1859
 
1633
1860
    # Set by load_tests
1634
1861
    _dir_reader_class = None
1635
1862
    _native_to_unicode = None
1636
1863
 
1637
1864
    def setUp(self):
1638
 
        tests.TestCaseInTempDir.setUp(self)
1639
 
 
1640
 
        # Save platform specific info and reset it
1641
 
        cur_dir_reader = osutils._selected_dir_reader
1642
 
 
1643
 
        def restore():
1644
 
            osutils._selected_dir_reader = cur_dir_reader
1645
 
        self.addCleanup(restore)
1646
 
 
1647
 
        osutils._selected_dir_reader = self._dir_reader_class()
 
1865
        super(TestDirReader, self).setUp()
 
1866
        self.overrideAttr(osutils,
 
1867
                          '_selected_dir_reader', self._dir_reader_class())
1648
1868
 
1649
1869
    def _get_ascii_tree(self):
1650
1870
        tree = [
1742
1962
        return filtered_dirblocks
1743
1963
 
1744
1964
    def test_walk_unicode_tree(self):
1745
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1965
        self.requireFeature(features.UnicodeFilenameFeature)
1746
1966
        tree, expected_dirblocks = self._get_unicode_tree()
1747
1967
        self.build_tree(tree)
1748
1968
        result = list(osutils._walkdirs_utf8('.'))
1749
1969
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1750
1970
 
1751
1971
    def test_symlink(self):
1752
 
        self.requireFeature(tests.SymlinkFeature)
1753
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1972
        self.requireFeature(features.SymlinkFeature)
 
1973
        self.requireFeature(features.UnicodeFilenameFeature)
1754
1974
        target = u'target\N{Euro Sign}'
1755
1975
        link_name = u'l\N{Euro Sign}nk'
1756
1976
        os.symlink(target, link_name)
1774
1994
    But prior python versions failed to properly encode the passed unicode
1775
1995
    string.
1776
1996
    """
1777
 
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
 
1997
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1778
1998
 
1779
1999
    def setUp(self):
1780
2000
        super(tests.TestCaseInTempDir, self).setUp()
1783
2003
        os.symlink(self.target, self.link)
1784
2004
 
1785
2005
    def test_os_readlink_link_encoding(self):
1786
 
        if sys.version_info < (2, 6):
1787
 
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
1788
 
        else:
1789
 
            self.assertEquals(self.target,  os.readlink(self.link))
 
2006
        self.assertEquals(self.target,  os.readlink(self.link))
1790
2007
 
1791
2008
    def test_os_readlink_link_decoding(self):
1792
2009
        self.assertEquals(self.target.encode(osutils._fs_enc),
1795
2012
 
1796
2013
class TestConcurrency(tests.TestCase):
1797
2014
 
 
2015
    def setUp(self):
 
2016
        super(TestConcurrency, self).setUp()
 
2017
        self.overrideAttr(osutils, '_cached_local_concurrency')
 
2018
 
1798
2019
    def test_local_concurrency(self):
1799
2020
        concurrency = osutils.local_concurrency()
1800
2021
        self.assertIsInstance(concurrency, int)
 
2022
 
 
2023
    def test_local_concurrency_environment_variable(self):
 
2024
        self.overrideEnv('BZR_CONCURRENCY', '2')
 
2025
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
 
2026
        self.overrideEnv('BZR_CONCURRENCY', '3')
 
2027
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
 
2028
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
 
2029
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
 
2030
 
 
2031
    def test_option_concurrency(self):
 
2032
        self.overrideEnv('BZR_CONCURRENCY', '1')
 
2033
        self.run_bzr('rocks --concurrency 42')
 
2034
        # Command line overrides environment variable
 
2035
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
 
2036
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
 
2037
 
 
2038
 
 
2039
class TestFailedToLoadExtension(tests.TestCase):
 
2040
 
 
2041
    def _try_loading(self):
 
2042
        try:
 
2043
            import bzrlib._fictional_extension_py
 
2044
        except ImportError, e:
 
2045
            osutils.failed_to_load_extension(e)
 
2046
            return True
 
2047
 
 
2048
    def setUp(self):
 
2049
        super(TestFailedToLoadExtension, self).setUp()
 
2050
        self.overrideAttr(osutils, '_extension_load_failures', [])
 
2051
 
 
2052
    def test_failure_to_load(self):
 
2053
        self._try_loading()
 
2054
        self.assertLength(1, osutils._extension_load_failures)
 
2055
        self.assertEquals(osutils._extension_load_failures[0],
 
2056
            "No module named _fictional_extension_py")
 
2057
 
 
2058
    def test_report_extension_load_failures_no_warning(self):
 
2059
        self.assertTrue(self._try_loading())
 
2060
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
 
2061
        # it used to give a Python warning; it no longer does
 
2062
        self.assertLength(0, warnings)
 
2063
 
 
2064
    def test_report_extension_load_failures_message(self):
 
2065
        log = StringIO()
 
2066
        trace.push_log_file(log)
 
2067
        self.assertTrue(self._try_loading())
 
2068
        osutils.report_extension_load_failures()
 
2069
        self.assertContainsRe(
 
2070
            log.getvalue(),
 
2071
            r"bzr: warning: some compiled extensions could not be loaded; "
 
2072
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
 
2073
            )
 
2074
 
 
2075
 
 
2076
class TestTerminalWidth(tests.TestCase):
 
2077
 
 
2078
    def setUp(self):
 
2079
        super(TestTerminalWidth, self).setUp()
 
2080
        self._orig_terminal_size_state = osutils._terminal_size_state
 
2081
        self._orig_first_terminal_size = osutils._first_terminal_size
 
2082
        self.addCleanup(self.restore_osutils_globals)
 
2083
        osutils._terminal_size_state = 'no_data'
 
2084
        osutils._first_terminal_size = None
 
2085
 
 
2086
    def restore_osutils_globals(self):
 
2087
        osutils._terminal_size_state = self._orig_terminal_size_state
 
2088
        osutils._first_terminal_size = self._orig_first_terminal_size
 
2089
 
 
2090
    def replace_stdout(self, new):
 
2091
        self.overrideAttr(sys, 'stdout', new)
 
2092
 
 
2093
    def replace__terminal_size(self, new):
 
2094
        self.overrideAttr(osutils, '_terminal_size', new)
 
2095
 
 
2096
    def set_fake_tty(self):
 
2097
 
 
2098
        class I_am_a_tty(object):
 
2099
            def isatty(self):
 
2100
                return True
 
2101
 
 
2102
        self.replace_stdout(I_am_a_tty())
 
2103
 
 
2104
    def test_default_values(self):
 
2105
        self.assertEqual(80, osutils.default_terminal_width)
 
2106
 
 
2107
    def test_defaults_to_BZR_COLUMNS(self):
 
2108
        # BZR_COLUMNS is set by the test framework
 
2109
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
 
2110
        self.overrideEnv('BZR_COLUMNS', '12')
 
2111
        self.assertEqual(12, osutils.terminal_width())
 
2112
 
 
2113
    def test_BZR_COLUMNS_0_no_limit(self):
 
2114
        self.overrideEnv('BZR_COLUMNS', '0')
 
2115
        self.assertEqual(None, osutils.terminal_width())
 
2116
 
 
2117
    def test_falls_back_to_COLUMNS(self):
 
2118
        self.overrideEnv('BZR_COLUMNS', None)
 
2119
        self.assertNotEqual('42', os.environ['COLUMNS'])
 
2120
        self.set_fake_tty()
 
2121
        self.overrideEnv('COLUMNS', '42')
 
2122
        self.assertEqual(42, osutils.terminal_width())
 
2123
 
 
2124
    def test_tty_default_without_columns(self):
 
2125
        self.overrideEnv('BZR_COLUMNS', None)
 
2126
        self.overrideEnv('COLUMNS', None)
 
2127
 
 
2128
        def terminal_size(w, h):
 
2129
            return 42, 42
 
2130
 
 
2131
        self.set_fake_tty()
 
2132
        # We need to override the osutils definition as it depends on the
 
2133
        # running environment that we can't control (PQM running without a
 
2134
        # controlling terminal is one example).
 
2135
        self.replace__terminal_size(terminal_size)
 
2136
        self.assertEqual(42, osutils.terminal_width())
 
2137
 
 
2138
    def test_non_tty_default_without_columns(self):
 
2139
        self.overrideEnv('BZR_COLUMNS', None)
 
2140
        self.overrideEnv('COLUMNS', None)
 
2141
        self.replace_stdout(None)
 
2142
        self.assertEqual(None, osutils.terminal_width())
 
2143
 
 
2144
    def test_no_TIOCGWINSZ(self):
 
2145
        self.requireFeature(term_ios_feature)
 
2146
        termios = term_ios_feature.module
 
2147
        # bug 63539 is about a termios without TIOCGWINSZ attribute
 
2148
        try:
 
2149
            orig = termios.TIOCGWINSZ
 
2150
        except AttributeError:
 
2151
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
 
2152
            pass
 
2153
        else:
 
2154
            self.overrideAttr(termios, 'TIOCGWINSZ')
 
2155
            del termios.TIOCGWINSZ
 
2156
        self.overrideEnv('BZR_COLUMNS', None)
 
2157
        self.overrideEnv('COLUMNS', None)
 
2158
        # Whatever the result is, if we don't raise an exception, it's ok.
 
2159
        osutils.terminal_width()
 
2160
 
 
2161
 
 
2162
class TestCreationOps(tests.TestCaseInTempDir):
 
2163
    _test_needs_features = [features.chown_feature]
 
2164
 
 
2165
    def setUp(self):
 
2166
        super(TestCreationOps, self).setUp()
 
2167
        self.overrideAttr(os, 'chown', self._dummy_chown)
 
2168
 
 
2169
        # params set by call to _dummy_chown
 
2170
        self.path = self.uid = self.gid = None
 
2171
 
 
2172
    def _dummy_chown(self, path, uid, gid):
 
2173
        self.path, self.uid, self.gid = path, uid, gid
 
2174
 
 
2175
    def test_copy_ownership_from_path(self):
 
2176
        """copy_ownership_from_path test with specified src."""
 
2177
        ownsrc = '/'
 
2178
        f = open('test_file', 'wt')
 
2179
        osutils.copy_ownership_from_path('test_file', ownsrc)
 
2180
 
 
2181
        s = os.stat(ownsrc)
 
2182
        self.assertEquals(self.path, 'test_file')
 
2183
        self.assertEquals(self.uid, s.st_uid)
 
2184
        self.assertEquals(self.gid, s.st_gid)
 
2185
 
 
2186
    def test_copy_ownership_nonesrc(self):
 
2187
        """copy_ownership_from_path test with src=None."""
 
2188
        f = open('test_file', 'wt')
 
2189
        # should use parent dir for permissions
 
2190
        osutils.copy_ownership_from_path('test_file')
 
2191
 
 
2192
        s = os.stat('..')
 
2193
        self.assertEquals(self.path, 'test_file')
 
2194
        self.assertEquals(self.uid, s.st_uid)
 
2195
        self.assertEquals(self.gid, s.st_gid)
 
2196
 
 
2197
 
 
2198
class TestPathFromEnviron(tests.TestCase):
 
2199
 
 
2200
    def test_is_unicode(self):
 
2201
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
 
2202
        path = osutils.path_from_environ('BZR_TEST_PATH')
 
2203
        self.assertIsInstance(path, unicode)
 
2204
        self.assertEqual(u'./anywhere at all/', path)
 
2205
 
 
2206
    def test_posix_path_env_ascii(self):
 
2207
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
 
2208
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
 
2209
        self.assertIsInstance(home, unicode)
 
2210
        self.assertEqual(u'/tmp', home)
 
2211
 
 
2212
    def test_posix_path_env_unicode(self):
 
2213
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2214
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
 
2215
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2216
        self.assertEqual(u'/home/\xa7test',
 
2217
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
 
2218
        osutils._fs_enc = "iso8859-5"
 
2219
        self.assertEqual(u'/home/\u0407test',
 
2220
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
 
2221
        osutils._fs_enc = "utf-8"
 
2222
        self.assertRaises(errors.BadFilenameEncoding,
 
2223
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
 
2224
 
 
2225
 
 
2226
class TestGetHomeDir(tests.TestCase):
 
2227
 
 
2228
    def test_is_unicode(self):
 
2229
        home = osutils._get_home_dir()
 
2230
        self.assertIsInstance(home, unicode)
 
2231
 
 
2232
    def test_posix_homeless(self):
 
2233
        self.overrideEnv('HOME', None)
 
2234
        home = osutils._get_home_dir()
 
2235
        self.assertIsInstance(home, unicode)
 
2236
 
 
2237
    def test_posix_home_ascii(self):
 
2238
        self.overrideEnv('HOME', '/home/test')
 
2239
        home = osutils._posix_get_home_dir()
 
2240
        self.assertIsInstance(home, unicode)
 
2241
        self.assertEqual(u'/home/test', home)
 
2242
 
 
2243
    def test_posix_home_unicode(self):
 
2244
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2245
        self.overrideEnv('HOME', '/home/\xa7test')
 
2246
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2247
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
 
2248
        osutils._fs_enc = "iso8859-5"
 
2249
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
 
2250
        osutils._fs_enc = "utf-8"
 
2251
        self.assertRaises(errors.BadFilenameEncoding,
 
2252
            osutils._posix_get_home_dir)
 
2253
 
 
2254
 
 
2255
class TestGetuserUnicode(tests.TestCase):
 
2256
 
 
2257
    def test_is_unicode(self):
 
2258
        user = osutils.getuser_unicode()
 
2259
        self.assertIsInstance(user, unicode)
 
2260
 
 
2261
    def envvar_to_override(self):
 
2262
        if sys.platform == "win32":
 
2263
            # Disable use of platform calls on windows so envvar is used
 
2264
            self.overrideAttr(win32utils, 'has_ctypes', False)
 
2265
            return 'USERNAME' # only variable used on windows
 
2266
        return 'LOGNAME' # first variable checked by getpass.getuser()
 
2267
 
 
2268
    def test_ascii_user(self):
 
2269
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
 
2270
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
 
2271
 
 
2272
    def test_unicode_user(self):
 
2273
        ue = osutils.get_user_encoding()
 
2274
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
2275
        if uni_val is None:
 
2276
            raise tests.TestSkipped(
 
2277
                'Cannot find a unicode character that works in encoding %s'
 
2278
                % (osutils.get_user_encoding(),))
 
2279
        uni_username = u'jrandom' + uni_val
 
2280
        encoded_username = uni_username.encode(ue)
 
2281
        self.overrideEnv(self.envvar_to_override(), encoded_username)
 
2282
        self.assertEqual(uni_username, osutils.getuser_unicode())
 
2283
 
 
2284
 
 
2285
class TestBackupNames(tests.TestCase):
 
2286
 
 
2287
    def setUp(self):
 
2288
        super(TestBackupNames, self).setUp()
 
2289
        self.backups = []
 
2290
 
 
2291
    def backup_exists(self, name):
 
2292
        return name in self.backups
 
2293
 
 
2294
    def available_backup_name(self, name):
 
2295
        backup_name = osutils.available_backup_name(name, self.backup_exists)
 
2296
        self.backups.append(backup_name)
 
2297
        return backup_name
 
2298
 
 
2299
    def assertBackupName(self, expected, name):
 
2300
        self.assertEqual(expected, self.available_backup_name(name))
 
2301
 
 
2302
    def test_empty(self):
 
2303
        self.assertBackupName('file.~1~', 'file')
 
2304
 
 
2305
    def test_existing(self):
 
2306
        self.available_backup_name('file')
 
2307
        self.available_backup_name('file')
 
2308
        self.assertBackupName('file.~3~', 'file')
 
2309
        # Empty slots are found, this is not a strict requirement and may be
 
2310
        # revisited if we test against all implementations.
 
2311
        self.backups.remove('file.~2~')
 
2312
        self.assertBackupName('file.~2~', 'file')
 
2313
 
 
2314
 
 
2315
class TestFindExecutableInPath(tests.TestCase):
 
2316
 
 
2317
    def test_windows(self):
 
2318
        if sys.platform != 'win32':
 
2319
            raise tests.TestSkipped('test requires win32')
 
2320
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
 
2321
        self.assertTrue(
 
2322
            osutils.find_executable_on_path('explorer.exe') is not None)
 
2323
        self.assertTrue(
 
2324
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
 
2325
        self.assertTrue(
 
2326
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
 
2327
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
 
2328
        
 
2329
    def test_windows_app_path(self):
 
2330
        if sys.platform != 'win32':
 
2331
            raise tests.TestSkipped('test requires win32')
 
2332
        # Override PATH env var so that exe can only be found on App Path
 
2333
        self.overrideEnv('PATH', '')
 
2334
        # Internt Explorer is always registered in the App Path
 
2335
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
 
2336
 
 
2337
    def test_other(self):
 
2338
        if sys.platform == 'win32':
 
2339
            raise tests.TestSkipped('test requires non-win32')
 
2340
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
 
2341
        self.assertTrue(
 
2342
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
 
2343
 
 
2344
 
 
2345
class TestEnvironmentErrors(tests.TestCase):
 
2346
    """Test handling of environmental errors"""
 
2347
 
 
2348
    def test_is_oserror(self):
 
2349
        self.assertTrue(osutils.is_environment_error(
 
2350
            OSError(errno.EINVAL, "Invalid parameter")))
 
2351
 
 
2352
    def test_is_ioerror(self):
 
2353
        self.assertTrue(osutils.is_environment_error(
 
2354
            IOError(errno.EINVAL, "Invalid parameter")))
 
2355
 
 
2356
    def test_is_socket_error(self):
 
2357
        self.assertTrue(osutils.is_environment_error(
 
2358
            socket.error(errno.EINVAL, "Invalid parameter")))
 
2359
 
 
2360
    def test_is_select_error(self):
 
2361
        self.assertTrue(osutils.is_environment_error(
 
2362
            select.error(errno.EINVAL, "Invalid parameter")))
 
2363
 
 
2364
    def test_is_pywintypes_error(self):
 
2365
        self.requireFeature(features.pywintypes)
 
2366
        import pywintypes
 
2367
        self.assertTrue(osutils.is_environment_error(
 
2368
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))