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)
106
load_tests = load_tests_apply_scenarios
107
109
class TestContainsWhitespace(tests.TestCase):
109
111
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'))
112
self.assertTrue(osutils.contains_whitespace(u' '))
113
self.assertTrue(osutils.contains_whitespace(u'hello there'))
114
self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
115
self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
116
self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
117
self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
117
119
# \xa0 is "Non-breaking-space" which on some python locales thinks it
118
120
# 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'))
121
self.assertFalse(osutils.contains_whitespace(u''))
122
self.assertFalse(osutils.contains_whitespace(u'hellothere'))
123
self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
124
126
class TestRename(tests.TestCaseInTempDir):
137
139
def test_fancy_rename(self):
138
140
# This should work everywhere
139
self.create_file('a', 'something in a\n')
141
self.create_file('a', b'something in a\n')
140
142
self._fancy_rename('a', 'b')
141
self.failIfExists('a')
142
self.failUnlessExists('b')
143
self.check_file_contents('b', 'something in a\n')
143
self.assertPathDoesNotExist('a')
144
self.assertPathExists('b')
145
self.check_file_contents('b', b'something in a\n')
145
self.create_file('a', 'new something in a\n')
147
self.create_file('a', b'new something in a\n')
146
148
self._fancy_rename('b', 'a')
148
self.check_file_contents('a', 'something in a\n')
150
self.check_file_contents('a', b'something in a\n')
150
152
def test_fancy_rename_fails_source_missing(self):
151
153
# An exception should be raised, and the target should be left in place
152
self.create_file('target', 'data in target\n')
154
self.create_file('target', b'data in target\n')
153
155
self.assertRaises((IOError, OSError), self._fancy_rename,
154
156
'missingsource', 'target')
155
self.failUnlessExists('target')
156
self.check_file_contents('target', 'data in target\n')
157
self.assertPathExists('target')
158
self.check_file_contents('target', b'data in target\n')
158
160
def test_fancy_rename_fails_if_source_and_target_missing(self):
159
161
self.assertRaises((IOError, OSError), self._fancy_rename,
418
439
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
442
class TestFdatasync(tests.TestCaseInTempDir):
444
def do_fdatasync(self):
445
f = tempfile.NamedTemporaryFile()
446
osutils.fdatasync(f.fileno())
450
def raise_eopnotsupp(*args, **kwargs):
451
raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
454
def raise_enotsup(*args, **kwargs):
455
raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
457
def test_fdatasync_handles_system_function(self):
458
self.overrideAttr(os, "fdatasync")
461
def test_fdatasync_handles_no_fdatasync_no_fsync(self):
462
self.overrideAttr(os, "fdatasync")
463
self.overrideAttr(os, "fsync")
466
def test_fdatasync_handles_no_EOPNOTSUPP(self):
467
self.overrideAttr(errno, "EOPNOTSUPP")
470
def test_fdatasync_catches_ENOTSUP(self):
471
enotsup = getattr(errno, "ENOTSUP", None)
473
raise tests.TestNotApplicable("No ENOTSUP on this platform")
474
self.overrideAttr(os, "fdatasync", self.raise_enotsup)
477
def test_fdatasync_catches_EOPNOTSUPP(self):
478
enotsup = getattr(errno, "EOPNOTSUPP", None)
480
raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
481
self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
421
485
class TestLinks(tests.TestCaseInTempDir):
423
487
def test_dereference_path(self):
424
self.requireFeature(tests.SymlinkFeature)
488
self.requireFeature(features.SymlinkFeature)
425
489
cwd = osutils.realpath('.')
427
491
bar_path = osutils.pathjoin(cwd, 'bar')
677
740
class TestPumpStringFile(tests.TestCase):
679
742
def test_empty(self):
681
osutils.pump_string_file("", output)
682
self.assertEqual("", output.getvalue())
744
osutils.pump_string_file(b"", output)
745
self.assertEqual(b"", output.getvalue())
684
747
def test_more_than_segment_size(self):
686
osutils.pump_string_file("123456789", output, 2)
687
self.assertEqual("123456789", output.getvalue())
749
osutils.pump_string_file(b"123456789", output, 2)
750
self.assertEqual(b"123456789", output.getvalue())
689
752
def test_segment_size(self):
691
osutils.pump_string_file("12", output, 2)
692
self.assertEqual("12", output.getvalue())
754
osutils.pump_string_file(b"12", output, 2)
755
self.assertEqual(b"12", output.getvalue())
694
757
def test_segment_size_multiple(self):
696
osutils.pump_string_file("1234", output, 2)
697
self.assertEqual("1234", output.getvalue())
759
osutils.pump_string_file(b"1234", output, 2)
760
self.assertEqual(b"1234", output.getvalue())
700
763
class TestRelpath(tests.TestCase):
728
791
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
730
793
def test_from_utf8_string(self):
731
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
794
self.assertEqual(u'foo\xae', osutils.safe_unicode(b'foo\xc2\xae'))
733
796
def test_bad_utf8_string(self):
734
797
self.assertRaises(errors.BzrBadParameterNotUnicode,
735
798
osutils.safe_unicode,
739
802
class TestSafeUtf8(tests.TestCase):
741
804
def test_from_ascii_string(self):
743
self.assertEqual('foobar', osutils.safe_utf8(f))
806
self.assertEqual(b'foobar', osutils.safe_utf8(f))
745
808
def test_from_unicode_string_ascii_contents(self):
746
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
809
self.assertEqual(b'bargam', osutils.safe_utf8(u'bargam'))
748
811
def test_from_unicode_string_unicode_contents(self):
749
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
812
self.assertEqual(b'bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
751
814
def test_from_utf8_string(self):
752
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
815
self.assertEqual(b'foo\xc2\xae', osutils.safe_utf8(b'foo\xc2\xae'))
754
817
def test_bad_utf8_string(self):
755
818
self.assertRaises(errors.BzrBadParameterNotUnicode,
756
osutils.safe_utf8, '\xbb\xbb')
819
osutils.safe_utf8, b'\xbb\xbb')
759
822
class TestSafeRevisionId(tests.TestCase):
761
824
def test_from_ascii_string(self):
762
825
# this shouldn't give a warning because it's getting an ascii string
763
self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
826
self.assertEqual(b'foobar', osutils.safe_revision_id(b'foobar'))
765
828
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'))
829
self.assertRaises(TypeError,
830
osutils.safe_revision_id, u'bargam')
774
832
def test_from_unicode_string_unicode_contents(self):
775
self.assertEqual('bargam\xc2\xae',
776
osutils.safe_revision_id(u'bargam\xae', warn=False))
833
self.assertRaises(TypeError,
834
osutils.safe_revision_id, u'bargam\xae')
778
836
def test_from_utf8_string(self):
779
self.assertEqual('foo\xc2\xae',
780
osutils.safe_revision_id('foo\xc2\xae'))
837
self.assertEqual(b'foo\xc2\xae',
838
osutils.safe_revision_id(b'foo\xc2\xae'))
782
840
def test_none(self):
783
841
"""Currently, None is a valid revision_id"""
787
845
class TestSafeFileId(tests.TestCase):
789
847
def test_from_ascii_string(self):
790
self.assertEqual('foobar', osutils.safe_file_id('foobar'))
848
self.assertEqual(b'foobar', osutils.safe_file_id(b'foobar'))
792
850
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'))
851
self.assertRaises(TypeError, osutils.safe_file_id, u'bargam')
800
853
def test_from_unicode_string_unicode_contents(self):
801
self.assertEqual('bargam\xc2\xae',
802
osutils.safe_file_id(u'bargam\xae', warn=False))
854
self.assertRaises(TypeError,
855
osutils.safe_file_id, u'bargam\xae')
804
857
def test_from_utf8_string(self):
805
self.assertEqual('foo\xc2\xae',
806
osutils.safe_file_id('foo\xc2\xae'))
858
self.assertEqual(b'foo\xc2\xae',
859
osutils.safe_file_id(b'foo\xc2\xae'))
808
861
def test_none(self):
809
862
"""Currently, None is a valid revision_id"""
810
863
self.assertEqual(None, osutils.safe_file_id(None))
866
class TestSendAll(tests.TestCase):
868
def test_send_with_disconnected_socket(self):
869
class DisconnectedSocket(object):
870
def __init__(self, err):
872
def send(self, content):
876
# All of these should be treated as ConnectionReset
878
for err_cls in (IOError, socket.error):
879
for errnum in osutils._end_of_stream_errors:
880
errs.append(err_cls(errnum))
882
sock = DisconnectedSocket(err)
883
self.assertRaises(errors.ConnectionReset,
884
osutils.send_all, sock, b'some more content')
886
def test_send_with_no_progress(self):
887
# See https://bugs.launchpad.net/bzr/+bug/1047309
888
# It seems that paramiko can get into a state where it doesn't error,
889
# but it returns 0 bytes sent for requests over and over again.
890
class NoSendingSocket(object):
893
def send(self, bytes):
895
if self.call_count > 100:
896
# Prevent the test suite from hanging
897
raise RuntimeError('too many calls')
899
sock = NoSendingSocket()
900
self.assertRaises(errors.ConnectionReset,
901
osutils.send_all, sock, b'content')
902
self.assertEqual(1, sock.call_count)
905
class TestPosixFuncs(tests.TestCase):
906
"""Test that the posix version of normpath returns an appropriate path
907
when used with 2 leading slashes."""
909
def test_normpath(self):
910
self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
911
self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
912
self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
813
915
class TestWin32Funcs(tests.TestCase):
814
916
"""Test that _win32 versions of os utilities return appropriate paths."""
816
918
def test_abspath(self):
919
self.requireFeature(features.win32_feature)
817
920
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
818
921
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
819
922
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
908
1001
self.assertFalse('\\' in tmpdir)
910
1003
def test_rename(self):
1004
with open('a', 'wb') as a:
1006
with open('b', 'wb') as b:
918
1009
osutils._win32_rename('b', 'a')
919
self.failUnlessExists('a')
920
self.failIfExists('b')
921
self.assertFileEqual('baz\n', 'a')
1010
self.assertPathExists('a')
1011
self.assertPathDoesNotExist('b')
1012
self.assertFileEqual(b'baz\n', 'a')
923
1014
def test_rename_missing_file(self):
1015
with open('a', 'wb') as a:
929
1019
osutils._win32_rename('b', 'a')
930
except (IOError, OSError), e:
1020
except (IOError, OSError) as e:
931
1021
self.assertEqual(errno.ENOENT, e.errno)
932
self.assertFileEqual('foo\n', 'a')
1022
self.assertFileEqual(b'foo\n', 'a')
934
1024
def test_rename_missing_dir(self):
937
1027
osutils._win32_rename('b', 'a')
938
except (IOError, OSError), e:
1028
except (IOError, OSError) as e:
939
1029
self.assertEqual(errno.ENOENT, e.errno)
941
1031
def test_rename_current_dir(self):
1071
1161
self.assertExpectedBlocks(expected_dirblocks[1:], result)
1073
1163
def test_walkdirs_os_error(self):
1074
# <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1164
# <https://bugs.launchpad.net/bzr/+bug/338653>
1075
1165
# Pyrex readdir didn't raise useful messages if it had an error
1076
1166
# reading the directory
1077
1167
if sys.platform == 'win32':
1078
1168
raise tests.TestNotApplicable(
1079
1169
"readdir IOError not tested on win32")
1170
self.requireFeature(features.not_running_as_root)
1080
1171
os.mkdir("test-unreadable")
1081
1172
os.chmod("test-unreadable", 0000)
1082
1173
# must chmod it back so that it can be removed
1083
self.addCleanup(os.chmod, "test-unreadable", 0700)
1174
self.addCleanup(os.chmod, "test-unreadable", 0o700)
1084
1175
# The error is not raised until the generator is actually evaluated.
1085
1176
# (It would be ok if it happened earlier but at the moment it
1087
1178
e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1088
self.assertEquals('./test-unreadable', e.filename)
1089
self.assertEquals(errno.EACCES, e.errno)
1179
self.assertEqual('./test-unreadable', e.filename)
1180
self.assertEqual(errno.EACCES, e.errno)
1090
1181
# Ensure the message contains the file name
1091
self.assertContainsRe(str(e), "\./test-unreadable")
1182
self.assertContainsRe(str(e), "\\./test-unreadable")
1185
def test_walkdirs_encoding_error(self):
1186
# <https://bugs.launchpad.net/bzr/+bug/488519>
1187
# walkdirs didn't raise a useful message when the filenames
1188
# are not using the filesystem's encoding
1190
# require a bytestring based filesystem
1191
self.requireFeature(features.ByteStringNamedFilesystem)
1202
self.build_tree(tree)
1204
# rename the 1file to a latin-1 filename
1205
os.rename(b"./1file", b"\xe8file")
1206
if b"\xe8file" not in os.listdir("."):
1207
self.skipTest("Lack filesystem that preserves arbitrary bytes")
1209
self._save_platform_info()
1210
osutils._fs_enc = 'UTF-8'
1212
# this should raise on error
1214
for dirdetail, dirblock in osutils.walkdirs(b'.'):
1217
self.assertRaises(errors.BadFilenameEncoding, attempt)
1093
1219
def test__walkdirs_utf8(self):
1154
1283
# Force it to redetect
1155
1284
osutils._selected_dir_reader = None
1156
1285
# Nothing to list, but should still trigger the selection logic
1157
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1286
self.assertEqual([((b'', '.'), [])], list(osutils._walkdirs_utf8('.')))
1158
1287
self.assertIsInstance(osutils._selected_dir_reader, expected)
1160
1289
def test_force_walkdirs_utf8_fs_utf8(self):
1161
1290
self.requireFeature(UTF8DirReaderFeature)
1162
1291
self._save_platform_info()
1163
win32utils.winver = None # Avoid the win32 detection code
1164
osutils._fs_enc = 'UTF-8'
1165
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1292
osutils._fs_enc = 'utf-8'
1293
self.assertDirReaderIs(
1294
UTF8DirReaderFeature.module.UTF8DirReader)
1167
1296
def test_force_walkdirs_utf8_fs_ascii(self):
1168
1297
self.requireFeature(UTF8DirReaderFeature)
1169
1298
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)
1299
osutils._fs_enc = 'ascii'
1300
self.assertDirReaderIs(
1301
UTF8DirReaderFeature.module.UTF8DirReader)
1181
1303
def test_force_walkdirs_utf8_fs_latin1(self):
1182
1304
self._save_platform_info()
1183
win32utils.winver = None # Avoid the win32 detection code
1184
osutils._fs_enc = 'latin1'
1305
osutils._fs_enc = 'iso-8859-1'
1185
1306
self.assertDirReaderIs(osutils.UnicodeDirReader)
1187
1308
def test_force_walkdirs_utf8_nt(self):
1188
1309
# Disabled because the thunk of the whole walkdirs api is disabled.
1189
1310
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1190
1311
self._save_platform_info()
1191
win32utils.winver = 'Windows NT'
1192
from bzrlib._walkdirs_win32 import Win32ReadDir
1312
from .._walkdirs_win32 import Win32ReadDir
1193
1313
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)
1201
1315
def test_unicode_walkdirs(self):
1202
1316
"""Walkdirs should always return unicode paths."""
1203
self.requireFeature(tests.UnicodeFilenameFeature)
1317
self.requireFeature(features.UnicodeFilenameFeature)
1204
1318
name0 = u'0file-\xb6'
1205
1319
name1 = u'1dir-\u062c\u0648'
1206
1320
name2 = u'2file-\u0633'
1260
1374
name2 = name2.encode('utf8')
1262
1376
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),
1378
[(name0, name0, 'file', b'./' + name0),
1379
(name1, name1, 'directory', b'./' + name1),
1380
(name2, name2, 'file', b'./' + name2),
1383
((name1, b'./' + name1),
1384
[(name1 + b'/' + name0, name0, 'file', b'./' + name1
1386
(name1 + b'/' + name1, name1, 'directory', b'./' + name1
1390
((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1282
1396
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1283
1397
# all abspaths are Unicode, and encode them back into utf8.
1284
1398
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1285
self.assertIsInstance(dirdetail[0], str)
1286
if isinstance(dirdetail[1], unicode):
1399
self.assertIsInstance(dirdetail[0], bytes)
1400
if isinstance(dirdetail[1], text_type):
1287
1401
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1288
1402
dirblock = [list(info) for info in dirblock]
1289
1403
for info in dirblock:
1290
self.assertIsInstance(info[4], unicode)
1404
self.assertIsInstance(info[4], text_type)
1291
1405
info[4] = info[4].encode('utf8')
1292
1406
new_dirblock = []
1293
1407
for info in dirblock:
1294
self.assertIsInstance(info[0], str)
1295
self.assertIsInstance(info[1], str)
1296
self.assertIsInstance(info[4], str)
1408
self.assertIsInstance(info[0], bytes)
1409
self.assertIsInstance(info[1], bytes)
1410
self.assertIsInstance(info[4], bytes)
1297
1411
# Remove the stat information
1298
1412
new_dirblock.append((info[0], info[1], info[2], info[4]))
1299
1413
result.append((dirdetail, new_dirblock))
1580
1691
def setUp(self):
1581
1692
super(TestSetUnsetEnv, self).setUp()
1583
self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1694
self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'),
1584
1695
'Environment was not cleaned up properly.'
1585
' Variable BZR_TEST_ENV_VAR should not exist.')
1696
' 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']
1698
if 'BRZ_TEST_ENV_VAR' in os.environ:
1699
del os.environ['BRZ_TEST_ENV_VAR']
1589
1700
self.addCleanup(cleanup)
1591
1702
def test_set(self):
1592
1703
"""Test that we can set an env variable"""
1593
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1704
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1594
1705
self.assertEqual(None, old)
1595
self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1706
self.assertEqual('foo', os.environ.get('BRZ_TEST_ENV_VAR'))
1597
1708
def test_double_set(self):
1598
1709
"""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')
1710
osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1711
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'bar')
1601
1712
self.assertEqual('foo', old)
1602
self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1713
self.assertEqual('bar', os.environ.get('BRZ_TEST_ENV_VAR'))
1604
1715
def test_unicode(self):
1605
1716
"""Environment can only contain plain strings
1612
1723
'Cannot find a unicode character that works in encoding %s'
1613
1724
% (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'))
1726
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', uni_val)
1728
self.assertEqual(uni_val, os.environ.get('BRZ_TEST_ENV_VAR'))
1730
self.assertEqual(env_val, os.environ.get('BRZ_TEST_ENV_VAR'))
1618
1732
def test_unset(self):
1619
1733
"""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)
1734
osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1735
old = osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', None)
1622
1736
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)
1737
self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'))
1738
self.assertNotIn('BRZ_TEST_ENV_VAR', os.environ)
1627
1741
class TestSizeShaFile(tests.TestCaseInTempDir):
1629
1743
def test_sha_empty(self):
1630
self.build_tree_contents([('foo', '')])
1631
expected_sha = osutils.sha_string('')
1744
self.build_tree_contents([('foo', b'')])
1745
expected_sha = osutils.sha_string(b'')
1632
1746
f = open('foo')
1633
1747
self.addCleanup(f.close)
1634
1748
size, sha = osutils.size_sha_file(f)
1663
1777
class TestResourceLoading(tests.TestCaseInTempDir):
1665
1779
def test_resource_string(self):
1666
# test resource in bzrlib
1667
text = osutils.resource_string('bzrlib', 'debug.py')
1780
# test resource in breezy
1781
text = osutils.resource_string('breezy', 'debug.py')
1668
1782
self.assertContainsRe(text, "debug_flags = set()")
1669
# test resource under bzrlib
1670
text = osutils.resource_string('bzrlib.ui', 'text.py')
1783
# test resource under breezy
1784
text = osutils.resource_string('breezy.ui', 'text.py')
1671
1785
self.assertContainsRe(text, "class TextUIFactory")
1672
1786
# test unsupported package
1673
1787
self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1675
1789
# 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",
1790
self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
1697
1793
class TestDirReader(tests.TestCaseInTempDir):
1795
scenarios = dir_reader_scenarios()
1699
1797
# Set by load_tests
1700
1798
_dir_reader_class = None
1701
1799
_native_to_unicode = None
1703
1801
def setUp(self):
1704
tests.TestCaseInTempDir.setUp(self)
1802
super(TestDirReader, self).setUp()
1705
1803
self.overrideAttr(osutils,
1706
1804
'_selected_dir_reader', self._dir_reader_class())
1863
1958
self.assertIsInstance(concurrency, int)
1865
1960
def test_local_concurrency_environment_variable(self):
1866
os.environ['BZR_CONCURRENCY'] = '2'
1961
self.overrideEnv('BRZ_CONCURRENCY', '2')
1867
1962
self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1868
os.environ['BZR_CONCURRENCY'] = '3'
1963
self.overrideEnv('BRZ_CONCURRENCY', '3')
1869
1964
self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1870
os.environ['BZR_CONCURRENCY'] = 'foo'
1965
self.overrideEnv('BRZ_CONCURRENCY', 'foo')
1871
1966
self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1873
1968
def test_option_concurrency(self):
1874
os.environ['BZR_CONCURRENCY'] = '1'
1969
self.overrideEnv('BRZ_CONCURRENCY', '1')
1875
1970
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))
1971
# Command line overrides environment variable
1972
self.assertEqual('42', os.environ['BRZ_CONCURRENCY'])
1973
self.assertEqual(42, osutils.local_concurrency(use_cache=False))
1881
1976
class TestFailedToLoadExtension(tests.TestCase):
1883
1978
def _try_loading(self):
1885
import bzrlib._fictional_extension_py
1886
except ImportError, e:
1980
import breezy._fictional_extension_py
1981
except ImportError as e:
1887
1982
osutils.failed_to_load_extension(e)
1934
2045
def test_default_values(self):
1935
2046
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'
2048
def test_defaults_to_BRZ_COLUMNS(self):
2049
# BRZ_COLUMNS is set by the test framework
2050
self.assertNotEqual('12', os.environ['BRZ_COLUMNS'])
2051
self.overrideEnv('BRZ_COLUMNS', '12')
1941
2052
self.assertEqual(12, osutils.terminal_width())
2054
def test_BRZ_COLUMNS_0_no_limit(self):
2055
self.overrideEnv('BRZ_COLUMNS', '0')
2056
self.assertEqual(None, osutils.terminal_width())
1943
2058
def test_falls_back_to_COLUMNS(self):
1944
del os.environ['BZR_COLUMNS']
2059
self.overrideEnv('BRZ_COLUMNS', None)
1945
2060
self.assertNotEqual('42', os.environ['COLUMNS'])
1946
2061
self.set_fake_tty()
1947
os.environ['COLUMNS'] = '42'
2062
self.overrideEnv('COLUMNS', '42')
1948
2063
self.assertEqual(42, osutils.terminal_width())
1950
2065
def test_tty_default_without_columns(self):
1951
del os.environ['BZR_COLUMNS']
1952
del os.environ['COLUMNS']
2066
self.overrideEnv('BRZ_COLUMNS', None)
2067
self.overrideEnv('COLUMNS', None)
1954
2069
def terminal_size(w, h):
2015
2131
osutils.copy_ownership_from_path('test_file')
2017
2133
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)
2134
self.assertEqual(self.path, 'test_file')
2135
self.assertEqual(self.uid, s.st_uid)
2136
self.assertEqual(self.gid, s.st_gid)
2139
class TestPathFromEnviron(tests.TestCase):
2141
def test_is_unicode(self):
2142
self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
2143
path = osutils.path_from_environ('BRZ_TEST_PATH')
2144
self.assertIsInstance(path, text_type)
2145
self.assertEqual(u'./anywhere at all/', path)
2147
def test_posix_path_env_ascii(self):
2148
self.overrideEnv('BRZ_TEST_PATH', '/tmp')
2149
home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
2150
self.assertIsInstance(home, text_type)
2151
self.assertEqual(u'/tmp', home)
2153
def test_posix_path_env_unicode(self):
2154
self.requireFeature(features.ByteStringNamedFilesystem)
2155
self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
2156
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2157
self.assertEqual(u'/home/\xa7test',
2158
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2159
osutils._fs_enc = "iso8859-5"
2161
# In Python 3, os.environ returns unicode.
2162
self.assertEqual(u'/home/\xa7test',
2163
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2165
self.assertEqual(u'/home/\u0407test',
2166
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2167
osutils._fs_enc = "utf-8"
2168
self.assertRaises(errors.BadFilenameEncoding,
2169
osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
2172
class TestGetHomeDir(tests.TestCase):
2174
def test_is_unicode(self):
2175
home = osutils._get_home_dir()
2176
self.assertIsInstance(home, text_type)
2178
def test_posix_homeless(self):
2179
self.overrideEnv('HOME', None)
2180
home = osutils._get_home_dir()
2181
self.assertIsInstance(home, text_type)
2183
def test_posix_home_ascii(self):
2184
self.overrideEnv('HOME', '/home/test')
2185
home = osutils._posix_get_home_dir()
2186
self.assertIsInstance(home, text_type)
2187
self.assertEqual(u'/home/test', home)
2189
def test_posix_home_unicode(self):
2190
self.requireFeature(features.ByteStringNamedFilesystem)
2191
self.overrideEnv('HOME', '/home/\xa7test')
2192
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2193
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2194
osutils._fs_enc = "iso8859-5"
2196
# In python 3, os.environ returns unicode
2197
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2199
self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
2200
osutils._fs_enc = "utf-8"
2201
self.assertRaises(errors.BadFilenameEncoding,
2202
osutils._posix_get_home_dir)
2205
class TestGetuserUnicode(tests.TestCase):
2207
def test_is_unicode(self):
2208
user = osutils.getuser_unicode()
2209
self.assertIsInstance(user, text_type)
2211
def envvar_to_override(self):
2212
if sys.platform == "win32":
2213
# Disable use of platform calls on windows so envvar is used
2214
self.overrideAttr(win32utils, 'has_ctypes', False)
2215
return 'USERNAME' # only variable used on windows
2216
return 'LOGNAME' # first variable checked by getpass.getuser()
2218
def test_ascii_user(self):
2219
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2220
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2222
def test_unicode_user(self):
2223
ue = osutils.get_user_encoding()
2224
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2226
raise tests.TestSkipped(
2227
'Cannot find a unicode character that works in encoding %s'
2228
% (osutils.get_user_encoding(),))
2229
uni_username = u'jrandom' + uni_val
2230
encoded_username = uni_username.encode(ue)
2232
self.overrideEnv(self.envvar_to_override(), uni_username)
2234
self.overrideEnv(self.envvar_to_override(), encoded_username)
2235
self.assertEqual(uni_username, osutils.getuser_unicode())
2238
class TestBackupNames(tests.TestCase):
2241
super(TestBackupNames, self).setUp()
2244
def backup_exists(self, name):
2245
return name in self.backups
2247
def available_backup_name(self, name):
2248
backup_name = osutils.available_backup_name(name, self.backup_exists)
2249
self.backups.append(backup_name)
2252
def assertBackupName(self, expected, name):
2253
self.assertEqual(expected, self.available_backup_name(name))
2255
def test_empty(self):
2256
self.assertBackupName('file.~1~', 'file')
2258
def test_existing(self):
2259
self.available_backup_name('file')
2260
self.available_backup_name('file')
2261
self.assertBackupName('file.~3~', 'file')
2262
# Empty slots are found, this is not a strict requirement and may be
2263
# revisited if we test against all implementations.
2264
self.backups.remove('file.~2~')
2265
self.assertBackupName('file.~2~', 'file')
2268
class TestFindExecutableInPath(tests.TestCase):
2270
def test_windows(self):
2271
if sys.platform != 'win32':
2272
raise tests.TestSkipped('test requires win32')
2273
self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2275
osutils.find_executable_on_path('explorer.exe') is not None)
2277
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2279
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2280
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2282
def test_windows_app_path(self):
2283
if sys.platform != 'win32':
2284
raise tests.TestSkipped('test requires win32')
2285
# Override PATH env var so that exe can only be found on App Path
2286
self.overrideEnv('PATH', '')
2287
# Internt Explorer is always registered in the App Path
2288
self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2290
def test_other(self):
2291
if sys.platform == 'win32':
2292
raise tests.TestSkipped('test requires non-win32')
2293
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2295
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2298
class TestEnvironmentErrors(tests.TestCase):
2299
"""Test handling of environmental errors"""
2301
def test_is_oserror(self):
2302
self.assertTrue(osutils.is_environment_error(
2303
OSError(errno.EINVAL, "Invalid parameter")))
2305
def test_is_ioerror(self):
2306
self.assertTrue(osutils.is_environment_error(
2307
IOError(errno.EINVAL, "Invalid parameter")))
2309
def test_is_socket_error(self):
2310
self.assertTrue(osutils.is_environment_error(
2311
socket.error(errno.EINVAL, "Invalid parameter")))
2313
def test_is_select_error(self):
2314
self.assertTrue(osutils.is_environment_error(
2315
select.error(errno.EINVAL, "Invalid parameter")))
2317
def test_is_pywintypes_error(self):
2318
self.requireFeature(features.pywintypes)
2320
self.assertTrue(osutils.is_environment_error(
2321
pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))