/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_osutils.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-22 00:56:52 UTC
  • mfrom: (6621.2.26 py3_pokes)
  • Revision ID: jelmer@jelmer.uk-20170522005652-yjahcr9hwmjkno7n
Merge Python3 porting work ('py3 pokes')

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2016 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
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
19
 
from cStringIO import StringIO
20
19
import errno
21
20
import os
22
21
import re
 
22
import select
23
23
import socket
24
 
import stat
25
24
import sys
 
25
import tempfile
26
26
import time
27
27
 
28
 
from bzrlib import (
 
28
from .. import (
29
29
    errors,
 
30
    lazy_regex,
30
31
    osutils,
 
32
    symbol_versioning,
31
33
    tests,
32
34
    trace,
33
35
    win32utils,
34
36
    )
35
 
from bzrlib.tests import (
 
37
from ..sixish import (
 
38
    BytesIO,
 
39
    )
 
40
from . import (
36
41
    features,
37
42
    file_utils,
38
43
    test__walkdirs_win32,
39
44
    )
40
 
 
41
 
 
42
 
class _UTF8DirReaderFeature(tests.Feature):
 
45
from .scenarios import load_tests_apply_scenarios
 
46
 
 
47
 
 
48
class _UTF8DirReaderFeature(features.Feature):
43
49
 
44
50
    def _probe(self):
45
51
        try:
46
 
            from bzrlib import _readdir_pyx
 
52
            from .. import _readdir_pyx
47
53
            self.reader = _readdir_pyx.UTF8DirReader
48
54
            return True
49
55
        except ImportError:
50
56
            return False
51
57
 
52
58
    def feature_name(self):
53
 
        return 'bzrlib._readdir_pyx'
54
 
 
55
 
UTF8DirReaderFeature = _UTF8DirReaderFeature()
56
 
 
57
 
term_ios_feature = tests.ModuleAvailableFeature('termios')
 
59
        return 'breezy._readdir_pyx'
 
60
 
 
61
UTF8DirReaderFeature = features.ModuleAvailableFeature('breezy._readdir_pyx')
 
62
 
 
63
term_ios_feature = features.ModuleAvailableFeature('termios')
58
64
 
59
65
 
60
66
def _already_unicode(s):
78
84
    # Some DirReaders are platform specific and even there they may not be
79
85
    # available.
80
86
    if UTF8DirReaderFeature.available():
81
 
        from bzrlib import _readdir_pyx
 
87
        from .. import _readdir_pyx
82
88
        scenarios.append(('utf8',
83
89
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
84
90
                               _native_to_unicode=_utf8_to_unicode)))
85
91
 
86
92
    if test__walkdirs_win32.win32_readdir_feature.available():
87
93
        try:
88
 
            from bzrlib import _walkdirs_win32
 
94
            from .. import _walkdirs_win32
89
95
            scenarios.append(
90
96
                ('win32',
91
97
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
95
101
    return scenarios
96
102
 
97
103
 
98
 
def load_tests(basic_tests, module, loader):
99
 
    suite = loader.suiteClass()
100
 
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
101
 
        basic_tests, tests.condition_isinstance(TestDirReader))
102
 
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
103
 
    suite.addTest(remaining_tests)
104
 
    return suite
 
104
load_tests = load_tests_apply_scenarios
105
105
 
106
106
 
107
107
class TestContainsWhitespace(tests.TestCase):
108
108
 
109
109
    def test_contains_whitespace(self):
110
 
        self.failUnless(osutils.contains_whitespace(u' '))
111
 
        self.failUnless(osutils.contains_whitespace(u'hello there'))
112
 
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
113
 
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
114
 
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
115
 
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
 
110
        self.assertTrue(osutils.contains_whitespace(u' '))
 
111
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
 
112
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
 
113
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
 
114
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
 
115
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
116
116
 
117
117
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
118
118
        # is whitespace, but we do not.
119
 
        self.failIf(osutils.contains_whitespace(u''))
120
 
        self.failIf(osutils.contains_whitespace(u'hellothere'))
121
 
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
 
119
        self.assertFalse(osutils.contains_whitespace(u''))
 
120
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
 
121
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
122
122
 
123
123
 
124
124
class TestRename(tests.TestCaseInTempDir):
138
138
        # This should work everywhere
139
139
        self.create_file('a', 'something in a\n')
140
140
        self._fancy_rename('a', 'b')
141
 
        self.failIfExists('a')
142
 
        self.failUnlessExists('b')
 
141
        self.assertPathDoesNotExist('a')
 
142
        self.assertPathExists('b')
143
143
        self.check_file_contents('b', 'something in a\n')
144
144
 
145
145
        self.create_file('a', 'new something in a\n')
152
152
        self.create_file('target', 'data in target\n')
153
153
        self.assertRaises((IOError, OSError), self._fancy_rename,
154
154
                          'missingsource', 'target')
155
 
        self.failUnlessExists('target')
 
155
        self.assertPathExists('target')
156
156
        self.check_file_contents('target', 'data in target\n')
157
157
 
158
158
    def test_fancy_rename_fails_if_source_and_target_missing(self):
163
163
        # Rename should be semi-atomic on all platforms
164
164
        self.create_file('a', 'something in a\n')
165
165
        osutils.rename('a', 'b')
166
 
        self.failIfExists('a')
167
 
        self.failUnlessExists('b')
 
166
        self.assertPathDoesNotExist('a')
 
167
        self.assertPathExists('b')
168
168
        self.check_file_contents('b', 'something in a\n')
169
169
 
170
170
        self.create_file('a', 'new something in a\n')
182
182
        # we can't use failUnlessExists on case-insensitive filesystem
183
183
        # so try to check shape of the tree
184
184
        shape = sorted(os.listdir('.'))
185
 
        self.assertEquals(['A', 'B'], shape)
 
185
        self.assertEqual(['A', 'B'], shape)
186
186
 
187
 
    def test_rename_error(self):
188
 
        # We wrap os.rename to make it give an error including the filenames
189
 
        # https://bugs.launchpad.net/bzr/+bug/491763
190
 
        err = self.assertRaises(OSError, osutils.rename,
191
 
            'nonexistent', 'target')
192
 
        self.assertContainsString(str(err), 'nonexistent')
 
187
    def test_rename_exception(self):
 
188
        try:
 
189
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
 
190
        except OSError as e:
 
191
            self.assertEqual(e.old_filename, 'nonexistent_path')
 
192
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
 
193
            self.assertTrue('nonexistent_path' in e.strerror)
 
194
            self.assertTrue('different_nonexistent_path' in e.strerror)
193
195
 
194
196
 
195
197
class TestRandChars(tests.TestCase):
222
224
                         (['src'], SRC_FOO_C),
223
225
                         (['src'], 'src'),
224
226
                         ]:
225
 
            self.assert_(osutils.is_inside_any(dirs, fn))
 
227
            self.assertTrue(osutils.is_inside_any(dirs, fn))
226
228
        for dirs, fn in [(['src'], 'srccontrol'),
227
229
                         (['src'], 'srccontrol/foo')]:
228
230
            self.assertFalse(osutils.is_inside_any(dirs, fn))
234
236
                         (['src/bar.c', 'bla/foo.c'], 'src'),
235
237
                         (['src'], 'src'),
236
238
                         ]:
237
 
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
 
239
            self.assertTrue(osutils.is_inside_or_parent_of_any(dirs, fn))
