/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 bzrlib/tests/test_osutils.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2016 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
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
19
 
from __future__ import absolute_import, division
20
 
 
 
19
from cStringIO import StringIO
21
20
import errno
22
21
import os
23
22
import re
27
26
import tempfile
28
27
import time
29
28
 
30
 
from .. import (
 
29
from bzrlib import (
31
30
    errors,
32
31
    lazy_regex,
33
32
    osutils,
36
35
    trace,
37
36
    win32utils,
38
37
    )
39
 
from ..sixish import (
40
 
    BytesIO,
41
 
    )
42
 
from . import (
 
38
from bzrlib.tests import (
43
39
    features,
44
40
    file_utils,
45
41
    test__walkdirs_win32,
46
42
    )
47
 
from .scenarios import load_tests_apply_scenarios
48
 
 
49
 
 
50
 
class _UTF8DirReaderFeature(features.ModuleAvailableFeature):
 
43
from bzrlib.tests.scenarios import load_tests_apply_scenarios
 
44
 
 
45
 
 
46
class _UTF8DirReaderFeature(features.Feature):
51
47
 
52
48
    def _probe(self):
53
49
        try:
54
 
            from .. import _readdir_pyx
55
 
            self._module = _readdir_pyx
 
50
            from bzrlib import _readdir_pyx
56
51
            self.reader = _readdir_pyx.UTF8DirReader
57
52
            return True
58
53
        except ImportError:
59
54
            return False
60
55
 
61
 
UTF8DirReaderFeature = _UTF8DirReaderFeature('breezy._readdir_pyx')
 
56
    def feature_name(self):
 
57
        return 'bzrlib._readdir_pyx'
 
58
 
 
59
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
62
60
 
63
61
term_ios_feature = features.ModuleAvailableFeature('termios')
64
62
 
84
82
    # Some DirReaders are platform specific and even there they may not be
85
83
    # available.
86
84
    if UTF8DirReaderFeature.available():
87
 
        from .. import _readdir_pyx
 
85
        from bzrlib import _readdir_pyx
88
86
        scenarios.append(('utf8',
89
87
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
90
88
                               _native_to_unicode=_utf8_to_unicode)))
91
89
 
92
90
    if test__walkdirs_win32.win32_readdir_feature.available():
93
91
        try:
94
 
            from .. import _walkdirs_win32
 
92
            from bzrlib import _walkdirs_win32
95
93
            scenarios.append(
96
94
                ('win32',
97
95
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
182
180
        # we can't use failUnlessExists on case-insensitive filesystem
183
181
        # so try to check shape of the tree
184
182
        shape = sorted(os.listdir('.'))
185
 
        self.assertEqual(['A', 'B'], shape)
 
183
        self.assertEquals(['A', 'B'], shape)
186
184
 
187
185
    def test_rename_exception(self):
188
186
        try:
189
187
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
190
 
        except OSError as e:
 
188
        except OSError, e:
191
189
            self.assertEqual(e.old_filename, 'nonexistent_path')
192
190
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
193
191
            self.assertTrue('nonexistent_path' in e.strerror)
224
222
                         (['src'], SRC_FOO_C),
225
223
                         (['src'], 'src'),
226
224
                         ]:
227
 
            self.assertTrue(osutils.is_inside_any(dirs, fn))
 
225
            self.assert_(osutils.is_inside_any(dirs, fn))
228
226
        for dirs, fn in [(['src'], 'srccontrol'),
229
227
                         (['src'], 'srccontrol/foo')]:
230
228
            self.assertFalse(osutils.is_inside_any(dirs, fn))
236
234
                         (['src/bar.c', 'bla/foo.c'], 'src'),
237
235
                         (['src'], 'src'),
238
236
                         ]:
239
 
            self.assertTrue(osutils.is_inside_or_parent_of_any(dirs, fn))
 
237
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
240
238
 
241
239
        for dirs, fn in [(['src'], 'srccontrol'),
242
240
                         (['srccontrol/foo.c'], 'src'),
300
298
 
301
299
    def test_file_kind(self):
302
300
        self.build_tree(['file', 'dir/'])
303
 
        self.assertEqual('file', osutils.file_kind('file'))
304
 
        self.assertEqual('directory', osutils.file_kind('dir/'))
 
301
        self.assertEquals('file', osutils.file_kind('file'))
 
302
        self.assertEquals('directory', osutils.file_kind('dir/'))
305
303
        if osutils.has_symlinks():
306
304
            os.symlink('symlink', 'symlink')
307
 
            self.assertEqual('symlink', osutils.file_kind('symlink'))
 
305
            self.assertEquals('symlink', osutils.file_kind('symlink'))
308
306
 
309
307
        # TODO: jam 20060529 Test a block device
310
308
        try:
311
309
            os.lstat('/dev/null')
312
 
        except OSError as e:
 
310
        except OSError, e:
313
311
            if e.errno not in (errno.ENOENT,):
314
312
                raise
315
313
        else:
316
 
            self.assertEqual('chardev', osutils.file_kind('/dev/null'))
 
314
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
317
315
 
318
316
        mkfifo = getattr(os, 'mkfifo', None)
319
317
        if mkfifo:
320
318
            mkfifo('fifo')
321
319
            try:
322
 
                self.assertEqual('fifo', osutils.file_kind('fifo'))
 
320
                self.assertEquals('fifo', osutils.file_kind('fifo'))
323
321
            finally:
324
322
                os.remove('fifo')
325
323
 
328
326
            s = socket.socket(AF_UNIX)
329
327
            s.bind('socket')
330
328
            try:
331
 
                self.assertEqual('socket', osutils.file_kind('socket'))
 
329
                self.assertEquals('socket', osutils.file_kind('socket'))
332
330
            finally:
333
331
                os.remove('socket')
334
332
 
353
351
 
354
352
        orig_umask = osutils.get_umask()
355
353
        self.addCleanup(os.umask, orig_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())
 
354
        os.umask(0222)
 
355
        self.assertEqual(0222, osutils.get_umask())
 
356
        os.umask(0022)
 
357
        self.assertEqual(0022, osutils.get_umask())
 
358
        os.umask(0002)
 
359
        self.assertEqual(0002, osutils.get_umask())
 
360
        os.umask(0027)
 
361
        self.assertEqual(0027, osutils.get_umask())
364
362
 
365
363
 
366
364
class TestDateTime(tests.TestCase):
402
400
        self.assertFormatedDelta('2 seconds in the future', -2)
403
401
 
404
402
    def test_format_date(self):
405
 
        self.assertRaises(osutils.UnsupportedTimezoneFormat,
 
403
        self.assertRaises(errors.UnsupportedTimezoneFormat,
406
404
            osutils.format_date, 0, timezone='foo')
407
405
        self.assertIsInstance(osutils.format_date(0), str)
408
406
        self.assertIsInstance(osutils.format_local_date(0), unicode)
519
517
        # Make a file readonly
520
518
        osutils.make_readonly('file')
521
519
        mode = os.lstat('file').st_mode
522
 
        self.assertEqual(mode, mode & 0o777555)
 
520
        self.assertEqual(mode, mode & 0777555)
523
521
 
524
522
        # Make a file writable
525
523
        osutils.make_writable('file')
526
524
        mode = os.lstat('file').st_mode
527
 
        self.assertEqual(mode, mode | 0o200)
 
525
        self.assertEqual(mode, mode | 0200)
528
526
 
529
527
        if osutils.has_symlinks():
530
528
            # should not error when handed a symlink
603
601
        super(TestPumpFile, self).setUp()
604
602
        # create a test datablock
605
603
        self.block_size = 512
606
 
        pattern = b'0123456789ABCDEF'
607
 
        self.test_data = pattern * (3 * self.block_size // len(pattern))
 
604
        pattern = '0123456789ABCDEF'
 
605
        self.test_data = pattern * (3 * self.block_size / len(pattern))
608
606
        self.test_data_len = len(self.test_data)
609
607
 
610
608
    def test_bracket_block_size(self):
614
612
        self.assertTrue(self.test_data_len > self.block_size)
615
613
 
616
614
        from_file = file_utils.FakeReadFile(self.test_data)
617
 
        to_file = BytesIO()
 
615
        to_file = StringIO()
618
616
 
619
 
        # read (max // 2) bytes and verify read size wasn't affected
620
 
        num_bytes_to_read = self.block_size // 2
 
617
        # read (max / 2) bytes and verify read size wasn't affected
 
618
        num_bytes_to_read = self.block_size / 2
621
619
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
622
620
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
623
621
        self.assertEqual(from_file.get_read_count(), 1)
655
653
 
656
654
        # retrieve data in blocks
657
655
        from_file = file_utils.FakeReadFile(self.test_data)
658
 
        to_file = BytesIO()
 
656
        to_file = StringIO()
659
657
        osutils.pumpfile(from_file, to_file, self.test_data_len,
660
658
                         self.block_size)
661
659
 
679
677
 
680
678
        # retrieve data to EOF
681
679
        from_file = file_utils.FakeReadFile(self.test_data)
682
 
        to_file = BytesIO()
 
680
        to_file = StringIO()
683
681
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
684
682
 
685
683
        # verify read size was equal to the maximum read size
699
697
        with this new version."""
700
698
        # retrieve data using default (old) pumpfile method
701
699
        from_file = file_utils.FakeReadFile(self.test_data)
702
 
        to_file = BytesIO()
 
700
        to_file = StringIO()
703
701
        osutils.pumpfile(from_file, to_file)
704
702
 
705
703
        # report error if the data wasn't equal (we only report the size due
713
711
        activity = []
714
712
        def log_activity(length, direction):
715
713
            activity.append((length, direction))
716
 
        from_file = BytesIO(self.test_data)
717
 
        to_file = BytesIO()
 
714
        from_file = StringIO(self.test_data)
 
715
        to_file = StringIO()
718
716
        osutils.pumpfile(from_file, to_file, buff_size=500,
719
717
                         report_activity=log_activity, direction='read')
720
718
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
721
719
                          (36, 'read')], activity)
722
720
 
723
 
        from_file = BytesIO(self.test_data)
724
 
        to_file = BytesIO()
 
721
        from_file = StringIO(self.test_data)
 
722
        to_file = StringIO()
725
723
        del activity[:]
726
724
        osutils.pumpfile(from_file, to_file, buff_size=500,
727
725
                         report_activity=log_activity, direction='write')
729
727
                          (36, 'write')], activity)
730
728
 
731
729
        # And with a limited amount of data
732
 
        from_file = BytesIO(self.test_data)
733
 
        to_file = BytesIO()
 
730
        from_file = StringIO(self.test_data)
 
731
        to_file = StringIO()
734
732
        del activity[:]
735
733
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
736
734
                         report_activity=log_activity, direction='read')
741
739
class TestPumpStringFile(tests.TestCase):
742
740
 
743
741
    def test_empty(self):
744
 
        output = BytesIO()
745
 
        osutils.pump_string_file(b"", output)
746
 
        self.assertEqual(b"", output.getvalue())
 
742
        output = StringIO()
 
743
        osutils.pump_string_file("", output)
 
744
        self.assertEqual("", output.getvalue())
747
745
 
748
746
    def test_more_than_segment_size(self):
749
 
        output = BytesIO()
750
 
        osutils.pump_string_file(b"123456789", output, 2)
751
 
        self.assertEqual(b"123456789", output.getvalue())
 
747
        output = StringIO()
 
748
        osutils.pump_string_file("123456789", output, 2)
 
749
        self.assertEqual("123456789", output.getvalue())
752
750
 
753
751
    def test_segment_size(self):
754
 
        output = BytesIO()
755
 
        osutils.pump_string_file(b"12", output, 2)
756
 
        self.assertEqual(b"12", output.getvalue())
 
752
        output = StringIO()
 
753
        osutils.pump_string_file("12", output, 2)
 
754
        self.assertEqual("12", output.getvalue())
757
755
 
758
756
    def test_segment_size_multiple(self):
759
 
        output = BytesIO()
760
 
        osutils.pump_string_file(b"1234", output, 2)
761
 
        self.assertEqual(b"1234", output.getvalue())
 
757
        output = StringIO()
 
758
        osutils.pump_string_file("1234", output, 2)
 
759
        self.assertEqual("1234", output.getvalue())
762
760
 
763
761
 
764
762
class TestRelpath(tests.TestCase):
827
825
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
828
826
 
829
827
    def test_from_unicode_string_ascii_contents(self):
830
 
        self.assertRaises(TypeError,
831
 
                          osutils.safe_revision_id, u'bargam')
 
828
        self.assertEqual('bargam',
 
829
                         osutils.safe_revision_id(u'bargam', warn=False))
 
830
 
 
831
    def test_from_unicode_deprecated(self):
 
832
        self.assertEqual('bargam',
 
833
            self.callDeprecated([osutils._revision_id_warning],
 
834
                                osutils.safe_revision_id, u'bargam'))
832
835
 
833
836
    def test_from_unicode_string_unicode_contents(self):
834
 
        self.assertRaises(TypeError,
835
 
                         osutils.safe_revision_id, u'bargam\xae')
 
837
        self.assertEqual('bargam\xc2\xae',
 
838
                         osutils.safe_revision_id(u'bargam\xae', warn=False))
836
839
 
837
840
    def test_from_utf8_string(self):
838
841
        self.assertEqual('foo\xc2\xae',
849
852
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
850
853
 
851
854
    def test_from_unicode_string_ascii_contents(self):
852
 
        self.assertRaises(TypeError, osutils.safe_file_id, u'bargam')
 
855
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
 
856
 
 
857
    def test_from_unicode_deprecated(self):
 
858
        self.assertEqual('bargam',
 
859
            self.callDeprecated([osutils._file_id_warning],
 
860
                                osutils.safe_file_id, u'bargam'))
853
861
 
854
862
    def test_from_unicode_string_unicode_contents(self):
855
 
        self.assertRaises(TypeError,
856
 
                          osutils.safe_file_id, u'bargam\xae')
 
863
        self.assertEqual('bargam\xc2\xae',
 
864
                         osutils.safe_file_id(u'bargam\xae', warn=False))
857
865
 
858
866
    def test_from_utf8_string(self):
859
867
        self.assertEqual('foo\xc2\xae',
882
890
        for err in errs:
883
891
            sock = DisconnectedSocket(err)
884
892
            self.assertRaises(errors.ConnectionReset,
885
 
                osutils.send_all, sock, b'some more content')
 
893
                osutils.send_all, sock, 'some more content')
886
894
 
887
895
    def test_send_with_no_progress(self):
888
896
        # See https://bugs.launchpad.net/bzr/+bug/1047309
899
907
                return 0
900
908
        sock = NoSendingSocket()
901
909
        self.assertRaises(errors.ConnectionReset,
902
 
                          osutils.send_all, sock, b'content')
 
910
                          osutils.send_all, sock, 'content')
903
911
        self.assertEqual(1, sock.call_count)
904
912
 
905
913
 
955
963
 
956
964
    def test_getcwd(self):
957
965
        cwd = osutils._win32_getcwd()
958
 
        os_cwd = osutils._getcwd()
 
966
        os_cwd = os.getcwdu()
959
967
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
960
968
        # win32 is inconsistent whether it returns lower or upper case
961
969
        # and even if it was consistent the user might type the other
969
977
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
970
978
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
971
979
 
 
980
    def test_win98_abspath(self):
 
981
        self.requireFeature(features.win32_feature)
 
982
        # absolute path
 
983
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
 
984
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
 
985
        # UNC path
 
986
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
 
987
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
 
988
        # relative path
 
989
        cwd = osutils.getcwd().rstrip('/')
 
990
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
991
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
 
992
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
 
993
        # unicode path
 
994
        u = u'\u1234'
 
995
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
 
996
 
972
997
 
973
998
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
974
999
    """Test win32 functions that create files."""
986
1011
    def test_minimum_path_selection(self):
987
1012
        self.assertEqual(set(),
988
1013
            osutils.minimum_path_selection([]))
989
 
        self.assertEqual({'a'},
 
1014
        self.assertEqual(set(['a']),
990
1015
            osutils.minimum_path_selection(['a']))
991
 
        self.assertEqual({'a', 'b'},
 
1016
        self.assertEqual(set(['a', 'b']),
992
1017
            osutils.minimum_path_selection(['a', 'b']))
993
 
        self.assertEqual({'a/', 'b'},
 
1018
        self.assertEqual(set(['a/', 'b']),
994
1019
            osutils.minimum_path_selection(['a/', 'b']))
995
 
        self.assertEqual({'a/', 'b'},
 
1020
        self.assertEqual(set(['a/', 'b']),
996
1021
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
997
 
        self.assertEqual({'a-b', 'a', 'a0b'},
 
1022
        self.assertEqual(set(['a-b', 'a', 'a0b']),
998
1023
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
999
1024
 
1000
1025
    def test_mkdtemp(self):
1021
1046
 
1022
1047
        try:
1023
1048
            osutils._win32_rename('b', 'a')
1024
 
        except (IOError, OSError) as e:
 
1049
        except (IOError, OSError), e:
1025
1050
            self.assertEqual(errno.ENOENT, e.errno)
1026
1051
        self.assertFileEqual('foo\n', 'a')
1027
1052
 
1029
1054
        os.mkdir('a')
1030
1055
        try:
1031
1056
            osutils._win32_rename('b', 'a')
1032
 
        except (IOError, OSError) as e:
 
1057
        except (IOError, OSError), e:
1033
1058
            self.assertEqual(errno.ENOENT, e.errno)
1034
1059
 
1035
1060
    def test_rename_current_dir(self):
1041
1066
        # doesn't exist.
1042
1067
        try:
1043
1068
            osutils._win32_rename('b', '.')
1044
 
        except (IOError, OSError) as e:
 
1069
        except (IOError, OSError), e:
1045
1070
            self.assertEqual(errno.ENOENT, e.errno)
1046
1071
 
1047
1072
    def test_splitpath(self):
1092
1117
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
1093
1118
 
1094
1119
    def test_osutils_binding(self):
1095
 
        from . import test__chunks_to_lines
 
1120
        from bzrlib.tests import test__chunks_to_lines
1096
1121
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
1097
 
            from .._chunks_to_lines_pyx import chunks_to_lines
 
1122
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1098
1123
        else:
1099
 
            from .._chunks_to_lines_py import chunks_to_lines
 
1124
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1100
1125
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
1101
1126
 
1102
1127
 
1175
1200
        os.mkdir("test-unreadable")
1176
1201
        os.chmod("test-unreadable", 0000)
1177
1202
        # must chmod it back so that it can be removed
1178
 
        self.addCleanup(os.chmod, "test-unreadable", 0o700)
 
1203
        self.addCleanup(os.chmod, "test-unreadable", 0700)
1179
1204
        # The error is not raised until the generator is actually evaluated.
1180
1205
        # (It would be ok if it happened earlier but at the moment it
1181
1206
        # doesn't.)
1182
1207
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1183
 
        self.assertEqual('./test-unreadable', e.filename)
1184
 
        self.assertEqual(errno.EACCES, e.errno)
 
1208
        self.assertEquals('./test-unreadable', e.filename)
 
1209
        self.assertEquals(errno.EACCES, e.errno)
1185
1210
        # Ensure the message contains the file name
1186
 
        self.assertContainsRe(str(e), "\\./test-unreadable")
 
1211
        self.assertContainsRe(str(e), "\./test-unreadable")
1187
1212
 
1188
1213
 
1189
1214
    def test_walkdirs_encoding_error(self):
1208
1233
        # rename the 1file to a latin-1 filename
1209
1234
        os.rename("./1file", "\xe8file")
1210
1235
        if "\xe8file" not in os.listdir("."):
1211
 
            self.skipTest("Lack filesystem that preserves arbitrary bytes")
 
1236
            self.skip("Lack filesystem that preserves arbitrary bytes")
1212
1237
 
1213
1238
        self._save_platform_info()
 
1239
        win32utils.winver = None # Avoid the win32 detection code
1214
1240
        osutils._fs_enc = 'UTF-8'
1215
1241
 
1216
1242
        # this should raise on error
1275
1301
            dirblock[:] = new_dirblock
1276
1302
 
1277
1303
    def _save_platform_info(self):
 
1304
        self.overrideAttr(win32utils, 'winver')
1278
1305
        self.overrideAttr(osutils, '_fs_enc')
1279
1306
        self.overrideAttr(osutils, '_selected_dir_reader')
1280
1307
 
1289
1316
    def test_force_walkdirs_utf8_fs_utf8(self):
1290
1317
        self.requireFeature(UTF8DirReaderFeature)
1291
1318
        self._save_platform_info()
 
1319
        win32utils.winver = None # Avoid the win32 detection code
1292
1320
        osutils._fs_enc = 'utf-8'
1293
1321
        self.assertDirReaderIs(
1294
1322
            UTF8DirReaderFeature.module.UTF8DirReader)
1296
1324
    def test_force_walkdirs_utf8_fs_ascii(self):
1297
1325
        self.requireFeature(UTF8DirReaderFeature)
1298
1326
        self._save_platform_info()
 
1327
        win32utils.winver = None # Avoid the win32 detection code
1299
1328
        osutils._fs_enc = 'ascii'
1300
1329
        self.assertDirReaderIs(
1301
1330
            UTF8DirReaderFeature.module.UTF8DirReader)
1302
1331
 
1303
1332
    def test_force_walkdirs_utf8_fs_latin1(self):
1304
1333
        self._save_platform_info()
 
1334
        win32utils.winver = None # Avoid the win32 detection code
1305
1335
        osutils._fs_enc = 'iso-8859-1'
1306
1336
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1307
1337
 
1309
1339
        # Disabled because the thunk of the whole walkdirs api is disabled.
1310
1340
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1311
1341
        self._save_platform_info()
1312
 
        from .._walkdirs_win32 import Win32ReadDir
 
1342
        win32utils.winver = 'Windows NT'
 
1343
        from bzrlib._walkdirs_win32 import Win32ReadDir
1313
1344
        self.assertDirReaderIs(Win32ReadDir)
1314
1345
 
 
1346
    def test_force_walkdirs_utf8_98(self):
 
1347
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1348
        self._save_platform_info()
 
1349
        win32utils.winver = 'Windows 98'
 
1350
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
1351
 
1315
1352
    def test_unicode_walkdirs(self):
1316
1353
        """Walkdirs should always return unicode paths."""
1317
1354
        self.requireFeature(features.UnicodeFilenameFeature)
1466
1503
    def test__walkdirs_utf8_win32readdir(self):
1467
1504
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1468
1505
        self.requireFeature(features.UnicodeFilenameFeature)
1469
 
        from .._walkdirs_win32 import Win32ReadDir
 
1506
        from bzrlib._walkdirs_win32 import Win32ReadDir
1470
1507
        self._save_platform_info()
1471
1508
        osutils._selected_dir_reader = Win32ReadDir()
1472
1509
        name0u = u'0file-\xb6'
1523
1560
        """make sure our Stat values are valid"""
1524
1561
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1525
1562
        self.requireFeature(features.UnicodeFilenameFeature)
1526
 
        from .._walkdirs_win32 import Win32ReadDir
 
1563
        from bzrlib._walkdirs_win32 import Win32ReadDir
1527
1564
        name0u = u'0file-\xb6'
1528
1565
        name0 = name0u.encode('utf8')
1529
1566
        self.build_tree([name0u])
1547
1584
        """make sure our Stat values are valid"""
1548
1585
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1549
1586
        self.requireFeature(features.UnicodeFilenameFeature)
1550
 
        from .._walkdirs_win32 import Win32ReadDir
 
1587
        from bzrlib._walkdirs_win32 import Win32ReadDir
1551
1588
        name0u = u'0dir-\u062c\u0648'
1552
1589
        name0 = name0u.encode('utf8')
1553
1590
        self.build_tree([name0u + '/'])
1668
1705
            processed_files.append(('d', from_path, to_path))
1669
1706
        def link_handler(from_path, to_path):
1670
1707
            processed_links.append((from_path, to_path))
1671
 
        handlers = {'file': file_handler,
1672
 
                    'directory': dir_handler,
1673
 
                    'symlink': link_handler,
 
1708
        handlers = {'file':file_handler,
 
1709
                    'directory':dir_handler,
 
1710
                    'symlink':link_handler,
1674
1711
                   }
1675
1712
 
1676
1713
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1694
1731
    def setUp(self):
1695
1732
        super(TestSetUnsetEnv, self).setUp()
1696
1733
 
1697
 
        self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'),
 
1734
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1698
1735
                         'Environment was not cleaned up properly.'
1699
 
                         ' Variable BRZ_TEST_ENV_VAR should not exist.')
 
1736
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
1700
1737
        def cleanup():
1701
 
            if 'BRZ_TEST_ENV_VAR' in os.environ:
1702
 
                del os.environ['BRZ_TEST_ENV_VAR']
 
1738
            if 'BZR_TEST_ENV_VAR' in os.environ:
 
1739
                del os.environ['BZR_TEST_ENV_VAR']
1703
1740
        self.addCleanup(cleanup)
1704
1741
 
1705
1742
    def test_set(self):
1706
1743
        """Test that we can set an env variable"""
1707
 
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
 
1744
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1708
1745
        self.assertEqual(None, old)
1709
 
        self.assertEqual('foo', os.environ.get('BRZ_TEST_ENV_VAR'))
 
1746
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1710
1747
 
1711
1748
    def test_double_set(self):
1712
1749
        """Test that we get the old value out"""
1713
 
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1714
 
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'bar')
 
1750
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1751
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
1715
1752
        self.assertEqual('foo', old)
1716
 
        self.assertEqual('bar', os.environ.get('BRZ_TEST_ENV_VAR'))
 
1753
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1717
1754
 
1718
1755
    def test_unicode(self):
1719
1756
        """Environment can only contain plain strings
1726
1763
                'Cannot find a unicode character that works in encoding %s'
1727
1764
                % (osutils.get_user_encoding(),))
1728
1765
 
1729
 
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', uni_val)
1730
 
        self.assertEqual(env_val, os.environ.get('BRZ_TEST_ENV_VAR'))
 
1766
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
 
1767
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1731
1768
 
1732
1769
    def test_unset(self):
1733
1770
        """Test that passing None will remove the env var"""
1734
 
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1735
 
        old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', None)
 
1771
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1772
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1736
1773
        self.assertEqual('foo', old)
1737
 
        self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'))
1738
 
        self.assertFalse('BRZ_TEST_ENV_VAR' in os.environ)
 
1774
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
 
1775
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1739
1776
 
1740
1777
 
1741
1778
class TestSizeShaFile(tests.TestCaseInTempDir):
1742
1779
 
1743
1780
    def test_sha_empty(self):
1744
 
        self.build_tree_contents([('foo', b'')])
 
1781
        self.build_tree_contents([('foo', '')])
1745
1782
        expected_sha = osutils.sha_string('')
1746
1783
        f = open('foo')
1747
1784
        self.addCleanup(f.close)
1750
1787
        self.assertEqual(expected_sha, sha)
1751
1788
 
1752
1789
    def test_sha_mixed_endings(self):
1753
 
        text = b'test\r\nwith\nall\rpossible line endings\r\n'
 
1790
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1754
1791
        self.build_tree_contents([('foo', text)])
1755
1792
        expected_sha = osutils.sha_string(text)
1756
1793
        f = open('foo', 'rb')
1763
1800
class TestShaFileByName(tests.TestCaseInTempDir):
1764
1801
 
1765
1802
    def test_sha_empty(self):
1766
 
        self.build_tree_contents([('foo', b'')])
 
1803
        self.build_tree_contents([('foo', '')])
1767
1804
        expected_sha = osutils.sha_string('')
1768
1805
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1769
1806
 
1770
1807
    def test_sha_mixed_endings(self):
1771
 
        text = b'test\r\nwith\nall\rpossible line endings\r\n'
 
1808
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1772
1809
        self.build_tree_contents([('foo', text)])
1773
1810
        expected_sha = osutils.sha_string(text)
1774
1811
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1777
1814
class TestResourceLoading(tests.TestCaseInTempDir):
1778
1815
 
1779
1816
    def test_resource_string(self):
1780
 
        # test resource in breezy
1781
 
        text = osutils.resource_string('breezy', 'debug.py')
 
1817
        # test resource in bzrlib
 
1818
        text = osutils.resource_string('bzrlib', 'debug.py')
1782
1819
        self.assertContainsRe(text, "debug_flags = set()")
1783
 
        # test resource under breezy
1784
 
        text = osutils.resource_string('breezy.ui', 'text.py')
 
1820
        # test resource under bzrlib
 
1821
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1785
1822
        self.assertContainsRe(text, "class TextUIFactory")
1786
1823
        # test unsupported package
1787
1824
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1788
1825
            'yyy.xx')
1789
1826
        # test unknown resource
1790
 
        self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
 
1827
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
 
1828
 
 
1829
 
 
1830
class TestReCompile(tests.TestCase):
 
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
 
 
1836
    def test_re_compile_checked(self):
 
1837
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1838
        self.assertTrue(r.match('aaaa'))
 
1839
        self.assertTrue(r.match('aAaA'))
 
1840
 
 
1841
    def test_re_compile_checked_error(self):
 
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()
 
1847
        err = self.assertRaises(
 
1848
            errors.BzrCommandError,
 
1849
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1850
        self.assertEqual(
 
1851
            'Invalid regular expression in test case: '
 
1852
            '"*" nothing to repeat',
 
1853
            str(err))
1791
1854
 
1792
1855
 
1793
1856
class TestDirReader(tests.TestCaseInTempDir):
1940
2003
        os.symlink(self.target, self.link)
1941
2004
 
1942
2005
    def test_os_readlink_link_encoding(self):
1943
 
        self.assertEqual(self.target,  os.readlink(self.link))
 
2006
        self.assertEquals(self.target,  os.readlink(self.link))
1944
2007
 
1945
2008
    def test_os_readlink_link_decoding(self):
1946
 
        self.assertEqual(self.target.encode(osutils._fs_enc),
 
2009
        self.assertEquals(self.target.encode(osutils._fs_enc),
1947
2010
                          os.readlink(self.link.encode(osutils._fs_enc)))
1948
2011
 
1949
2012
 
1958
2021
        self.assertIsInstance(concurrency, int)
1959
2022
 
1960
2023
    def test_local_concurrency_environment_variable(self):
1961
 
        self.overrideEnv('BRZ_CONCURRENCY', '2')
 
2024
        self.overrideEnv('BZR_CONCURRENCY', '2')
1962
2025
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1963
 
        self.overrideEnv('BRZ_CONCURRENCY', '3')
 
2026
        self.overrideEnv('BZR_CONCURRENCY', '3')
1964
2027
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1965
 
        self.overrideEnv('BRZ_CONCURRENCY', 'foo')
 
2028
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
1966
2029
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1967
2030
 
1968
2031
    def test_option_concurrency(self):
1969
 
        self.overrideEnv('BRZ_CONCURRENCY', '1')
 
2032
        self.overrideEnv('BZR_CONCURRENCY', '1')
1970
2033
        self.run_bzr('rocks --concurrency 42')
1971
2034
        # Command line overrides environment variable
1972
 
        self.assertEqual('42', os.environ['BRZ_CONCURRENCY'])
1973
 
        self.assertEqual(42, osutils.local_concurrency(use_cache=False))
 
2035
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
 
2036
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1974
2037
 
1975
2038
 
1976
2039
class TestFailedToLoadExtension(tests.TestCase):
1977
2040
 
1978
2041
    def _try_loading(self):
1979
2042
        try:
1980
 
            import breezy._fictional_extension_py
1981
 
        except ImportError as e:
 
2043
            import bzrlib._fictional_extension_py
 
2044
        except ImportError, e:
1982
2045
            osutils.failed_to_load_extension(e)
1983
2046
            return True
1984
2047
 
1989
2052
    def test_failure_to_load(self):
1990
2053
        self._try_loading()
1991
2054
        self.assertLength(1, osutils._extension_load_failures)
1992
 
        self.assertEqual(osutils._extension_load_failures[0],
 
2055
        self.assertEquals(osutils._extension_load_failures[0],
1993
2056
            "No module named _fictional_extension_py")
1994
2057
 
1995
2058
    def test_report_extension_load_failures_no_warning(self):
1999
2062
        self.assertLength(0, warnings)
2000
2063
 
2001
2064
    def test_report_extension_load_failures_message(self):
2002
 
        log = BytesIO()
 
2065
        log = StringIO()
2003
2066
        trace.push_log_file(log)
2004
2067
        self.assertTrue(self._try_loading())
2005
2068
        osutils.report_extension_load_failures()
2006
2069
        self.assertContainsRe(
2007
2070
            log.getvalue(),
2008
 
            r"brz: warning: some compiled extensions could not be loaded; "
2009
 
            "see ``brz help missing-extensions``\n"
 
2071
            r"bzr: warning: some compiled extensions could not be loaded; "
 
2072
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
2010
2073
            )
2011
2074
 
2012
2075
 
2041
2104
    def test_default_values(self):
2042
2105
        self.assertEqual(80, osutils.default_terminal_width)
2043
2106
 
2044
 
    def test_defaults_to_BRZ_COLUMNS(self):
2045
 
        # BRZ_COLUMNS is set by the test framework
2046
 
        self.assertNotEqual('12', os.environ['BRZ_COLUMNS'])
2047
 
        self.overrideEnv('BRZ_COLUMNS', '12')
 
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')
2048
2111
        self.assertEqual(12, osutils.terminal_width())
2049
2112
 
2050
 
    def test_BRZ_COLUMNS_0_no_limit(self):
2051
 
        self.overrideEnv('BRZ_COLUMNS', '0')
 
2113
    def test_BZR_COLUMNS_0_no_limit(self):
 
2114
        self.overrideEnv('BZR_COLUMNS', '0')
2052
2115
        self.assertEqual(None, osutils.terminal_width())
2053
2116
 
2054
2117
    def test_falls_back_to_COLUMNS(self):
2055
 
        self.overrideEnv('BRZ_COLUMNS', None)
 
2118
        self.overrideEnv('BZR_COLUMNS', None)
2056
2119
        self.assertNotEqual('42', os.environ['COLUMNS'])
2057
2120
        self.set_fake_tty()
2058
2121
        self.overrideEnv('COLUMNS', '42')
2059
2122
        self.assertEqual(42, osutils.terminal_width())
2060
2123
 
2061
2124
    def test_tty_default_without_columns(self):
2062
 
        self.overrideEnv('BRZ_COLUMNS', None)
 
2125
        self.overrideEnv('BZR_COLUMNS', None)
2063
2126
        self.overrideEnv('COLUMNS', None)
2064
2127
 
2065
2128
        def terminal_size(w, h):
2073
2136
        self.assertEqual(42, osutils.terminal_width())
2074
2137
 
2075
2138
    def test_non_tty_default_without_columns(self):
2076
 
        self.overrideEnv('BRZ_COLUMNS', None)
 
2139
        self.overrideEnv('BZR_COLUMNS', None)
2077
2140
        self.overrideEnv('COLUMNS', None)
2078
2141
        self.replace_stdout(None)
2079
2142
        self.assertEqual(None, osutils.terminal_width())
2090
2153
        else:
2091
2154
            self.overrideAttr(termios, 'TIOCGWINSZ')
2092
2155
            del termios.TIOCGWINSZ
2093
 
        self.overrideEnv('BRZ_COLUMNS', None)
 
2156
        self.overrideEnv('BZR_COLUMNS', None)
2094
2157
        self.overrideEnv('COLUMNS', None)
2095
2158
        # Whatever the result is, if we don't raise an exception, it's ok.
2096
2159
        osutils.terminal_width()
2116
2179
        osutils.copy_ownership_from_path('test_file', ownsrc)
2117
2180
 
2118
2181
        s = os.stat(ownsrc)
2119
 
        self.assertEqual(self.path, 'test_file')
2120
 
        self.assertEqual(self.uid, s.st_uid)
2121
 
        self.assertEqual(self.gid, s.st_gid)
 
2182
        self.assertEquals(self.path, 'test_file')
 
2183
        self.assertEquals(self.uid, s.st_uid)
 
2184
        self.assertEquals(self.gid, s.st_gid)
2122
2185
 
2123
2186
    def test_copy_ownership_nonesrc(self):
2124
2187
        """copy_ownership_from_path test with src=None."""
2127
2190
        osutils.copy_ownership_from_path('test_file')
2128
2191
 
2129
2192
        s = os.stat('..')
2130
 
        self.assertEqual(self.path, 'test_file')
2131
 
        self.assertEqual(self.uid, s.st_uid)
2132
 
        self.assertEqual(self.gid, s.st_gid)
 
2193
        self.assertEquals(self.path, 'test_file')
 
2194
        self.assertEquals(self.uid, s.st_uid)
 
2195
        self.assertEquals(self.gid, s.st_gid)
2133
2196
 
2134
2197
 
2135
2198
class TestPathFromEnviron(tests.TestCase):
2136
2199
 
2137
2200
    def test_is_unicode(self):
2138
 
        self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
2139
 
        path = osutils.path_from_environ('BRZ_TEST_PATH')
 
2201
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
 
2202
        path = osutils.path_from_environ('BZR_TEST_PATH')
2140
2203
        self.assertIsInstance(path, unicode)
2141
2204
        self.assertEqual(u'./anywhere at all/', path)
2142
2205
 
2143
2206
    def test_posix_path_env_ascii(self):
2144
 
        self.overrideEnv('BRZ_TEST_PATH', '/tmp')
2145
 
        home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
 
2207
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
 
2208
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
2146
2209
        self.assertIsInstance(home, unicode)
2147
2210
        self.assertEqual(u'/tmp', home)
2148
2211
 
2149
2212
    def test_posix_path_env_unicode(self):
2150
2213
        self.requireFeature(features.ByteStringNamedFilesystem)
2151
 
        self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
 
2214
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
2152
2215
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2153
2216
        self.assertEqual(u'/home/\xa7test',
2154
 
            osutils._posix_path_from_environ('BRZ_TEST_PATH'))
 
2217
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2155
2218
        osutils._fs_enc = "iso8859-5"
2156
2219
        self.assertEqual(u'/home/\u0407test',
2157
 
            osutils._posix_path_from_environ('BRZ_TEST_PATH'))
 
2220
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2158
2221
        osutils._fs_enc = "utf-8"
2159
2222
        self.assertRaises(errors.BadFilenameEncoding,
2160
 
            osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
 
2223
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
2161
2224
 
2162
2225
 
2163
2226
class TestGetHomeDir(tests.TestCase):