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)
98
load_tests = load_tests_apply_scenarios
107
101
class TestContainsWhitespace(tests.TestCase):
109
103
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'))
104
self.assertTrue(osutils.contains_whitespace(u' '))
105
self.assertTrue(osutils.contains_whitespace(u'hello there'))
106
self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
107
self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
108
self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
109
self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
117
111
# \xa0 is "Non-breaking-space" which on some python locales thinks it
118
112
# 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'))
113
self.assertFalse(osutils.contains_whitespace(u''))
114
self.assertFalse(osutils.contains_whitespace(u'hellothere'))
115
self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
124
118
class TestRename(tests.TestCaseInTempDir):
137
131
def test_fancy_rename(self):
138
132
# This should work everywhere
139
self.create_file('a', 'something in a\n')
133
self.create_file('a', b'something in a\n')
140
134
self._fancy_rename('a', 'b')
141
self.failIfExists('a')
142
self.failUnlessExists('b')
143
self.check_file_contents('b', 'something in a\n')
135
self.assertPathDoesNotExist('a')
136
self.assertPathExists('b')
137
self.check_file_contents('b', b'something in a\n')
145
self.create_file('a', 'new something in a\n')
139
self.create_file('a', b'new something in a\n')
146
140
self._fancy_rename('b', 'a')
148
self.check_file_contents('a', 'something in a\n')
142
self.check_file_contents('a', b'something in a\n')
150
144
def test_fancy_rename_fails_source_missing(self):
151
145
# An exception should be raised, and the target should be left in place
152
self.create_file('target', 'data in target\n')
146
self.create_file('target', b'data in target\n')
153
147
self.assertRaises((IOError, OSError), self._fancy_rename,
154
148
'missingsource', 'target')
155
self.failUnlessExists('target')
156
self.check_file_contents('target', 'data in target\n')
149
self.assertPathExists('target')
150
self.check_file_contents('target', b'data in target\n')
158
152
def test_fancy_rename_fails_if_source_and_target_missing(self):
159
153
self.assertRaises((IOError, OSError), self._fancy_rename,
418
433
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
436
class TestFdatasync(tests.TestCaseInTempDir):
438
def do_fdatasync(self):
439
f = tempfile.NamedTemporaryFile()
440
osutils.fdatasync(f.fileno())
444
def raise_eopnotsupp(*args, **kwargs):
445
raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
448
def raise_enotsup(*args, **kwargs):
449
raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
451
def test_fdatasync_handles_system_function(self):
452
self.overrideAttr(os, "fdatasync")
455
def test_fdatasync_handles_no_fdatasync_no_fsync(self):
456
self.overrideAttr(os, "fdatasync")
457
self.overrideAttr(os, "fsync")
460
def test_fdatasync_handles_no_EOPNOTSUPP(self):
461
self.overrideAttr(errno, "EOPNOTSUPP")
464
def test_fdatasync_catches_ENOTSUP(self):
465
enotsup = getattr(errno, "ENOTSUP", None)
467
raise tests.TestNotApplicable("No ENOTSUP on this platform")
468
self.overrideAttr(os, "fdatasync", self.raise_enotsup)
471
def test_fdatasync_catches_EOPNOTSUPP(self):
472
enotsup = getattr(errno, "EOPNOTSUPP", None)
474
raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
475
self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
421
479
class TestLinks(tests.TestCaseInTempDir):
423
481
def test_dereference_path(self):
424
self.requireFeature(tests.SymlinkFeature)
482
self.requireFeature(features.SymlinkFeature)
425
483
cwd = osutils.realpath('.')
427
485
bar_path = osutils.pathjoin(cwd, 'bar')
550
607
self.assertTrue(self.test_data_len > self.block_size)
552
609
from_file = file_utils.FakeReadFile(self.test_data)
555
# read (max / 2) bytes and verify read size wasn't affected
556
num_bytes_to_read = self.block_size / 2
557
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
612
# read (max // 2) bytes and verify read size wasn't affected
613
num_bytes_to_read = self.block_size // 2
614
osutils.pumpfile(from_file, to_file,
615
num_bytes_to_read, self.block_size)
558
616
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
559
617
self.assertEqual(from_file.get_read_count(), 1)
561
619
# read (max) bytes and verify read size wasn't affected
562
620
num_bytes_to_read = self.block_size
563
621
from_file.reset_read_count()
564
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
622
osutils.pumpfile(from_file, to_file,
623
num_bytes_to_read, self.block_size)
565
624
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
566
625
self.assertEqual(from_file.get_read_count(), 1)
568
627
# read (max + 1) bytes and verify read size was limited
569
628
num_bytes_to_read = self.block_size + 1
570
629
from_file.reset_read_count()
571
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
630
osutils.pumpfile(from_file, to_file,
631
num_bytes_to_read, self.block_size)
572
632
self.assertEqual(from_file.get_max_read_size(), self.block_size)
573
633
self.assertEqual(from_file.get_read_count(), 2)
575
635
# finish reading the rest of the data
576
636
num_bytes_to_read = self.test_data_len - to_file.tell()
577
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
637
osutils.pumpfile(from_file, to_file,
638
num_bytes_to_read, self.block_size)
579
640
# report error if the data wasn't equal (we only report the size due
580
641
# to the length of the data)
665
727
(36, 'write')], activity)
667
729
# And with a limited amount of data
668
from_file = StringIO(self.test_data)
730
from_file = BytesIO(self.test_data)
671
733
osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
672
734
report_activity=log_activity, direction='read')
673
self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
736
[(500, 'read'), (500, 'read'), (28, 'read')], activity)
677
739
class TestPumpStringFile(tests.TestCase):
679
741
def test_empty(self):
681
osutils.pump_string_file("", output)
682
self.assertEqual("", output.getvalue())
743
osutils.pump_string_file(b"", output)
744
self.assertEqual(b"", output.getvalue())
684
746
def test_more_than_segment_size(self):
686
osutils.pump_string_file("123456789", output, 2)
687
self.assertEqual("123456789", output.getvalue())
748
osutils.pump_string_file(b"123456789", output, 2)
749
self.assertEqual(b"123456789", output.getvalue())
689
751
def test_segment_size(self):
691
osutils.pump_string_file("12", output, 2)
692
self.assertEqual("12", output.getvalue())
753
osutils.pump_string_file(b"12", output, 2)
754
self.assertEqual(b"12", output.getvalue())
694
756
def test_segment_size_multiple(self):
696
osutils.pump_string_file("1234", output, 2)
697
self.assertEqual("1234", output.getvalue())
758
osutils.pump_string_file(b"1234", output, 2)
759
self.assertEqual(b"1234", output.getvalue())
700
762
class TestRelpath(tests.TestCase):
728
790
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
730
792
def test_from_utf8_string(self):
731
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
793
self.assertEqual(u'foo\xae', osutils.safe_unicode(b'foo\xc2\xae'))
733
795
def test_bad_utf8_string(self):
734
796
self.assertRaises(errors.BzrBadParameterNotUnicode,
735
797
osutils.safe_unicode,
739
801
class TestSafeUtf8(tests.TestCase):
741
803
def test_from_ascii_string(self):
743
self.assertEqual('foobar', osutils.safe_utf8(f))
805
self.assertEqual(b'foobar', osutils.safe_utf8(f))
745
807
def test_from_unicode_string_ascii_contents(self):
746
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
808
self.assertEqual(b'bargam', osutils.safe_utf8(u'bargam'))
748
810
def test_from_unicode_string_unicode_contents(self):
749
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
811
self.assertEqual(b'bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
751
813
def test_from_utf8_string(self):
752
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
814
self.assertEqual(b'foo\xc2\xae', osutils.safe_utf8(b'foo\xc2\xae'))
754
816
def test_bad_utf8_string(self):
755
817
self.assertRaises(errors.BzrBadParameterNotUnicode,
756
osutils.safe_utf8, '\xbb\xbb')
759
class TestSafeRevisionId(tests.TestCase):
761
def test_from_ascii_string(self):
762
# this shouldn't give a warning because it's getting an ascii string
763
self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
765
def test_from_unicode_string_ascii_contents(self):
766
self.assertEqual('bargam',
767
osutils.safe_revision_id(u'bargam', warn=False))
769
def test_from_unicode_deprecated(self):
770
self.assertEqual('bargam',
771
self.callDeprecated([osutils._revision_id_warning],
772
osutils.safe_revision_id, u'bargam'))
774
def test_from_unicode_string_unicode_contents(self):
775
self.assertEqual('bargam\xc2\xae',
776
osutils.safe_revision_id(u'bargam\xae', warn=False))
778
def test_from_utf8_string(self):
779
self.assertEqual('foo\xc2\xae',
780
osutils.safe_revision_id('foo\xc2\xae'))
783
"""Currently, None is a valid revision_id"""
784
self.assertEqual(None, osutils.safe_revision_id(None))
787
class TestSafeFileId(tests.TestCase):
789
def test_from_ascii_string(self):
790
self.assertEqual('foobar', osutils.safe_file_id('foobar'))
792
def test_from_unicode_string_ascii_contents(self):
793
self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
795
def test_from_unicode_deprecated(self):
796
self.assertEqual('bargam',
797
self.callDeprecated([osutils._file_id_warning],
798
osutils.safe_file_id, u'bargam'))
800
def test_from_unicode_string_unicode_contents(self):
801
self.assertEqual('bargam\xc2\xae',
802
osutils.safe_file_id(u'bargam\xae', warn=False))
804
def test_from_utf8_string(self):
805
self.assertEqual('foo\xc2\xae',
806
osutils.safe_file_id('foo\xc2\xae'))
809
"""Currently, None is a valid revision_id"""
810
self.assertEqual(None, osutils.safe_file_id(None))
818
osutils.safe_utf8, b'\xbb\xbb')
821
class TestSendAll(tests.TestCase):
823
def test_send_with_disconnected_socket(self):
824
class DisconnectedSocket(object):
825
def __init__(self, err):
828
def send(self, content):
833
# All of these should be treated as ConnectionReset
835
for err_cls in (IOError, socket.error):
836
for errnum in osutils._end_of_stream_errors:
837
errs.append(err_cls(errnum))
839
sock = DisconnectedSocket(err)
840
self.assertRaises(errors.ConnectionReset,
841
osutils.send_all, sock, b'some more content')
843
def test_send_with_no_progress(self):
844
# See https://bugs.launchpad.net/bzr/+bug/1047309
845
# It seems that paramiko can get into a state where it doesn't error,
846
# but it returns 0 bytes sent for requests over and over again.
847
class NoSendingSocket(object):
851
def send(self, bytes):
853
if self.call_count > 100:
854
# Prevent the test suite from hanging
855
raise RuntimeError('too many calls')
857
sock = NoSendingSocket()
858
self.assertRaises(errors.ConnectionReset,
859
osutils.send_all, sock, b'content')
860
self.assertEqual(1, sock.call_count)
863
class TestPosixFuncs(tests.TestCase):
864
"""Test that the posix version of normpath returns an appropriate path
865
when used with 2 leading slashes."""
867
def test_normpath(self):
868
self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
870
'/etc/shadow', osutils._posix_normpath('//etc/shadow'))
872
'/etc/shadow', osutils._posix_normpath('///etc/shadow'))
813
875
class TestWin32Funcs(tests.TestCase):
814
876
"""Test that _win32 versions of os utilities return appropriate paths."""
816
878
def test_abspath(self):
879
self.requireFeature(features.win32_feature)
817
880
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
818
881
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
819
882
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
892
942
def test_minimum_path_selection(self):
893
943
self.assertEqual(set(),
894
osutils.minimum_path_selection([]))
895
self.assertEqual(set(['a']),
896
osutils.minimum_path_selection(['a']))
897
self.assertEqual(set(['a', 'b']),
898
osutils.minimum_path_selection(['a', 'b']))
899
self.assertEqual(set(['a/', 'b']),
900
osutils.minimum_path_selection(['a/', 'b']))
901
self.assertEqual(set(['a/', 'b']),
902
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
903
self.assertEqual(set(['a-b', 'a', 'a0b']),
904
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
944
osutils.minimum_path_selection([]))
945
self.assertEqual({'a'},
946
osutils.minimum_path_selection(['a']))
947
self.assertEqual({'a', 'b'},
948
osutils.minimum_path_selection(['a', 'b']))
949
self.assertEqual({'a/', 'b'},
950
osutils.minimum_path_selection(['a/', 'b']))
951
self.assertEqual({'a/', 'b'},
952
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
953
self.assertEqual({'a-b', 'a', 'a0b'},
954
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
906
956
def test_mkdtemp(self):
907
957
tmpdir = osutils._win32_mkdtemp(dir='.')
908
958
self.assertFalse('\\' in tmpdir)
910
960
def test_rename(self):
961
with open('a', 'wb') as a:
963
with open('b', 'wb') as b:
918
966
osutils._win32_rename('b', 'a')
919
self.failUnlessExists('a')
920
self.failIfExists('b')
921
self.assertFileEqual('baz\n', 'a')
967
self.assertPathExists('a')
968
self.assertPathDoesNotExist('b')
969
self.assertFileEqual(b'baz\n', 'a')
923
971
def test_rename_missing_file(self):
972
with open('a', 'wb') as a:
929
976
osutils._win32_rename('b', 'a')
930
except (IOError, OSError), e:
977
except (IOError, OSError) as e:
931
978
self.assertEqual(errno.ENOENT, e.errno)
932
self.assertFileEqual('foo\n', 'a')
979
self.assertFileEqual(b'foo\n', 'a')
934
981
def test_rename_missing_dir(self):
937
984
osutils._win32_rename('b', 'a')
938
except (IOError, OSError), e:
985
except (IOError, OSError) as e:
939
986
self.assertEqual(errno.ENOENT, e.errno)
941
988
def test_rename_current_dir(self):
1071
1121
self.assertExpectedBlocks(expected_dirblocks[1:], result)
1073
1123
def test_walkdirs_os_error(self):
1074
# <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1124
# <https://bugs.launchpad.net/bzr/+bug/338653>
1075
1125
# Pyrex readdir didn't raise useful messages if it had an error
1076
1126
# reading the directory
1077
1127
if sys.platform == 'win32':
1078
1128
raise tests.TestNotApplicable(
1079
1129
"readdir IOError not tested on win32")
1130
self.requireFeature(features.not_running_as_root)
1080
1131
os.mkdir("test-unreadable")
1081
1132
os.chmod("test-unreadable", 0000)
1082
1133
# must chmod it back so that it can be removed
1083
self.addCleanup(os.chmod, "test-unreadable", 0700)
1134
self.addCleanup(os.chmod, "test-unreadable", 0o700)
1084
1135
# The error is not raised until the generator is actually evaluated.
1085
1136
# (It would be ok if it happened earlier but at the moment it
1087
1138
e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1088
self.assertEquals('./test-unreadable', e.filename)
1089
self.assertEquals(errno.EACCES, e.errno)
1139
self.assertEqual('./test-unreadable', osutils.safe_unicode(e.filename))
1140
self.assertEqual(errno.EACCES, e.errno)
1090
1141
# Ensure the message contains the file name
1091
self.assertContainsRe(str(e), "\./test-unreadable")
1142
self.assertContainsRe(str(e), "\\./test-unreadable")
1144
def test_walkdirs_encoding_error(self):
1145
# <https://bugs.launchpad.net/bzr/+bug/488519>
1146
# walkdirs didn't raise a useful message when the filenames
1147
# are not using the filesystem's encoding
1149
# require a bytestring based filesystem
1150
self.requireFeature(features.ByteStringNamedFilesystem)
1161
self.build_tree(tree)
1163
# rename the 1file to a latin-1 filename
1164
os.rename(b"./1file", b"\xe8file")
1165
if b"\xe8file" not in os.listdir("."):
1166
self.skipTest("Lack filesystem that preserves arbitrary bytes")
1168
self._save_platform_info()
1169
osutils._fs_enc = 'UTF-8'
1171
# this should raise on error
1173
for dirdetail, dirblock in osutils.walkdirs(b'.'):
1176
self.assertRaises(errors.BadFilenameEncoding, attempt)
1093
1178
def test__walkdirs_utf8(self):
1102
1187
self.build_tree(tree)
1103
1188
expected_dirblocks = [
1105
[('0file', '0file', 'file'),
1106
('1dir', '1dir', 'directory'),
1107
('2file', '2file', 'file'),
1110
(('1dir', './1dir'),
1111
[('1dir/0file', '0file', 'file'),
1112
('1dir/1dir', '1dir', 'directory'),
1115
(('1dir/1dir', './1dir/1dir'),
1190
[('0file', '0file', 'file'),
1191
('1dir', '1dir', 'directory'),
1192
('2file', '2file', 'file'),
1195
(('1dir', './1dir'),
1196
[('1dir/0file', '0file', 'file'),
1197
('1dir/1dir', '1dir', 'directory'),
1200
(('1dir/1dir', './1dir/1dir'),
1121
1206
found_bzrdir = False
1122
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1123
if len(dirblock) and dirblock[0][1] == '.bzr':
1207
for dirdetail, dirblock in osutils._walkdirs_utf8(b'.'):
1208
if len(dirblock) and dirblock[0][1] == b'.bzr':
1124
1209
# this tests the filtering of selected paths
1125
1210
found_bzrdir = True
1126
1211
del dirblock[0]
1212
dirdetail = (dirdetail[0].decode('utf-8'),
1213
osutils.safe_unicode(dirdetail[1]))
1215
(entry[0].decode('utf-8'), entry[1].decode('utf-8'), entry[2])
1216
for entry in dirblock]
1127
1217
result.append((dirdetail, dirblock))
1129
1219
self.assertTrue(found_bzrdir)
1145
1235
dirblock[:] = new_dirblock
1147
1237
def _save_platform_info(self):
1148
self.overrideAttr(win32utils, 'winver')
1149
1238
self.overrideAttr(osutils, '_fs_enc')
1150
1239
self.overrideAttr(osutils, '_selected_dir_reader')
1152
def assertDirReaderIs(self, expected):
1241
def assertDirReaderIs(self, expected, top):
1153
1242
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
1154
1243
# Force it to redetect
1155
1244
osutils._selected_dir_reader = None
1156
1245
# Nothing to list, but should still trigger the selection logic
1157
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1246
self.assertEqual([((b'', top), [])], list(osutils._walkdirs_utf8('.')))
1158
1247
self.assertIsInstance(osutils._selected_dir_reader, expected)
1160
1249
def test_force_walkdirs_utf8_fs_utf8(self):
1161
1250
self.requireFeature(UTF8DirReaderFeature)
1162
1251
self._save_platform_info()
1163
win32utils.winver = None # Avoid the win32 detection code
1164
osutils._fs_enc = 'UTF-8'
1165
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1252
osutils._fs_enc = 'utf-8'
1253
self.assertDirReaderIs(UTF8DirReaderFeature.module.UTF8DirReader, b".")
1167
1255
def test_force_walkdirs_utf8_fs_ascii(self):
1168
1256
self.requireFeature(UTF8DirReaderFeature)
1169
1257
self._save_platform_info()
1170
win32utils.winver = None # Avoid the win32 detection code
1171
osutils._fs_enc = 'US-ASCII'
1172
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
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)
1258
osutils._fs_enc = 'ascii'
1259
self.assertDirReaderIs(
1260
UTF8DirReaderFeature.module.UTF8DirReader, b".")
1181
1262
def test_force_walkdirs_utf8_fs_latin1(self):
1182
1263
self._save_platform_info()
1183
win32utils.winver = None # Avoid the win32 detection code
1184
osutils._fs_enc = 'latin1'
1185
self.assertDirReaderIs(osutils.UnicodeDirReader)
1264
osutils._fs_enc = 'iso-8859-1'
1265
self.assertDirReaderIs(osutils.UnicodeDirReader, ".")
1187
1267
def test_force_walkdirs_utf8_nt(self):
1188
1268
# Disabled because the thunk of the whole walkdirs api is disabled.
1189
1269
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1190
1270
self._save_platform_info()
1191
win32utils.winver = 'Windows NT'
1192
from bzrlib._walkdirs_win32 import Win32ReadDir
1193
self.assertDirReaderIs(Win32ReadDir)
1195
def test_force_walkdirs_utf8_98(self):
1196
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1197
self._save_platform_info()
1198
win32utils.winver = 'Windows 98'
1199
self.assertDirReaderIs(osutils.UnicodeDirReader)
1271
from .._walkdirs_win32 import Win32ReadDir
1272
self.assertDirReaderIs(Win32ReadDir, ".")
1201
1274
def test_unicode_walkdirs(self):
1202
1275
"""Walkdirs should always return unicode paths."""
1203
self.requireFeature(tests.UnicodeFilenameFeature)
1276
self.requireFeature(features.UnicodeFilenameFeature)
1204
1277
name0 = u'0file-\xb6'
1205
1278
name1 = u'1dir-\u062c\u0648'
1206
1279
name2 = u'2file-\u0633'
1214
1287
self.build_tree(tree)
1215
1288
expected_dirblocks = [
1217
[(name0, name0, 'file', './' + name0),
1218
(name1, name1, 'directory', './' + name1),
1219
(name2, name2, 'file', './' + name2),
1222
((name1, './' + name1),
1223
[(name1 + '/' + name0, name0, 'file', './' + name1
1225
(name1 + '/' + name1, name1, 'directory', './' + name1
1229
((name1 + '/' + name1, './' + name1 + '/' + name1),
1290
[(name0, name0, 'file', './' + name0),
1291
(name1, name1, 'directory', './' + name1),
1292
(name2, name2, 'file', './' + name2),
1295
((name1, './' + name1),
1296
[(name1 + '/' + name0, name0, 'file', './' + name1
1298
(name1 + '/' + name1, name1, 'directory', './' + name1
1302
((name1 + '/' + name1, './' + name1 + '/' + name1),
1234
1307
result = list(osutils.walkdirs('.'))
1235
1308
self._filter_out_stat(result)
1236
1309
self.assertEqual(expected_dirblocks, result)
1237
result = list(osutils.walkdirs(u'./'+name1, name1))
1310
result = list(osutils.walkdirs(u'./' + name1, name1))
1238
1311
self._filter_out_stat(result)
1239
1312
self.assertEqual(expected_dirblocks[1:], result)
1260
1333
name2 = name2.encode('utf8')
1262
1335
expected_dirblocks = [
1264
[(name0, name0, 'file', './' + name0),
1265
(name1, name1, 'directory', './' + name1),
1266
(name2, name2, 'file', './' + name2),
1269
((name1, './' + name1),
1270
[(name1 + '/' + name0, name0, 'file', './' + name1
1272
(name1 + '/' + name1, name1, 'directory', './' + name1
1276
((name1 + '/' + name1, './' + name1 + '/' + name1),
1337
[(name0, name0, 'file', b'./' + name0),
1338
(name1, name1, 'directory', b'./' + name1),
1339
(name2, name2, 'file', b'./' + name2),
1342
((name1, b'./' + name1),
1343
[(name1 + b'/' + name0, name0, 'file', b'./' + name1
1345
(name1 + b'/' + name1, name1, 'directory', b'./' + name1
1349
((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1282
1355
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1283
1356
# all abspaths are Unicode, and encode them back into utf8.
1284
1357
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1285
self.assertIsInstance(dirdetail[0], str)
1286
if isinstance(dirdetail[1], unicode):
1358
self.assertIsInstance(dirdetail[0], bytes)
1359
if isinstance(dirdetail[1], str):
1287
1360
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1288
1361
dirblock = [list(info) for info in dirblock]
1289
1362
for info in dirblock:
1290
self.assertIsInstance(info[4], unicode)
1363
self.assertIsInstance(info[4], str)
1291
1364
info[4] = info[4].encode('utf8')
1292
1365
new_dirblock = []
1293
1366
for info in dirblock:
1294
self.assertIsInstance(info[0], str)
1295
self.assertIsInstance(info[1], str)
1296
self.assertIsInstance(info[4], str)
1367
self.assertIsInstance(info[0], bytes)
1368
self.assertIsInstance(info[1], bytes)
1369
self.assertIsInstance(info[4], bytes)
1297
1370
# Remove the stat information
1298
1371
new_dirblock.append((info[0], info[1], info[2], info[4]))
1299
1372
result.append((dirdetail, new_dirblock))
1327
1400
# All of the abspaths should be in unicode, all of the relative paths
1328
1401
# should be in utf8
1329
1402
expected_dirblocks = [
1331
[(name0, name0, 'file', './' + name0u),
1332
(name1, name1, 'directory', './' + name1u),
1333
(name2, name2, 'file', './' + name2u),
1336
((name1, './' + name1u),
1337
[(name1 + '/' + name0, name0, 'file', './' + name1u
1339
(name1 + '/' + name1, name1, 'directory', './' + name1u
1343
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1404
[(name0, name0, 'file', './' + name0u),
1405
(name1, name1, 'directory', './' + name1u),
1406
(name2, name2, 'file', './' + name2u),
1409
((name1, './' + name1u),
1410
[(name1 + b'/' + name0, name0, 'file', './' + name1u
1412
(name1 + b'/' + name1, name1, 'directory', './' + name1u
1416
((name1 + b'/' + name1, './' + name1u + '/' + name1u),
1348
1421
result = list(osutils._walkdirs_utf8('.'))
1349
1422
self._filter_out_stat(result)
1373
1446
# All of the abspaths should be in unicode, all of the relative paths
1374
1447
# should be in utf8
1375
1448
expected_dirblocks = [
1377
[(name0, name0, 'file', './' + name0u),
1378
(name1, name1, 'directory', './' + name1u),
1379
(name2, name2, 'file', './' + name2u),
1382
((name1, './' + name1u),
1383
[(name1 + '/' + name0, name0, 'file', './' + name1u
1385
(name1 + '/' + name1, name1, 'directory', './' + name1u
1389
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1450
[(name0, name0, 'file', './' + name0u),
1451
(name1, name1, 'directory', './' + name1u),
1452
(name2, name2, 'file', './' + name2u),
1455
((name1, './' + name1u),
1456
[(name1 + '/' + name0, name0, 'file', './' + name1u
1458
(name1 + '/' + name1, name1, 'directory', './' + name1u
1462
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1394
1467
result = list(osutils._walkdirs_utf8(u'.'))
1395
1468
self._filter_out_stat(result)
1580
1653
def setUp(self):
1581
1654
super(TestSetUnsetEnv, self).setUp()
1583
self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1656
self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'),
1584
1657
'Environment was not cleaned up properly.'
1585
' Variable BZR_TEST_ENV_VAR should not exist.')
1658
' Variable BRZ_TEST_ENV_VAR should not exist.')
1587
if 'BZR_TEST_ENV_VAR' in os.environ:
1588
del os.environ['BZR_TEST_ENV_VAR']
1661
if 'BRZ_TEST_ENV_VAR' in os.environ:
1662
del os.environ['BRZ_TEST_ENV_VAR']
1589
1663
self.addCleanup(cleanup)
1591
1665
def test_set(self):
1592
1666
"""Test that we can set an env variable"""
1593
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1667
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1594
1668
self.assertEqual(None, old)
1595
self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1669
self.assertEqual('foo', os.environ.get('BRZ_TEST_ENV_VAR'))
1597
1671
def test_double_set(self):
1598
1672
"""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')
1673
osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1674
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'bar')
1601
1675
self.assertEqual('foo', old)
1602
self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1676
self.assertEqual('bar', os.environ.get('BRZ_TEST_ENV_VAR'))
1604
1678
def test_unicode(self):
1605
1679
"""Environment can only contain plain strings
1612
1686
'Cannot find a unicode character that works in encoding %s'
1613
1687
% (osutils.get_user_encoding(),))
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'))
1689
osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', uni_val)
1690
self.assertEqual(uni_val, os.environ.get('BRZ_TEST_ENV_VAR'))
1618
1692
def test_unset(self):
1619
1693
"""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)
1694
osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1695
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', None)
1622
1696
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)
1697
self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'))
1698
self.assertNotIn('BRZ_TEST_ENV_VAR', os.environ)
1627
1701
class TestSizeShaFile(tests.TestCaseInTempDir):
1629
1703
def test_sha_empty(self):
1630
self.build_tree_contents([('foo', '')])
1631
expected_sha = osutils.sha_string('')
1704
self.build_tree_contents([('foo', b'')])
1705
expected_sha = osutils.sha_string(b'')
1632
1706
f = open('foo')
1633
1707
self.addCleanup(f.close)
1634
1708
size, sha = osutils.size_sha_file(f)
1663
1737
class TestResourceLoading(tests.TestCaseInTempDir):
1665
1739
def test_resource_string(self):
1666
# test resource in bzrlib
1667
text = osutils.resource_string('bzrlib', 'debug.py')
1740
# test resource in breezy
1741
text = osutils.resource_string('breezy', 'debug.py')
1668
1742
self.assertContainsRe(text, "debug_flags = set()")
1669
# test resource under bzrlib
1670
text = osutils.resource_string('bzrlib.ui', 'text.py')
1743
# test resource under breezy
1744
text = osutils.resource_string('breezy.ui', 'text.py')
1671
1745
self.assertContainsRe(text, "class TextUIFactory")
1672
1746
# test unsupported package
1673
1747
self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1675
1749
# test unknown resource
1676
self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1679
class TestReCompile(tests.TestCase):
1681
def test_re_compile_checked(self):
1682
r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1683
self.assertTrue(r.match('aaaa'))
1684
self.assertTrue(r.match('aAaA'))
1686
def test_re_compile_checked_error(self):
1687
# like https://bugs.launchpad.net/bzr/+bug/251352
1688
err = self.assertRaises(
1689
errors.BzrCommandError,
1690
osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1692
"Invalid regular expression in test case: '*': "
1693
"nothing to repeat",
1750
self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
1697
1753
class TestDirReader(tests.TestCaseInTempDir):
1755
scenarios = dir_reader_scenarios()
1699
1757
# Set by load_tests
1700
1758
_dir_reader_class = None
1701
1759
_native_to_unicode = None
1703
1761
def setUp(self):
1704
tests.TestCaseInTempDir.setUp(self)
1762
super(TestDirReader, self).setUp()
1705
1763
self.overrideAttr(osutils,
1706
1764
'_selected_dir_reader', self._dir_reader_class())
1766
1822
name1 = name1u.encode('UTF-8')
1767
1823
name2 = name2u.encode('UTF-8')
1768
1824
expected_dirblocks = [
1770
[(name0, name0, 'file', './' + name0u),
1771
(name1, name1, 'directory', './' + name1u),
1772
(name2, name2, 'file', './' + name2u),
1775
((name1, './' + name1u),
1776
[(name1 + '/' + name0, name0, 'file', './' + name1u
1778
(name1 + '/' + name1, name1, 'directory', './' + name1u
1782
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1826
[(name0, name0, 'file', './' + name0u),
1827
(name1, name1, 'directory', './' + name1u),
1828
(name2, name2, 'file', './' + name2u),
1831
((name1, './' + name1u),
1832
[(name1 + b'/' + name0, name0, 'file', './' + name1u
1834
(name1 + b'/' + name1, name1, 'directory', './' + name1u
1838
((name1 + b'/' + name1, './' + name1u + '/' + name1u),
1787
1843
return tree, expected_dirblocks
1796
1852
dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1798
1854
for line in block:
1799
details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1856
line[0:3] + (self._native_to_unicode(line[4]), ))
1800
1857
filtered_dirblocks.append((dirinfo, details))
1801
1858
return filtered_dirblocks
1803
1860
def test_walk_unicode_tree(self):
1804
self.requireFeature(tests.UnicodeFilenameFeature)
1861
self.requireFeature(features.UnicodeFilenameFeature)
1805
1862
tree, expected_dirblocks = self._get_unicode_tree()
1806
1863
self.build_tree(tree)
1807
1864
result = list(osutils._walkdirs_utf8('.'))
1808
1865
self.assertEqual(expected_dirblocks, self._filter_out(result))
1810
1867
def test_symlink(self):
1811
self.requireFeature(tests.SymlinkFeature)
1812
self.requireFeature(tests.UnicodeFilenameFeature)
1868
self.requireFeature(features.SymlinkFeature)
1869
self.requireFeature(features.UnicodeFilenameFeature)
1813
1870
target = u'target\N{Euro Sign}'
1814
1871
link_name = u'l\N{Euro Sign}nk'
1815
1872
os.symlink(target, link_name)
1816
target_utf8 = target.encode('UTF-8')
1817
1873
link_name_utf8 = link_name.encode('UTF-8')
1818
1874
expected_dirblocks = [
1820
[(link_name_utf8, link_name_utf8,
1821
'symlink', './' + link_name),],
1876
[(link_name_utf8, link_name_utf8,
1877
'symlink', './' + link_name), ],
1823
1879
result = list(osutils._walkdirs_utf8('.'))
1824
1880
self.assertEqual(expected_dirblocks, self._filter_out(result))
1863
1917
self.assertIsInstance(concurrency, int)
1865
1919
def test_local_concurrency_environment_variable(self):
1866
os.environ['BZR_CONCURRENCY'] = '2'
1920
self.overrideEnv('BRZ_CONCURRENCY', '2')
1867
1921
self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1868
os.environ['BZR_CONCURRENCY'] = '3'
1922
self.overrideEnv('BRZ_CONCURRENCY', '3')
1869
1923
self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1870
os.environ['BZR_CONCURRENCY'] = 'foo'
1924
self.overrideEnv('BRZ_CONCURRENCY', 'foo')
1871
1925
self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1873
1927
def test_option_concurrency(self):
1874
os.environ['BZR_CONCURRENCY'] = '1'
1928
self.overrideEnv('BRZ_CONCURRENCY', '1')
1875
1929
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))
1930
# Command line overrides environment variable
1931
self.assertEqual('42', os.environ['BRZ_CONCURRENCY'])
1932
self.assertEqual(42, osutils.local_concurrency(use_cache=False))
1881
1935
class TestFailedToLoadExtension(tests.TestCase):
1883
1937
def _try_loading(self):
1885
import bzrlib._fictional_extension_py
1886
except ImportError, e:
1939
import breezy._fictional_extension_py # noqa: F401
1940
except ImportError as e:
1887
1941
osutils.failed_to_load_extension(e)
1894
1948
def test_failure_to_load(self):
1895
1949
self._try_loading()
1896
1950
self.assertLength(1, osutils._extension_load_failures)
1897
self.assertEquals(osutils._extension_load_failures[0],
1898
"No module named _fictional_extension_py")
1952
osutils._extension_load_failures[0],
1953
"No module named 'breezy._fictional_extension_py'")
1900
1955
def test_report_extension_load_failures_no_warning(self):
1901
1956
self.assertTrue(self._try_loading())
1902
warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1957
warnings, result = self.callCatchWarnings(
1958
osutils.report_extension_load_failures)
1903
1959
# it used to give a Python warning; it no longer does
1904
1960
self.assertLength(0, warnings)
1906
1962
def test_report_extension_load_failures_message(self):
1908
1964
trace.push_log_file(log)
1909
1965
self.assertTrue(self._try_loading())
1910
1966
osutils.report_extension_load_failures()
1911
1967
self.assertContainsRe(
1912
1968
log.getvalue(),
1913
r"bzr: warning: some compiled extensions could not be loaded; "
1914
"see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1969
br"brz: warning: some compiled extensions could not be loaded; "
1970
b"see ``brz help missing-extensions``\n"
1918
1974
class TestTerminalWidth(tests.TestCase):
1977
super(TestTerminalWidth, self).setUp()
1978
self._orig_terminal_size_state = osutils._terminal_size_state
1979
self._orig_first_terminal_size = osutils._first_terminal_size
1980
self.addCleanup(self.restore_osutils_globals)
1981
osutils._terminal_size_state = 'no_data'
1982
osutils._first_terminal_size = None
1984
def restore_osutils_globals(self):
1985
osutils._terminal_size_state = self._orig_terminal_size_state
1986
osutils._first_terminal_size = self._orig_first_terminal_size
1920
1988
def replace_stdout(self, new):
1921
1989
self.overrideAttr(sys, 'stdout', new)
1934
2002
def test_default_values(self):
1935
2003
self.assertEqual(80, osutils.default_terminal_width)
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'
2005
def test_defaults_to_BRZ_COLUMNS(self):
2006
# BRZ_COLUMNS is set by the test framework
2007
self.assertNotEqual('12', os.environ['BRZ_COLUMNS'])
2008
self.overrideEnv('BRZ_COLUMNS', '12')
1941
2009
self.assertEqual(12, osutils.terminal_width())
2011
def test_BRZ_COLUMNS_0_no_limit(self):
2012
self.overrideEnv('BRZ_COLUMNS', '0')
2013
self.assertEqual(None, osutils.terminal_width())
1943
2015
def test_falls_back_to_COLUMNS(self):
1944
del os.environ['BZR_COLUMNS']
2016
self.overrideEnv('BRZ_COLUMNS', None)
1945
2017
self.assertNotEqual('42', os.environ['COLUMNS'])
1946
2018
self.set_fake_tty()
1947
os.environ['COLUMNS'] = '42'
2019
self.overrideEnv('COLUMNS', '42')
1948
2020
self.assertEqual(42, osutils.terminal_width())
1950
2022
def test_tty_default_without_columns(self):
1951
del os.environ['BZR_COLUMNS']
1952
del os.environ['COLUMNS']
2023
self.overrideEnv('BRZ_COLUMNS', None)
2024
self.overrideEnv('COLUMNS', None)
1954
2026
def terminal_size(w, h):
2000
2073
def test_copy_ownership_from_path(self):
2001
2074
"""copy_ownership_from_path test with specified src."""
2003
f = open('test_file', 'wt')
2076
open('test_file', 'wt').close()
2004
2077
osutils.copy_ownership_from_path('test_file', ownsrc)
2006
2079
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)
2080
self.assertEqual(self.path, 'test_file')
2081
self.assertEqual(self.uid, s.st_uid)
2082
self.assertEqual(self.gid, s.st_gid)
2011
2084
def test_copy_ownership_nonesrc(self):
2012
2085
"""copy_ownership_from_path test with src=None."""
2013
f = open('test_file', 'wt')
2086
open('test_file', 'wt').close()
2014
2087
# should use parent dir for permissions
2015
2088
osutils.copy_ownership_from_path('test_file')
2017
2090
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)
2091
self.assertEqual(self.path, 'test_file')
2092
self.assertEqual(self.uid, s.st_uid)
2093
self.assertEqual(self.gid, s.st_gid)
2096
class TestGetHomeDir(tests.TestCase):
2098
def test_is_unicode(self):
2099
home = osutils._get_home_dir()
2100
self.assertIsInstance(home, str)
2102
def test_posix_homeless(self):
2103
self.overrideEnv('HOME', None)
2104
home = osutils._get_home_dir()
2105
self.assertIsInstance(home, str)
2107
def test_posix_home_ascii(self):
2108
self.overrideEnv('HOME', '/home/test')
2109
home = osutils._posix_get_home_dir()
2110
self.assertIsInstance(home, str)
2111
self.assertEqual(u'/home/test', home)
2113
def test_posix_home_unicode(self):
2114
self.requireFeature(features.ByteStringNamedFilesystem)
2115
self.overrideEnv('HOME', '/home/\xa7test')
2116
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2117
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2118
osutils._fs_enc = "iso8859-5"
2119
# In python 3, os.environ returns unicode
2120
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2123
class TestGetuserUnicode(tests.TestCase):
2125
def test_is_unicode(self):
2126
user = osutils.getuser_unicode()
2127
self.assertIsInstance(user, str)
2129
def envvar_to_override(self):
2130
if sys.platform == "win32":
2131
# Disable use of platform calls on windows so envvar is used
2132
self.overrideAttr(win32utils, 'has_ctypes', False)
2133
return 'USERNAME' # only variable used on windows
2134
return 'LOGNAME' # first variable checked by getpass.getuser()
2136
def test_ascii_user(self):
2137
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2138
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2140
def test_unicode_user(self):
2141
ue = osutils.get_user_encoding()
2142
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2144
raise tests.TestSkipped(
2145
'Cannot find a unicode character that works in encoding %s'
2146
% (osutils.get_user_encoding(),))
2147
uni_username = u'jrandom' + uni_val
2148
encoded_username = uni_username.encode(ue)
2149
self.overrideEnv(self.envvar_to_override(), uni_username)
2150
self.assertEqual(uni_username, osutils.getuser_unicode())
2153
class TestBackupNames(tests.TestCase):
2156
super(TestBackupNames, self).setUp()
2159
def backup_exists(self, name):
2160
return name in self.backups
2162
def available_backup_name(self, name):
2163
backup_name = osutils.available_backup_name(name, self.backup_exists)
2164
self.backups.append(backup_name)
2167
def assertBackupName(self, expected, name):
2168
self.assertEqual(expected, self.available_backup_name(name))
2170
def test_empty(self):
2171
self.assertBackupName('file.~1~', 'file')
2173
def test_existing(self):
2174
self.available_backup_name('file')
2175
self.available_backup_name('file')
2176
self.assertBackupName('file.~3~', 'file')
2177
# Empty slots are found, this is not a strict requirement and may be
2178
# revisited if we test against all implementations.
2179
self.backups.remove('file.~2~')
2180
self.assertBackupName('file.~2~', 'file')
2183
class TestFindExecutableInPath(tests.TestCase):
2185
def test_windows(self):
2186
if sys.platform != 'win32':
2187
raise tests.TestSkipped('test requires win32')
2188
self.assertTrue(osutils.find_executable_on_path(
2189
'explorer') is not None)
2191
osutils.find_executable_on_path('explorer.exe') is not None)
2193
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2195
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2196
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2198
def test_windows_app_path(self):
2199
if sys.platform != 'win32':
2200
raise tests.TestSkipped('test requires win32')
2201
# Override PATH env var so that exe can only be found on App Path
2202
self.overrideEnv('PATH', '')
2203
# Internt Explorer is always registered in the App Path
2204
self.assertTrue(osutils.find_executable_on_path(
2205
'iexplore') is not None)
2207
def test_other(self):
2208
if sys.platform == 'win32':
2209
raise tests.TestSkipped('test requires non-win32')
2210
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2212
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2215
class SupportsExecutableTests(tests.TestCaseInTempDir):
2217
def test_returns_bool(self):
2218
self.assertIsInstance(osutils.supports_executable(self.test_dir), bool)
2221
class SupportsSymlinksTests(tests.TestCaseInTempDir):
2223
def test_returns_bool(self):
2224
self.assertIsInstance(osutils.supports_symlinks(self.test_dir), bool)
2227
class MtabReader(tests.TestCaseInTempDir):
2229
def test_read_mtab(self):
2230
self.build_tree_contents([('mtab', """\
2231
/dev/mapper/blah--vg-root / ext4 rw,relatime,errors=remount-ro 0 0
2232
/dev/mapper/blah--vg-home /home vfat rw,relatime 0 0
2238
list(osutils.read_mtab('mtab')),
2240
(b'/home', 'vfat')])
2243
class GetFsTypeTests(tests.TestCaseInTempDir):
2245
def test_returns_string_or_none(self):
2246
ret = osutils.get_fs_type(self.test_dir)
2247
self.assertTrue(isinstance(ret, str) or ret is None)
2249
def test_returns_most_specific(self):
2251
osutils, '_FILESYSTEM_FINDER',
2252
osutils.FilesystemFinder(
2253
[(b'/', 'ext4'), (b'/home', 'vfat'),
2254
(b'/home/jelmer', 'ext2')]))
2255
self.assertEqual(osutils.get_fs_type(b'/home/jelmer/blah'), 'ext2')
2256
self.assertEqual(osutils.get_fs_type('/home/jelmer/blah'), 'ext2')
2257
self.assertEqual(osutils.get_fs_type(b'/home/jelmer'), 'ext2')
2258
self.assertEqual(osutils.get_fs_type(b'/home/martin'), 'vfat')
2259
self.assertEqual(osutils.get_fs_type(b'/home'), 'vfat')
2260
self.assertEqual(osutils.get_fs_type(b'/other'), 'ext4')
2262
def test_returns_none(self):
2264
osutils, '_FILESYSTEM_FINDER',
2265
osutils.FilesystemFinder([]))
2266
self.assertIs(osutils.get_fs_type('/home/jelmer/blah'), None)
2267
self.assertIs(osutils.get_fs_type(b'/home/jelmer/blah'), None)
2268
self.assertIs(osutils.get_fs_type('/home/jelmer'), None)