238
240
 
239
241
        for dirs, fn in [(['src'], 'srccontrol'),
240
242
                         (['srccontrol/foo.c'], 'src'),
242
244
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
243
245
 
244
246
 
 
247
class TestLstat(tests.TestCaseInTempDir):
 
248
 
 
249
    def test_lstat_matches_fstat(self):
 
250
        # On Windows, lstat and fstat don't always agree, primarily in the
 
251
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
 
252
        # custom implementation.
 
253
        if sys.platform == 'win32':
 
254
            # We only have special lstat/fstat if we have the extension.
 
255
            # Without it, we may end up re-reading content when we don't have
 
256
            # to, but otherwise it doesn't effect correctness.
 
257
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
258
        f = open('test-file.txt', 'wb')
 
259
        self.addCleanup(f.close)
 
260
        f.write('some content\n')
 
261
        f.flush()
 
262
        self.assertEqualStat(osutils.fstat(f.fileno()),
 
263
                             osutils.lstat('test-file.txt'))
 
264
 
 
265
 
245
266
class TestRmTree(tests.TestCaseInTempDir):
246
267
 
247
268
    def test_rmtree(self):
259
280
 
260
281
        osutils.rmtree('dir')
261
282
 
262
 
        self.failIfExists('dir/file')
263
 
        self.failIfExists('dir')
 
283
        self.assertPathDoesNotExist('dir/file')
 
284
        self.assertPathDoesNotExist('dir')
264
285
 
265
286
 
266
287
class TestDeleteAny(tests.TestCaseInTempDir):
279
300
 
280
301
    def test_file_kind(self):
281
302
        self.build_tree(['file', 'dir/'])
282
 
        self.assertEquals('file', osutils.file_kind('file'))
283
 
        self.assertEquals('directory', osutils.file_kind('dir/'))
 
303
        self.assertEqual('file', osutils.file_kind('file'))
 
304
        self.assertEqual('directory', osutils.file_kind('dir/'))
284
305
        if osutils.has_symlinks():
285
306
            os.symlink('symlink', 'symlink')
286
 
            self.assertEquals('symlink', osutils.file_kind('symlink'))
 
307
            self.assertEqual('symlink', osutils.file_kind('symlink'))
287
308
 
288
309
        # TODO: jam 20060529 Test a block device
289
310
        try:
290
311
            os.lstat('/dev/null')
291
 
        except OSError, e:
 
312
        except OSError as e:
292
313
            if e.errno not in (errno.ENOENT,):
293
314
                raise
294
315
        else:
295
 
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
 
316
            self.assertEqual('chardev', osutils.file_kind('/dev/null'))
296
317
 
297
318
        mkfifo = getattr(os, 'mkfifo', None)
298
319
        if mkfifo:
299
320
            mkfifo('fifo')
300
321
            try:
301
 
                self.assertEquals('fifo', osutils.file_kind('fifo'))
 
322
                self.assertEqual('fifo', osutils.file_kind('fifo'))
302
323
            finally:
303
324
                os.remove('fifo')
304
325
 
307
328
            s = socket.socket(AF_UNIX)
308
329
            s.bind('socket')
309
330
            try:
310
 
                self.assertEquals('socket', osutils.file_kind('socket'))
 
331
                self.assertEqual('socket', osutils.file_kind('socket'))
311
332
            finally:
312
333
                os.remove('socket')
313
334
 
332
353
 
333
354
        orig_umask = osutils.get_umask()
334
355
        self.addCleanup(os.umask, orig_umask)
335
 
        os.umask(0222)
336
 
        self.assertEqual(0222, osutils.get_umask())
337
 
        os.umask(0022)
338
 
        self.assertEqual(0022, osutils.get_umask())
339
 
        os.umask(0002)
340
 
        self.assertEqual(0002, osutils.get_umask())
341
 
        os.umask(0027)
342
 
        self.assertEqual(0027, osutils.get_umask())
 
356
        os.umask(0o222)
 
357
        self.assertEqual(0o222, osutils.get_umask())
 
358
        os.umask(0o022)
 
359
        self.assertEqual(0o022, osutils.get_umask())
 
360
        os.umask(0o002)
 
361
        self.assertEqual(0o002, osutils.get_umask())
 
362
        os.umask(0o027)
 
363
        self.assertEqual(0o027, osutils.get_umask())
343
364
 
344
365
 
345
366
class TestDateTime(tests.TestCase):
418
439
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
419
440
 
420
441
 
 
442
class TestFdatasync(tests.TestCaseInTempDir):
 
443
 
 
444
    def do_fdatasync(self):
 
445
        f = tempfile.NamedTemporaryFile()
 
446
        osutils.fdatasync(f.fileno())
 
447
        f.close()
 
448
 
 
449
    @staticmethod
 
450
    def raise_eopnotsupp(*args, **kwargs):
 
451
        raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
 
452
 
 
453
    @staticmethod
 
454
    def raise_enotsup(*args, **kwargs):
 
455
        raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
 
456
 
 
457
    def test_fdatasync_handles_system_function(self):
 
458
        self.overrideAttr(os, "fdatasync")
 
459
        self.do_fdatasync()
 
460
 
 
461
    def test_fdatasync_handles_no_fdatasync_no_fsync(self):
 
462
        self.overrideAttr(os, "fdatasync")
 
463
        self.overrideAttr(os, "fsync")
 
464
        self.do_fdatasync()
 
465
 
 
466
    def test_fdatasync_handles_no_EOPNOTSUPP(self):
 
467
        self.overrideAttr(errno, "EOPNOTSUPP")
 
468
        self.do_fdatasync()
 
469
 
 
470
    def test_fdatasync_catches_ENOTSUP(self):
 
471
        enotsup = getattr(errno, "ENOTSUP", None)
 
472
        if enotsup is None:
 
473
            raise tests.TestNotApplicable("No ENOTSUP on this platform")
 
474
        self.overrideAttr(os, "fdatasync", self.raise_enotsup)
 
475
        self.do_fdatasync()
 
476
 
 
477
    def test_fdatasync_catches_EOPNOTSUPP(self):
 
478
        enotsup = getattr(errno, "EOPNOTSUPP", None)
 
479
        if enotsup is None:
 
480
            raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
 
481
        self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
 
482
        self.do_fdatasync()
 
483
 
 
484
 
421
485
class TestLinks(tests.TestCaseInTempDir):
422
486
 
423
487
    def test_dereference_path(self):
424
 
        self.requireFeature(tests.SymlinkFeature)
 
488
        self.requireFeature(features.SymlinkFeature)
425
489
        cwd = osutils.realpath('.')
426
490
        os.mkdir('bar')
427
491
        bar_path = osutils.pathjoin(cwd, 'bar')
455
519
        # Make a file readonly
456
520
        osutils.make_readonly('file')
457
521
        mode = os.lstat('file').st_mode
458
 
        self.assertEqual(mode, mode & 0777555)
 
522
        self.assertEqual(mode, mode & 0o777555)
459
523
 
460
524
        # Make a file writable
461
525
        osutils.make_writable('file')
462
526
        mode = os.lstat('file').st_mode
463
 
        self.assertEqual(mode, mode | 0200)
 
527
        self.assertEqual(mode, mode | 0o200)
464
528
 
465
529
        if osutils.has_symlinks():
466
530
            # should not error when handed a symlink
474
538
 
475
539
class TestCanonicalRelPath(tests.TestCaseInTempDir):
476
540
 
477
 
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
 
541
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
478
542
 
479
543
    def test_canonical_relpath_simple(self):
480
544
        f = file('MixedCaseName', 'w')
481
545
        f.close()
482
546
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
483
 
        self.failUnlessEqual('work/MixedCaseName', actual)
 
547
        self.assertEqual('work/MixedCaseName', actual)
484
548
 
485
549
    def test_canonical_relpath_missing_tail(self):
486
550
        os.mkdir('MixedCaseParent')
487
551
        actual = osutils.canonical_relpath(self.test_base_dir,
488
552
                                           'mixedcaseparent/nochild')
489
 
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
 
553
        self.assertEqual('work/MixedCaseParent/nochild', actual)
490
554
 
491
555
 
492
556
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
536
600
    """Test pumpfile method."""
537
601
 
538
602
    def setUp(self):
539
 
        tests.TestCase.setUp(self)
 
603
        super(TestPumpFile, self).setUp()
540
604
        # create a test datablock
541
605
        self.block_size = 512
542
606
        pattern = '0123456789ABCDEF'
550
614
        self.assertTrue(self.test_data_len > self.block_size)
551
615
 
552
616
        from_file = file_utils.FakeReadFile(self.test_data)
553
 
        to_file = StringIO()
 
617
        to_file = BytesIO()
554
618
 
555
619
        # read (max / 2) bytes and verify read size wasn't affected
556
620
        num_bytes_to_read = self.block_size / 2
591
655
 
592
656
        # retrieve data in blocks
593
657
        from_file = file_utils.FakeReadFile(self.test_data)
594
 
        to_file = StringIO()
 
658
        to_file = BytesIO()
595
659
        osutils.pumpfile(from_file, to_file, self.test_data_len,
596
660
                         self.block_size)
597
661
 
615
679
 
616
680
        # retrieve data to EOF
617
681
        from_file = file_utils.FakeReadFile(self.test_data)
618
 
        to_file = StringIO()
 
682
        to_file = BytesIO()
619
683
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
620
684
 
621
685
        # verify read size was equal to the maximum read size
635
699
        with this new version."""
636
700
        # retrieve data using default (old) pumpfile method
637
701
        from_file = file_utils.FakeReadFile(self.test_data)
638
 
        to_file = StringIO()
 
702
        to_file = BytesIO()
639
703
        osutils.pumpfile(from_file, to_file)
640
704
 
641
705
        # report error if the data wasn't equal (we only report the size due
649
713
        activity = []
650
714
        def log_activity(length, direction):
651
715
            activity.append((length, direction))
652
 
        from_file = StringIO(self.test_data)
653
 
        to_file = StringIO()
 
716
        from_file = BytesIO(self.test_data)
 
717
        to_file = BytesIO()
654
718
        osutils.pumpfile(from_file, to_file, buff_size=500,
655
719
                         report_activity=log_activity, direction='read')
656
720
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
657
721
                          (36, 'read')], activity)
658
722
 
659
 
        from_file = StringIO(self.test_data)
660
 
        to_file = StringIO()
 
723
        from_file = BytesIO(self.test_data)
 
724
        to_file = BytesIO()
661
725
        del activity[:]
662
726
        osutils.pumpfile(from_file, to_file, buff_size=500,
663
727
                         report_activity=log_activity, direction='write')
665
729
                          (36, 'write')], activity)
666
730
 
667
731
        # And with a limited amount of data
668
 
        from_file = StringIO(self.test_data)
669
 
        to_file = StringIO()
 
732
        from_file = BytesIO(self.test_data)
 
733
        to_file = BytesIO()
670
734
        del activity[:]
671
735
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
672
736
                         report_activity=log_activity, direction='read')
677
741
class TestPumpStringFile(tests.TestCase):
678
742
 
679
743
    def test_empty(self):
680
 
        output = StringIO()
 
744
        output = BytesIO()
681
745
        osutils.pump_string_file("", output)
682
746
        self.assertEqual("", output.getvalue())
683
747
 
684
748
    def test_more_than_segment_size(self):
685
 
        output = StringIO()
 
749
        output = BytesIO()
686
750
        osutils.pump_string_file("123456789", output, 2)
687
751
        self.assertEqual("123456789", output.getvalue())
688
752
 
689
753
    def test_segment_size(self):
690
 
        output = StringIO()
 
754
        output = BytesIO()
691
755
        osutils.pump_string_file("12", output, 2)
692
756
        self.assertEqual("12", output.getvalue())
693
757
 
694
758
    def test_segment_size_multiple(self):
695
 
        output = StringIO()
 
759
        output = BytesIO()
696
760
        osutils.pump_string_file("1234", output, 2)
697
761
        self.assertEqual("1234", output.getvalue())
698
762
 
810
874
        self.assertEqual(None, osutils.safe_file_id(None))
811
875
 
812
876
 
 
877
class TestSendAll(tests.TestCase):
 
878
 
 
879
    def test_send_with_disconnected_socket(self):
 
880
        class DisconnectedSocket(object):
 
881
            def __init__(self, err):
 
882
                self.err = err
 
883
            def send(self, content):
 
884
                raise self.err
 
885
            def close(self):
 
886
                pass
 
887
        # All of these should be treated as ConnectionReset
 
888
        errs = []
 
889
        for err_cls in (IOError, socket.error):
 
890
            for errnum in osutils._end_of_stream_errors:
 
891
                errs.append(err_cls(errnum))
 
892
        for err in errs:
 
893
            sock = DisconnectedSocket(err)
 
894
            self.assertRaises(errors.ConnectionReset,
 
895
                osutils.send_all, sock, 'some more content')
 
896
 
 
897
    def test_send_with_no_progress(self):
 
898
        # See https://bugs.launchpad.net/bzr/+bug/1047309
 
899
        # It seems that paramiko can get into a state where it doesn't error,
 
900
        # but it returns 0 bytes sent for requests over and over again.
 
901
        class NoSendingSocket(object):
 
902
            def __init__(self):
 
903
                self.call_count = 0
 
904
            def send(self, bytes):
 
905
                self.call_count += 1
 
906
                if self.call_count > 100:
 
907
                    # Prevent the test suite from hanging
 
908
                    raise RuntimeError('too many calls')
 
909
                return 0
 
910
        sock = NoSendingSocket()
 
911
        self.assertRaises(errors.ConnectionReset,
 
912
                          osutils.send_all, sock, 'content')
 
913
        self.assertEqual(1, sock.call_count)
 
914
 
 
915
 
 
916
class TestPosixFuncs(tests.TestCase):
 
917
    """Test that the posix version of normpath returns an appropriate path
 
918
       when used with 2 leading slashes."""
 
919
 
 
920
    def test_normpath(self):
 
921
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
 
922
        self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
 
923
        self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
 
924
 
 
925
 
813
926
class TestWin32Funcs(tests.TestCase):
814
927
    """Test that _win32 versions of os utilities return appropriate paths."""
815
928
 
816
929
    def test_abspath(self):
 
930
        self.requireFeature(features.win32_feature)
817
931
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
818
932
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
819
933
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
832
946
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
833
947
        self.assertEqual('path/to/foo',
834
948
                         osutils._win32_pathjoin('path/to/', 'foo'))
835
 
        self.assertEqual('/foo',
 
949
 
 
950
    def test_pathjoin_late_bugfix(self):
 
951
        if sys.version_info < (2, 7, 6):
 
952
            expected = '/foo'
 
953
        else:
 
954
            expected = 'C:/foo'
 
955
        self.assertEqual(expected,
836
956
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
837
 
        self.assertEqual('/foo',
 
957
        self.assertEqual(expected,
838
958
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
839
959
 
840
960
    def test_normpath(self):
845
965
 
846
966
    def test_getcwd(self):
847
967
        cwd = osutils._win32_getcwd()
848
 
        os_cwd = os.getcwdu()
 
968
        os_cwd = osutils._getcwd()
849
969
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
850
970
        # win32 is inconsistent whether it returns lower or upper case
851
971
        # and even if it was consistent the user might type the other
860
980
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
861
981
 
862
982
    def test_win98_abspath(self):
 
983
        self.requireFeature(features.win32_feature)
863
984
        # absolute path
864
985
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
865
986
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
868
989
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
869
990
        # relative path
870
991
        cwd = osutils.getcwd().rstrip('/')
871
 
        drive = osutils._nt_splitdrive(cwd)[0]
 
992
        drive = osutils.ntpath.splitdrive(cwd)[0]
872
993
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
873
994
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
874
995
        # unicode path
880
1001
    """Test win32 functions that create files."""
881
1002
 
882
1003
    def test_getcwd(self):
883
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1004
        self.requireFeature(features.UnicodeFilenameFeature)
884
1005
        os.mkdir(u'mu-\xb5')
885
1006
        os.chdir(u'mu-\xb5')
886
1007
        # TODO: jam 20060427 This will probably fail on Mac OSX because
892
1013
    def test_minimum_path_selection(self):
893
1014
        self.assertEqual(set(),
894
1015
            osutils.minimum_path_selection([]))
895
 
        self.assertEqual(set(['a']),
 
1016
        self.assertEqual({'a'},
896
1017
            osutils.minimum_path_selection(['a']))
897
 
        self.assertEqual(set(['a', 'b']),
 
1018
        self.assertEqual({'a', 'b'},
898
1019
            osutils.minimum_path_selection(['a', 'b']))
899
 
        self.assertEqual(set(['a/', 'b']),
 
1020
        self.assertEqual({'a/', 'b'},
900
1021
            osutils.minimum_path_selection(['a/', 'b']))
901
 
        self.assertEqual(set(['a/', 'b']),
 
1022
        self.assertEqual({'a/', 'b'},
902
1023
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
903
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
 
1024
        self.assertEqual({'a-b', 'a', 'a0b'},
904
1025
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
905
1026
 
906
1027
    def test_mkdtemp(self):
916
1037
        b.close()
917
1038
 
918
1039
        osutils._win32_rename('b', 'a')
919
 
        self.failUnlessExists('a')
920
 
        self.failIfExists('b')
 
1040
        self.assertPathExists('a')
 
1041
        self.assertPathDoesNotExist('b')
921
1042
        self.assertFileEqual('baz\n', 'a')
922
1043
 
923
1044
    def test_rename_missing_file(self):
927
1048
 
928
1049
        try:
929
1050
            osutils._win32_rename('b', 'a')
930
 
        except (IOError, OSError), e:
 
1051
        except (IOError, OSError) as e:
931
1052
            self.assertEqual(errno.ENOENT, e.errno)
932
1053
        self.assertFileEqual('foo\n', 'a')
933
1054
 
935
1056
        os.mkdir('a')
936
1057
        try:
937
1058
            osutils._win32_rename('b', 'a')
938
 
        except (IOError, OSError), e:
 
1059
        except (IOError, OSError) as e:
939
1060
            self.assertEqual(errno.ENOENT, e.errno)
940
1061
 
941
1062
    def test_rename_current_dir(self):
947
1068
        # doesn't exist.
948
1069
        try:
949
1070
            osutils._win32_rename('b', '.')
950
 
        except (IOError, OSError), e:
 
1071
        except (IOError, OSError) as e:
951
1072
            self.assertEqual(errno.ENOENT, e.errno)
952
1073
 
953
1074
    def test_splitpath(self):
976
1097
    """Test mac special functions that require directories."""
977
1098
 
978
1099
    def test_getcwd(self):
979
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1100
        self.requireFeature(features.UnicodeFilenameFeature)
980
1101
        os.mkdir(u'B\xe5gfors')
981
1102
        os.chdir(u'B\xe5gfors')
982
1103
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
983
1104
 
984
1105
    def test_getcwd_nonnorm(self):
985
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1106
        self.requireFeature(features.UnicodeFilenameFeature)
986
1107
        # Test that _mac_getcwd() will normalize this path
987
1108
        os.mkdir(u'Ba\u030agfors')
988
1109
        os.chdir(u'Ba\u030agfors')
998
1119
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
999
1120
 
1000
1121
    def test_osutils_binding(self):
1001
 
        from bzrlib.tests import test__chunks_to_lines
 
1122
        from . import test__chunks_to_lines
1002
1123
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
1003
 
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
1124
            from .._chunks_to_lines_pyx import chunks_to_lines
1004
1125
        else:
1005
 
            from bzrlib._chunks_to_lines_py import chunks_to_lines
 
1126
            from .._chunks_to_lines_py import chunks_to_lines
1006
1127
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
1007
1128
 
1008
1129
 
1071
1192
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1072
1193
 
1073
1194
    def test_walkdirs_os_error(self):
1074
 
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
 
1195
        # <https://bugs.launchpad.net/bzr/+bug/338653>
1075
1196
        # Pyrex readdir didn't raise useful messages if it had an error
1076
1197
        # reading the directory
1077
1198
        if sys.platform == 'win32':
1078
1199
            raise tests.TestNotApplicable(
1079
1200
                "readdir IOError not tested on win32")
 
1201
        self.requireFeature(features.not_running_as_root)
1080
1202
        os.mkdir("test-unreadable")
1081
1203
        os.chmod("test-unreadable", 0000)
1082
1204
        # must chmod it back so that it can be removed
1083
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
 
1205
        self.addCleanup(os.chmod, "test-unreadable", 0o700)
1084
1206
        # The error is not raised until the generator is actually evaluated.
1085
1207
        # (It would be ok if it happened earlier but at the moment it
1086
1208
        # doesn't.)
1087
1209
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1088
 
        self.assertEquals('./test-unreadable', e.filename)
1089
 
        self.assertEquals(errno.EACCES, e.errno)
 
1210
        self.assertEqual('./test-unreadable', e.filename)
 
1211
        self.assertEqual(errno.EACCES, e.errno)
1090
1212
        # Ensure the message contains the file name
1091
1213
        self.assertContainsRe(str(e), "\./test-unreadable")
1092
1214
 
 
1215
 
 
1216
    def test_walkdirs_encoding_error(self):
 
1217
        # <https://bugs.launchpad.net/bzr/+bug/488519>
 
1218
        # walkdirs didn't raise a useful message when the filenames
 
1219
        # are not using the filesystem's encoding
 
1220
 
 
1221
        # require a bytestring based filesystem
 
1222
        self.requireFeature(features.ByteStringNamedFilesystem)
 
1223
 
 
1224
        tree = [
 
1225
            '.bzr',
 
1226
            '0file',
 
1227
            '1dir/',
 
1228
            '1dir/0file',
 
1229
            '1dir/1dir/',
 
1230
            '1file'
 
1231
            ]
 
1232
 
 
1233
        self.build_tree(tree)
 
1234
 
 
1235
        # rename the 1file to a latin-1 filename
 
1236
        os.rename("./1file", "\xe8file")
 
1237
        if "\xe8file" not in os.listdir("."):
 
1238
            self.skipTest("Lack filesystem that preserves arbitrary bytes")
 
1239
 
 
1240
        self._save_platform_info()
 
1241
        win32utils.winver = None # Avoid the win32 detection code
 
1242
        osutils._fs_enc = 'UTF-8'
 
1243
 
 
1244
        # this should raise on error
 
1245
        def attempt():
 
1246
            for dirdetail, dirblock in osutils.walkdirs('.'):
 
1247
                pass
 
1248
 
 
1249
        self.assertRaises(errors.BadFilenameEncoding, attempt)
 
1250
 
1093
1251
    def test__walkdirs_utf8(self):
1094
1252
        tree = [
1095
1253
            '.bzr',
1161
1319
        self.requireFeature(UTF8DirReaderFeature)
1162
1320
        self._save_platform_info()
1163
1321
        win32utils.winver = None # Avoid the win32 detection code
1164
 
        osutils._fs_enc = 'UTF-8'
1165
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1322
        osutils._fs_enc = 'utf-8'
 
1323
        self.assertDirReaderIs(
 
1324
            UTF8DirReaderFeature.module.UTF8DirReader)
1166
1325
 
1167
1326
    def test_force_walkdirs_utf8_fs_ascii(self):
1168
1327
        self.requireFeature(UTF8DirReaderFeature)
1169
1328
        self._save_platform_info()
1170
1329
        win32utils.winver = None # Avoid the win32 detection code
1171
 
        osutils._fs_enc = 'US-ASCII'
1172
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1173
 
 
1174
 
    def test_force_walkdirs_utf8_fs_ANSI(self):
1175
 
        self.requireFeature(UTF8DirReaderFeature)
1176
 
        self._save_platform_info()
1177
 
        win32utils.winver = None # Avoid the win32 detection code
1178
 
        osutils._fs_enc = 'ANSI_X3.4-1968'
1179
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1330
        osutils._fs_enc = 'ascii'
 
1331
        self.assertDirReaderIs(
 
1332
            UTF8DirReaderFeature.module.UTF8DirReader)
1180
1333
 
1181
1334
    def test_force_walkdirs_utf8_fs_latin1(self):
1182
1335
        self._save_platform_info()
1183
1336
        win32utils.winver = None # Avoid the win32 detection code
1184
 
        osutils._fs_enc = 'latin1'
 
1337
        osutils._fs_enc = 'iso-8859-1'
1185
1338
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1186
1339
 
1187
1340
    def test_force_walkdirs_utf8_nt(self):
1189
1342
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1190
1343
        self._save_platform_info()
1191
1344
        win32utils.winver = 'Windows NT'
1192
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1345
        from .._walkdirs_win32 import Win32ReadDir
1193
1346
        self.assertDirReaderIs(Win32ReadDir)
1194
1347
 
1195
1348
    def test_force_walkdirs_utf8_98(self):
1200
1353
 
1201
1354
    def test_unicode_walkdirs(self):
1202
1355
        """Walkdirs should always return unicode paths."""
1203
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1356
        self.requireFeature(features.UnicodeFilenameFeature)
1204
1357
        name0 = u'0file-\xb6'
1205
1358
        name1 = u'1dir-\u062c\u0648'
1206
1359
        name2 = u'2file-\u0633'
1243
1396
 
1244
1397
        The abspath portion might be in unicode or utf-8
1245
1398
        """
1246
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1399
        self.requireFeature(features.UnicodeFilenameFeature)
1247
1400
        name0 = u'0file-\xb6'
1248
1401
        name1 = u'1dir-\u062c\u0648'
1249
1402
        name2 = u'2file-\u0633'
1304
1457
 
1305
1458
        The abspath portion should be in unicode
1306
1459
        """
1307
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1460
        self.requireFeature(features.UnicodeFilenameFeature)
1308
1461
        # Use the unicode reader. TODO: split into driver-and-driven unit
1309
1462
        # tests.
1310
1463
        self._save_platform_info()
1351
1504
 
1352
1505
    def test__walkdirs_utf8_win32readdir(self):
1353
1506
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1354
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1355
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1507
        self.requireFeature(features.UnicodeFilenameFeature)
 
1508
        from .._walkdirs_win32 import Win32ReadDir
1356
1509
        self._save_platform_info()
1357
1510
        osutils._selected_dir_reader = Win32ReadDir()
1358
1511
        name0u = u'0file-\xb6'
1408
1561
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1409
1562
        """make sure our Stat values are valid"""
1410
1563
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1411
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1412
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1564
        self.requireFeature(features.UnicodeFilenameFeature)
 
1565
        from .._walkdirs_win32 import Win32ReadDir
1413
1566
        name0u = u'0file-\xb6'
1414
1567
        name0 = name0u.encode('utf8')
1415
1568
        self.build_tree([name0u])
1432
1585
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1433
1586
        """make sure our Stat values are valid"""
1434
1587
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1435
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1436
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1588
        self.requireFeature(features.UnicodeFilenameFeature)
 
1589
        from .._walkdirs_win32 import Win32ReadDir
1437
1590
        name0u = u'0dir-\u062c\u0648'
1438
1591
        name0 = name0u.encode('utf8')
1439
1592
        self.build_tree([name0u + '/'])
1538
1691
        self.assertEqual(['c'], os.listdir('target/b'))
1539
1692
 
1540
1693
    def test_copy_tree_symlinks(self):
1541
 
        self.requireFeature(tests.SymlinkFeature)
 
1694
        self.requireFeature(features.SymlinkFeature)
1542
1695
        self.build_tree(['source/'])
1543
1696
        os.symlink('a/generic/path', 'source/lnk')
1544
1697
        osutils.copy_tree('source', 'target')
1569
1722
                          ('d', 'source/b', 'target/b'),
1570
1723
                          ('f', 'source/b/c', 'target/b/c'),
1571
1724
                         ], processed_files)
1572
 
        self.failIfExists('target')
 
1725
        self.assertPathDoesNotExist('target')
1573
1726
        if osutils.has_symlinks():
1574
1727
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1575
1728
 
1580
1733
    def setUp(self):
1581
1734
        super(TestSetUnsetEnv, self).setUp()
1582
1735
 
1583
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
 
1736
        self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'),
1584
1737
                         'Environment was not cleaned up properly.'
1585
 
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
 
1738
                         ' Variable BRZ_TEST_ENV_VAR should not exist.')
1586
1739
        def cleanup():
1587
 
            if 'BZR_TEST_ENV_VAR' in os.environ:
1588
 
                del os.environ['BZR_TEST_ENV_VAR']
 
1740
            if 'BRZ_TEST_ENV_VAR' in os.environ:
 
1741
                del os.environ['BRZ_TEST_ENV_VAR']
1589
1742
        self.addCleanup(cleanup)
1590
1743
 
1591
1744
    def test_set(self):
1592
1745
        """Test that we can set an env variable"""
1593
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1746
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1594
1747
        self.assertEqual(None, old)
1595
 
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
 
1748
        self.assertEqual('foo', os.environ.get('BRZ_TEST_ENV_VAR'))
1596
1749
 
1597
1750
    def test_double_set(self):
1598
1751
        """Test that we get the old value out"""
1599
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1600
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
 
1752
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
 
1753
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'bar')
1601
1754
        self.assertEqual('foo', old)
1602
 
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
 
1755
        self.assertEqual('bar', os.environ.get('BRZ_TEST_ENV_VAR'))
1603
1756
 
1604
1757
    def test_unicode(self):
1605
1758
        """Environment can only contain plain strings
1612
1765
                'Cannot find a unicode character that works in encoding %s'
1613
1766
                % (osutils.get_user_encoding(),))
1614
1767
 
1615
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1616
 
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
 
1768
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', uni_val)
 
1769
        self.assertEqual(env_val, os.environ.get('BRZ_TEST_ENV_VAR'))
1617
1770
 
1618
1771
    def test_unset(self):
1619
1772
        """Test that passing None will remove the env var"""
1620
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1621
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
 
1773
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
 
1774
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', None)
1622
1775
        self.assertEqual('foo', old)
1623
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1624
 
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1776
        self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'))
 
1777
        self.assertFalse('BRZ_TEST_ENV_VAR' in os.environ)
1625
1778
 
1626
1779
 
1627
1780
class TestSizeShaFile(tests.TestCaseInTempDir):
1663
1816
class TestResourceLoading(tests.TestCaseInTempDir):
1664
1817
 
1665
1818
    def test_resource_string(self):
1666
 
        # test resource in bzrlib
1667
 
        text = osutils.resource_string('bzrlib', 'debug.py')
 
1819
        # test resource in breezy
 
1820
        text = osutils.resource_string('breezy', 'debug.py')
1668
1821
        self.assertContainsRe(text, "debug_flags = set()")
1669
 
        # test resource under bzrlib
1670
 
        text = osutils.resource_string('bzrlib.ui', 'text.py')
 
1822
        # test resource under breezy
 
1823
        text = osutils.resource_string('breezy.ui', 'text.py')
1671
1824
        self.assertContainsRe(text, "class TextUIFactory")
1672
1825
        # test unsupported package
1673
1826
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1674
1827
            'yyy.xx')
1675
1828
        # test unknown resource
1676
 
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
 
1829
        self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
1677
1830
 
1678
1831
 
1679
1832
class TestReCompile(tests.TestCase):
1680
1833
 
 
1834
    def _deprecated_re_compile_checked(self, *args, **kwargs):
 
1835
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
 
1836
            osutils.re_compile_checked, *args, **kwargs)
 
1837
 
1681
1838
    def test_re_compile_checked(self):
1682
 
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
 
1839
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1683
1840
        self.assertTrue(r.match('aaaa'))
1684
1841
        self.assertTrue(r.match('aAaA'))
1685
1842
 
1686
1843
    def test_re_compile_checked_error(self):
1687
1844
        # like https://bugs.launchpad.net/bzr/+bug/251352
 
1845
 
 
1846
        # Due to possible test isolation error, re.compile is not lazy at
 
1847
        # this point. We re-install lazy compile.
 
1848
        lazy_regex.install_lazy_compile()
1688
1849
        err = self.assertRaises(
1689
1850
            errors.BzrCommandError,
1690
 
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1851
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1691
1852
        self.assertEqual(
1692
 
            "Invalid regular expression in test case: '*': "
1693
 
            "nothing to repeat",
 
1853
            'Invalid regular expression in test case: '
 
1854
            '"*" nothing to repeat',
1694
1855
            str(err))
1695
1856
 
1696
1857
 
1697
1858
class TestDirReader(tests.TestCaseInTempDir):
1698
1859
 
 
1860
    scenarios = dir_reader_scenarios()
 
1861
 
1699
1862
    # Set by load_tests
1700
1863
    _dir_reader_class = None
1701
1864
    _native_to_unicode = None
1702
1865
 
1703
1866
    def setUp(self):
1704
 
        tests.TestCaseInTempDir.setUp(self)
 
1867
        super(TestDirReader, self).setUp()
1705
1868
        self.overrideAttr(osutils,
1706
1869
                          '_selected_dir_reader', self._dir_reader_class())
1707
1870
 
1801
1964
        return filtered_dirblocks
1802
1965
 
1803
1966
    def test_walk_unicode_tree(self):
1804
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1967
        self.requireFeature(features.UnicodeFilenameFeature)
1805
1968
        tree, expected_dirblocks = self._get_unicode_tree()
1806
1969
        self.build_tree(tree)
1807
1970
        result = list(osutils._walkdirs_utf8('.'))
1808
1971
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1809
1972
 
1810
1973
    def test_symlink(self):
1811
 
        self.requireFeature(tests.SymlinkFeature)
1812
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1974
        self.requireFeature(features.SymlinkFeature)
 
1975
        self.requireFeature(features.UnicodeFilenameFeature)
1813
1976
        target = u'target\N{Euro Sign}'
1814
1977
        link_name = u'l\N{Euro Sign}nk'
1815
1978
        os.symlink(target, link_name)
1833
1996
    But prior python versions failed to properly encode the passed unicode
1834
1997
    string.
1835
1998
    """
1836
 
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
 
1999
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1837
2000
 
1838
2001
    def setUp(self):
1839
2002
        super(tests.TestCaseInTempDir, self).setUp()
1842
2005
        os.symlink(self.target, self.link)
1843
2006
 
1844
2007
    def test_os_readlink_link_encoding(self):
1845
 
        if sys.version_info < (2, 6):
1846
 
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
1847
 
        else:
1848
 
            self.assertEquals(self.target,  os.readlink(self.link))
 
2008
        self.assertEqual(self.target,  os.readlink(self.link))
1849
2009
 
1850
2010
    def test_os_readlink_link_decoding(self):
1851
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
 
2011
        self.assertEqual(self.target.encode(osutils._fs_enc),
1852
2012
                          os.readlink(self.link.encode(osutils._fs_enc)))
1853
2013
 
1854
2014
 
1863
2023
        self.assertIsInstance(concurrency, int)
1864
2024
 
1865
2025
    def test_local_concurrency_environment_variable(self):
1866
 
        os.environ['BZR_CONCURRENCY'] = '2'
 
2026
        self.overrideEnv('BRZ_CONCURRENCY', '2')
1867
2027
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1868
 
        os.environ['BZR_CONCURRENCY'] = '3'
 
2028
        self.overrideEnv('BRZ_CONCURRENCY', '3')
1869
2029
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1870
 
        os.environ['BZR_CONCURRENCY'] = 'foo'
 
2030
        self.overrideEnv('BRZ_CONCURRENCY', 'foo')
1871
2031
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1872
2032
 
1873
2033
    def test_option_concurrency(self):
1874
 
        os.environ['BZR_CONCURRENCY'] = '1'
 
2034
        self.overrideEnv('BRZ_CONCURRENCY', '1')
1875
2035
        self.run_bzr('rocks --concurrency 42')
1876
 
        # Command line overrides envrionment variable
1877
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1878
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
 
2036
        # Command line overrides environment variable
 
2037
        self.assertEqual('42', os.environ['BRZ_CONCURRENCY'])
 
2038
        self.assertEqual(42, osutils.local_concurrency(use_cache=False))
1879
2039
 
1880
2040
 
1881
2041
class TestFailedToLoadExtension(tests.TestCase):
1882
2042
 
1883
2043
    def _try_loading(self):
1884
2044
        try:
1885
 
            import bzrlib._fictional_extension_py
1886
 
        except ImportError, e:
 
2045
            import breezy._fictional_extension_py
 
2046
        except ImportError as e:
1887
2047
            osutils.failed_to_load_extension(e)
1888
2048
            return True
1889
2049
 
1894
2054
    def test_failure_to_load(self):
1895
2055
        self._try_loading()
1896
2056
        self.assertLength(1, osutils._extension_load_failures)
1897
 
        self.assertEquals(osutils._extension_load_failures[0],
 
2057
        self.assertEqual(osutils._extension_load_failures[0],
1898
2058
            "No module named _fictional_extension_py")
1899
2059
 
1900
2060
    def test_report_extension_load_failures_no_warning(self):
1904
2064
        self.assertLength(0, warnings)
1905
2065
 
1906
2066
    def test_report_extension_load_failures_message(self):
1907
 
        log = StringIO()
 
2067
        log = BytesIO()
1908
2068
        trace.push_log_file(log)
1909
2069
        self.assertTrue(self._try_loading())
1910
2070
        osutils.report_extension_load_failures()
1911
2071
        self.assertContainsRe(
1912
2072
            log.getvalue(),
1913
 
            r"bzr: warning: some compiled extensions could not be loaded; "
 
2073
            r"brz: warning: some compiled extensions could not be loaded; "
1914
2074
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1915
2075
            )
1916
2076
 
1917
2077
 
1918
2078
class TestTerminalWidth(tests.TestCase):
1919
2079
 
 
2080
    def setUp(self):
 
2081
        super(TestTerminalWidth, self).setUp()
 
2082
        self._orig_terminal_size_state = osutils._terminal_size_state
 
2083
        self._orig_first_terminal_size = osutils._first_terminal_size
 
2084
        self.addCleanup(self.restore_osutils_globals)
 
2085
        osutils._terminal_size_state = 'no_data'
 
2086
        osutils._first_terminal_size = None
 
2087
 
 
2088
    def restore_osutils_globals(self):
 
2089
        osutils._terminal_size_state = self._orig_terminal_size_state
 
2090
        osutils._first_terminal_size = self._orig_first_terminal_size
 
2091
 
1920
2092
    def replace_stdout(self, new):
1921
2093
        self.overrideAttr(sys, 'stdout', new)
1922
2094
 
1934
2106
    def test_default_values(self):
1935
2107
        self.assertEqual(80, osutils.default_terminal_width)
1936
2108
 
1937
 
    def test_defaults_to_BZR_COLUMNS(self):
1938
 
        # BZR_COLUMNS is set by the test framework
1939
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
1940
 
        os.environ['BZR_COLUMNS'] = '12'
 
2109
    def test_defaults_to_BRZ_COLUMNS(self):
 
2110
        # BRZ_COLUMNS is set by the test framework
 
2111
        self.assertNotEqual('12', os.environ['BRZ_COLUMNS'])
 
2112
        self.overrideEnv('BRZ_COLUMNS', '12')
1941
2113
        self.assertEqual(12, osutils.terminal_width())
1942
2114
 
 
2115
    def test_BRZ_COLUMNS_0_no_limit(self):
 
2116
        self.overrideEnv('BRZ_COLUMNS', '0')
 
2117
        self.assertEqual(None, osutils.terminal_width())
 
2118
 
1943
2119
    def test_falls_back_to_COLUMNS(self):
1944
 
        del os.environ['BZR_COLUMNS']
 
2120
        self.overrideEnv('BRZ_COLUMNS', None)
1945
2121
        self.assertNotEqual('42', os.environ['COLUMNS'])
1946
2122
        self.set_fake_tty()
1947
 
        os.environ['COLUMNS'] = '42'
 
2123
        self.overrideEnv('COLUMNS', '42')
1948
2124
        self.assertEqual(42, osutils.terminal_width())
1949
2125
 
1950
2126
    def test_tty_default_without_columns(self):
1951
 
        del os.environ['BZR_COLUMNS']
1952
 
        del os.environ['COLUMNS']
 
2127
        self.overrideEnv('BRZ_COLUMNS', None)
 
2128
        self.overrideEnv('COLUMNS', None)
1953
2129
 
1954
2130
        def terminal_size(w, h):
1955
2131
            return 42, 42
1962
2138
        self.assertEqual(42, osutils.terminal_width())
1963
2139
 
1964
2140
    def test_non_tty_default_without_columns(self):
1965
 
        del os.environ['BZR_COLUMNS']
1966
 
        del os.environ['COLUMNS']
 
2141
        self.overrideEnv('BRZ_COLUMNS', None)
 
2142
        self.overrideEnv('COLUMNS', None)
1967
2143
        self.replace_stdout(None)
1968
2144
        self.assertEqual(None, osutils.terminal_width())
1969
2145
 
1979
2155
        else:
1980
2156
            self.overrideAttr(termios, 'TIOCGWINSZ')
1981
2157
            del termios.TIOCGWINSZ
1982
 
        del os.environ['BZR_COLUMNS']
1983
 
        del os.environ['COLUMNS']
 
2158
        self.overrideEnv('BRZ_COLUMNS', None)
 
2159
        self.overrideEnv('COLUMNS', None)
1984
2160
        # Whatever the result is, if we don't raise an exception, it's ok.
1985
2161
        osutils.terminal_width()
1986
2162
 
 
2163
 
1987
2164
class TestCreationOps(tests.TestCaseInTempDir):
1988
2165
    _test_needs_features = [features.chown_feature]
1989
2166
 
1990
2167
    def setUp(self):
1991
 
        tests.TestCaseInTempDir.setUp(self)
 
2168
        super(TestCreationOps, self).setUp()
1992
2169
        self.overrideAttr(os, 'chown', self._dummy_chown)
1993
2170
 
1994
2171
        # params set by call to _dummy_chown
2004
2181
        osutils.copy_ownership_from_path('test_file', ownsrc)
2005
2182
 
2006
2183
        s = os.stat(ownsrc)
2007
 
        self.assertEquals(self.path, 'test_file')
2008
 
        self.assertEquals(self.uid, s.st_uid)
2009
 
        self.assertEquals(self.gid, s.st_gid)
 
2184
        self.assertEqual(self.path, 'test_file')
 
2185
        self.assertEqual(self.uid, s.st_uid)
 
2186
        self.assertEqual(self.gid, s.st_gid)
2010
2187
 
2011
2188
    def test_copy_ownership_nonesrc(self):
2012
2189
        """copy_ownership_from_path test with src=None."""
2015
2192
        osutils.copy_ownership_from_path('test_file')
2016
2193
 
2017
2194
        s = os.stat('..')
2018
 
        self.assertEquals(self.path, 'test_file')
2019
 
        self.assertEquals(self.uid, s.st_uid)
2020
 
        self.assertEquals(self.gid, s.st_gid)
 
2195
        self.assertEqual(self.path, 'test_file')
 
2196
        self.assertEqual(self.uid, s.st_uid)
 
2197
        self.assertEqual(self.gid, s.st_gid)
 
2198
 
 
2199
 
 
2200
class TestPathFromEnviron(tests.TestCase):
 
2201
 
 
2202
    def test_is_unicode(self):
 
2203
        self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
 
2204
        path = osutils.path_from_environ('BRZ_TEST_PATH')
 
2205
        self.assertIsInstance(path, unicode)
 
2206
        self.assertEqual(u'./anywhere at all/', path)
 
2207
 
 
2208
    def test_posix_path_env_ascii(self):
 
2209
        self.overrideEnv('BRZ_TEST_PATH', '/tmp')
 
2210
        home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
 
2211
        self.assertIsInstance(home, unicode)
 
2212
        self.assertEqual(u'/tmp', home)
 
2213
 
 
2214
    def test_posix_path_env_unicode(self):
 
2215
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2216
        self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
 
2217
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2218
        self.assertEqual(u'/home/\xa7test',
 
2219
            osutils._posix_path_from_environ('BRZ_TEST_PATH'))
 
2220
        osutils._fs_enc = "iso8859-5"
 
2221
        self.assertEqual(u'/home/\u0407test',
 
2222
            osutils._posix_path_from_environ('BRZ_TEST_PATH'))
 
2223
        osutils._fs_enc = "utf-8"
 
2224
        self.assertRaises(errors.BadFilenameEncoding,
 
2225
            osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
 
2226
 
 
2227
 
 
2228
class TestGetHomeDir(tests.TestCase):
 
2229
 
 
2230
    def test_is_unicode(self):
 
2231
        home = osutils._get_home_dir()
 
2232
        self.assertIsInstance(home, unicode)
 
2233
 
 
2234
    def test_posix_homeless(self):
 
2235
        self.overrideEnv('HOME', None)
 
2236
        home = osutils._get_home_dir()
 
2237
        self.assertIsInstance(home, unicode)
 
2238
 
 
2239
    def test_posix_home_ascii(self):
 
2240
        self.overrideEnv('HOME', '/home/test')
 
2241
        home = osutils._posix_get_home_dir()
 
2242
        self.assertIsInstance(home, unicode)
 
2243
        self.assertEqual(u'/home/test', home)
 
2244
 
 
2245
    def test_posix_home_unicode(self):
 
2246
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2247
        self.overrideEnv('HOME', '/home/\xa7test')
 
2248
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2249
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
 
2250
        osutils._fs_enc = "iso8859-5"
 
2251
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
 
2252
        osutils._fs_enc = "utf-8"
 
2253
        self.assertRaises(errors.BadFilenameEncoding,
 
2254
            osutils._posix_get_home_dir)
 
2255
 
 
2256
 
 
2257
class TestGetuserUnicode(tests.TestCase):
 
2258
 
 
2259
    def test_is_unicode(self):
 
2260
        user = osutils.getuser_unicode()
 
2261
        self.assertIsInstance(user, unicode)
 
2262
 
 
2263
    def envvar_to_override(self):
 
2264
        if sys.platform == "win32":
 
2265
            # Disable use of platform calls on windows so envvar is used
 
2266
            self.overrideAttr(win32utils, 'has_ctypes', False)
 
2267
            return 'USERNAME' # only variable used on windows
 
2268
        return 'LOGNAME' # first variable checked by getpass.getuser()
 
2269
 
 
2270
    def test_ascii_user(self):
 
2271
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
 
2272
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
 
2273
 
 
2274
    def test_unicode_user(self):
 
2275
        ue = osutils.get_user_encoding()
 
2276
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
2277
        if uni_val is None:
 
2278
            raise tests.TestSkipped(
 
2279
                'Cannot find a unicode character that works in encoding %s'
 
2280
                % (osutils.get_user_encoding(),))
 
2281
        uni_username = u'jrandom' + uni_val
 
2282
        encoded_username = uni_username.encode(ue)
 
2283
        self.overrideEnv(self.envvar_to_override(), encoded_username)
 
2284
        self.assertEqual(uni_username, osutils.getuser_unicode())
 
2285
 
 
2286
 
 
2287
class TestBackupNames(tests.TestCase):
 
2288
 
 
2289
    def setUp(self):
 
2290
        super(TestBackupNames, self).setUp()
 
2291
        self.backups = []
 
2292
 
 
2293
    def backup_exists(self, name):
 
2294
        return name in self.backups
 
2295
 
 
2296
    def available_backup_name(self, name):
 
2297
        backup_name = osutils.available_backup_name(name, self.backup_exists)
 
2298
        self.backups.append(backup_name)
 
2299
        return backup_name
 
2300
 
 
2301
    def assertBackupName(self, expected, name):
 
2302
        self.assertEqual(expected, self.available_backup_name(name))
 
2303
 
 
2304
    def test_empty(self):
 
2305
        self.assertBackupName('file.~1~', 'file')
 
2306
 
 
2307
    def test_existing(self):
 
2308
        self.available_backup_name('file')
 
2309
        self.available_backup_name('file')
 
2310
        self.assertBackupName('file.~3~', 'file')
 
2311
        # Empty slots are found, this is not a strict requirement and may be
 
2312
        # revisited if we test against all implementations.
 
2313
        self.backups.remove('file.~2~')
 
2314
        self.assertBackupName('file.~2~', 'file')
 
2315
 
 
2316
 
 
2317
class TestFindExecutableInPath(tests.TestCase):
 
2318
 
 
2319
    def test_windows(self):
 
2320
        if sys.platform != 'win32':
 
2321
            raise tests.TestSkipped('test requires win32')
 
2322
        self.assertTrue(osutils.find_executable_on_path('explorer') 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('EXPLORER.EXE') is not None)
 
2327
        self.assertTrue(
 
2328
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
 
2329
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
 
2330
        
 
2331
    def test_windows_app_path(self):
 
2332
        if sys.platform != 'win32':
 
2333
            raise tests.TestSkipped('test requires win32')
 
2334
        # Override PATH env var so that exe can only be found on App Path
 
2335
        self.overrideEnv('PATH', '')
 
2336
        # Internt Explorer is always registered in the App Path
 
2337
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
 
2338
 
 
2339
    def test_other(self):
 
2340
        if sys.platform == 'win32':
 
2341
            raise tests.TestSkipped('test requires non-win32')
 
2342
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
 
2343
        self.assertTrue(
 
2344
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
 
2345
 
 
2346
 
 
2347
class TestEnvironmentErrors(tests.TestCase):
 
2348
    """Test handling of environmental errors"""
 
2349
 
 
2350
    def test_is_oserror(self):
 
2351
        self.assertTrue(osutils.is_environment_error(
 
2352
            OSError(errno.EINVAL, "Invalid parameter")))
 
2353
 
 
2354
    def test_is_ioerror(self):
 
2355
        self.assertTrue(osutils.is_environment_error(
 
2356
            IOError(errno.EINVAL, "Invalid parameter")))
 
2357
 
 
2358
    def test_is_socket_error(self):
 
2359
        self.assertTrue(osutils.is_environment_error(
 
2360
            socket.error(errno.EINVAL, "Invalid parameter")))
 
2361
 
 
2362
    def test_is_select_error(self):
 
2363
        self.assertTrue(osutils.is_environment_error(
 
2364
            select.error(errno.EINVAL, "Invalid parameter")))
 
2365
 
 
2366
    def test_is_pywintypes_error(self):
 
2367
        self.requireFeature(features.pywintypes)
 
2368
        import pywintypes
 
2369
        self.assertTrue(osutils.is_environment_error(
 
2370
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))