550
613
self.assertTrue(self.test_data_len > self.block_size)
552
615
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)
618
# read (max // 2) bytes and verify read size wasn't affected
619
num_bytes_to_read = self.block_size // 2
620
osutils.pumpfile(from_file, to_file,
621
num_bytes_to_read, self.block_size)
558
622
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
559
623
self.assertEqual(from_file.get_read_count(), 1)
561
625
# read (max) bytes and verify read size wasn't affected
562
626
num_bytes_to_read = self.block_size
563
627
from_file.reset_read_count()
564
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
628
osutils.pumpfile(from_file, to_file,
629
num_bytes_to_read, self.block_size)
565
630
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
566
631
self.assertEqual(from_file.get_read_count(), 1)
568
633
# read (max + 1) bytes and verify read size was limited
569
634
num_bytes_to_read = self.block_size + 1
570
635
from_file.reset_read_count()
571
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
636
osutils.pumpfile(from_file, to_file,
637
num_bytes_to_read, self.block_size)
572
638
self.assertEqual(from_file.get_max_read_size(), self.block_size)
573
639
self.assertEqual(from_file.get_read_count(), 2)
575
641
# finish reading the rest of the data
576
642
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)
643
osutils.pumpfile(from_file, to_file,
644
num_bytes_to_read, self.block_size)
579
646
# report error if the data wasn't equal (we only report the size due
580
647
# to the length of the data)
665
733
(36, 'write')], activity)
667
735
# And with a limited amount of data
668
from_file = StringIO(self.test_data)
736
from_file = BytesIO(self.test_data)
671
739
osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
672
740
report_activity=log_activity, direction='read')
673
self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
742
[(500, 'read'), (500, 'read'), (28, 'read')], activity)
677
745
class TestPumpStringFile(tests.TestCase):
679
747
def test_empty(self):
681
osutils.pump_string_file("", output)
682
self.assertEqual("", output.getvalue())
749
osutils.pump_string_file(b"", output)
750
self.assertEqual(b"", output.getvalue())
684
752
def test_more_than_segment_size(self):
686
osutils.pump_string_file("123456789", output, 2)
687
self.assertEqual("123456789", output.getvalue())
754
osutils.pump_string_file(b"123456789", output, 2)
755
self.assertEqual(b"123456789", output.getvalue())
689
757
def test_segment_size(self):
691
osutils.pump_string_file("12", output, 2)
692
self.assertEqual("12", output.getvalue())
759
osutils.pump_string_file(b"12", output, 2)
760
self.assertEqual(b"12", output.getvalue())
694
762
def test_segment_size_multiple(self):
696
osutils.pump_string_file("1234", output, 2)
697
self.assertEqual("1234", output.getvalue())
764
osutils.pump_string_file(b"1234", output, 2)
765
self.assertEqual(b"1234", output.getvalue())
700
768
class TestRelpath(tests.TestCase):
728
796
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
730
798
def test_from_utf8_string(self):
731
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
799
self.assertEqual(u'foo\xae', osutils.safe_unicode(b'foo\xc2\xae'))
733
801
def test_bad_utf8_string(self):
734
802
self.assertRaises(errors.BzrBadParameterNotUnicode,
735
803
osutils.safe_unicode,
739
807
class TestSafeUtf8(tests.TestCase):
741
809
def test_from_ascii_string(self):
743
self.assertEqual('foobar', osutils.safe_utf8(f))
811
self.assertEqual(b'foobar', osutils.safe_utf8(f))
745
813
def test_from_unicode_string_ascii_contents(self):
746
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
814
self.assertEqual(b'bargam', osutils.safe_utf8(u'bargam'))
748
816
def test_from_unicode_string_unicode_contents(self):
749
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
817
self.assertEqual(b'bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
751
819
def test_from_utf8_string(self):
752
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
820
self.assertEqual(b'foo\xc2\xae', osutils.safe_utf8(b'foo\xc2\xae'))
754
822
def test_bad_utf8_string(self):
755
823
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))
824
osutils.safe_utf8, b'\xbb\xbb')
827
class TestSendAll(tests.TestCase):
829
def test_send_with_disconnected_socket(self):
830
class DisconnectedSocket(object):
831
def __init__(self, err):
834
def send(self, content):
839
# All of these should be treated as ConnectionReset
841
for err_cls in (IOError, socket.error):
842
for errnum in osutils._end_of_stream_errors:
843
errs.append(err_cls(errnum))
845
sock = DisconnectedSocket(err)
846
self.assertRaises(errors.ConnectionReset,
847
osutils.send_all, sock, b'some more content')
849
def test_send_with_no_progress(self):
850
# See https://bugs.launchpad.net/bzr/+bug/1047309
851
# It seems that paramiko can get into a state where it doesn't error,
852
# but it returns 0 bytes sent for requests over and over again.
853
class NoSendingSocket(object):
857
def send(self, bytes):
859
if self.call_count > 100:
860
# Prevent the test suite from hanging
861
raise RuntimeError('too many calls')
863
sock = NoSendingSocket()
864
self.assertRaises(errors.ConnectionReset,
865
osutils.send_all, sock, b'content')
866
self.assertEqual(1, sock.call_count)
869
class TestPosixFuncs(tests.TestCase):
870
"""Test that the posix version of normpath returns an appropriate path
871
when used with 2 leading slashes."""
873
def test_normpath(self):
874
self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
876
'/etc/shadow', osutils._posix_normpath('//etc/shadow'))
878
'/etc/shadow', osutils._posix_normpath('///etc/shadow'))
813
881
class TestWin32Funcs(tests.TestCase):
814
882
"""Test that _win32 versions of os utilities return appropriate paths."""
816
884
def test_abspath(self):
885
self.requireFeature(features.win32_feature)
817
886
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
818
887
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
819
888
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
892
951
def test_minimum_path_selection(self):
893
952
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']))
953
osutils.minimum_path_selection([]))
954
self.assertEqual({'a'},
955
osutils.minimum_path_selection(['a']))
956
self.assertEqual({'a', 'b'},
957
osutils.minimum_path_selection(['a', 'b']))
958
self.assertEqual({'a/', 'b'},
959
osutils.minimum_path_selection(['a/', 'b']))
960
self.assertEqual({'a/', 'b'},
961
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
962
self.assertEqual({'a-b', 'a', 'a0b'},
963
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
906
965
def test_mkdtemp(self):
907
966
tmpdir = osutils._win32_mkdtemp(dir='.')
908
967
self.assertFalse('\\' in tmpdir)
910
969
def test_rename(self):
970
with open('a', 'wb') as a:
972
with open('b', 'wb') as b:
918
975
osutils._win32_rename('b', 'a')
919
self.failUnlessExists('a')
920
self.failIfExists('b')
921
self.assertFileEqual('baz\n', 'a')
976
self.assertPathExists('a')
977
self.assertPathDoesNotExist('b')
978
self.assertFileEqual(b'baz\n', 'a')
923
980
def test_rename_missing_file(self):
981
with open('a', 'wb') as a:
929
985
osutils._win32_rename('b', 'a')
930
except (IOError, OSError), e:
986
except (IOError, OSError) as e:
931
987
self.assertEqual(errno.ENOENT, e.errno)
932
self.assertFileEqual('foo\n', 'a')
988
self.assertFileEqual(b'foo\n', 'a')
934
990
def test_rename_missing_dir(self):
937
993
osutils._win32_rename('b', 'a')
938
except (IOError, OSError), e:
994
except (IOError, OSError) as e:
939
995
self.assertEqual(errno.ENOENT, e.errno)
941
997
def test_rename_current_dir(self):
1071
1130
self.assertExpectedBlocks(expected_dirblocks[1:], result)
1073
1132
def test_walkdirs_os_error(self):
1074
# <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1133
# <https://bugs.launchpad.net/bzr/+bug/338653>
1075
1134
# Pyrex readdir didn't raise useful messages if it had an error
1076
1135
# reading the directory
1077
1136
if sys.platform == 'win32':
1078
1137
raise tests.TestNotApplicable(
1079
1138
"readdir IOError not tested on win32")
1139
self.requireFeature(features.not_running_as_root)
1080
1140
os.mkdir("test-unreadable")
1081
1141
os.chmod("test-unreadable", 0000)
1082
1142
# must chmod it back so that it can be removed
1083
self.addCleanup(os.chmod, "test-unreadable", 0700)
1143
self.addCleanup(os.chmod, "test-unreadable", 0o700)
1084
1144
# The error is not raised until the generator is actually evaluated.
1085
1145
# (It would be ok if it happened earlier but at the moment it
1087
1147
e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1088
self.assertEquals('./test-unreadable', e.filename)
1089
self.assertEquals(errno.EACCES, e.errno)
1148
self.assertEqual('./test-unreadable', osutils.safe_unicode(e.filename))
1149
self.assertEqual(errno.EACCES, e.errno)
1090
1150
# Ensure the message contains the file name
1091
self.assertContainsRe(str(e), "\./test-unreadable")
1151
self.assertContainsRe(str(e), "\\./test-unreadable")
1153
def test_walkdirs_encoding_error(self):
1154
# <https://bugs.launchpad.net/bzr/+bug/488519>
1155
# walkdirs didn't raise a useful message when the filenames
1156
# are not using the filesystem's encoding
1158
# require a bytestring based filesystem
1159
self.requireFeature(features.ByteStringNamedFilesystem)
1170
self.build_tree(tree)
1172
# rename the 1file to a latin-1 filename
1173
os.rename(b"./1file", b"\xe8file")
1174
if b"\xe8file" not in os.listdir("."):
1175
self.skipTest("Lack filesystem that preserves arbitrary bytes")
1177
self._save_platform_info()
1178
osutils._fs_enc = 'UTF-8'
1180
# this should raise on error
1182
for dirdetail, dirblock in osutils.walkdirs(b'.'):
1185
self.assertRaises(errors.BadFilenameEncoding, attempt)
1093
1187
def test__walkdirs_utf8(self):
1145
1244
dirblock[:] = new_dirblock
1147
1246
def _save_platform_info(self):
1148
self.overrideAttr(win32utils, 'winver')
1149
1247
self.overrideAttr(osutils, '_fs_enc')
1150
1248
self.overrideAttr(osutils, '_selected_dir_reader')
1152
def assertDirReaderIs(self, expected):
1250
def assertDirReaderIs(self, expected, top):
1153
1251
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
1154
1252
# Force it to redetect
1155
1253
osutils._selected_dir_reader = None
1156
1254
# Nothing to list, but should still trigger the selection logic
1157
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1255
self.assertEqual([((b'', top), [])], list(osutils._walkdirs_utf8('.')))
1158
1256
self.assertIsInstance(osutils._selected_dir_reader, expected)
1160
1258
def test_force_walkdirs_utf8_fs_utf8(self):
1161
1259
self.requireFeature(UTF8DirReaderFeature)
1162
1260
self._save_platform_info()
1163
win32utils.winver = None # Avoid the win32 detection code
1164
osutils._fs_enc = 'UTF-8'
1165
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1261
osutils._fs_enc = 'utf-8'
1262
self.assertDirReaderIs(UTF8DirReaderFeature.module.UTF8DirReader, b".")
1167
1264
def test_force_walkdirs_utf8_fs_ascii(self):
1168
1265
self.requireFeature(UTF8DirReaderFeature)
1169
1266
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)
1267
osutils._fs_enc = 'ascii'
1268
self.assertDirReaderIs(
1269
UTF8DirReaderFeature.module.UTF8DirReader, b".")
1181
1271
def test_force_walkdirs_utf8_fs_latin1(self):
1182
1272
self._save_platform_info()
1183
win32utils.winver = None # Avoid the win32 detection code
1184
osutils._fs_enc = 'latin1'
1185
self.assertDirReaderIs(osutils.UnicodeDirReader)
1273
osutils._fs_enc = 'iso-8859-1'
1274
self.assertDirReaderIs(osutils.UnicodeDirReader, ".")
1187
1276
def test_force_walkdirs_utf8_nt(self):
1188
1277
# Disabled because the thunk of the whole walkdirs api is disabled.
1189
1278
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1190
1279
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)
1280
from .._walkdirs_win32 import Win32ReadDir
1281
self.assertDirReaderIs(Win32ReadDir, ".")
1201
1283
def test_unicode_walkdirs(self):
1202
1284
"""Walkdirs should always return unicode paths."""
1203
self.requireFeature(tests.UnicodeFilenameFeature)
1285
self.requireFeature(features.UnicodeFilenameFeature)
1204
1286
name0 = u'0file-\xb6'
1205
1287
name1 = u'1dir-\u062c\u0648'
1206
1288
name2 = u'2file-\u0633'
1260
1342
name2 = name2.encode('utf8')
1262
1344
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),
1346
[(name0, name0, 'file', b'./' + name0),
1347
(name1, name1, 'directory', b'./' + name1),
1348
(name2, name2, 'file', b'./' + name2),
1351
((name1, b'./' + name1),
1352
[(name1 + b'/' + name0, name0, 'file', b'./' + name1
1354
(name1 + b'/' + name1, name1, 'directory', b'./' + name1
1358
((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1282
1364
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1283
1365
# all abspaths are Unicode, and encode them back into utf8.
1284
1366
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1285
self.assertIsInstance(dirdetail[0], str)
1286
if isinstance(dirdetail[1], unicode):
1367
self.assertIsInstance(dirdetail[0], bytes)
1368
if isinstance(dirdetail[1], text_type):
1287
1369
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1288
1370
dirblock = [list(info) for info in dirblock]
1289
1371
for info in dirblock:
1290
self.assertIsInstance(info[4], unicode)
1372
self.assertIsInstance(info[4], text_type)
1291
1373
info[4] = info[4].encode('utf8')
1292
1374
new_dirblock = []
1293
1375
for info in dirblock:
1294
self.assertIsInstance(info[0], str)
1295
self.assertIsInstance(info[1], str)
1296
self.assertIsInstance(info[4], str)
1376
self.assertIsInstance(info[0], bytes)
1377
self.assertIsInstance(info[1], bytes)
1378
self.assertIsInstance(info[4], bytes)
1297
1379
# Remove the stat information
1298
1380
new_dirblock.append((info[0], info[1], info[2], info[4]))
1299
1381
result.append((dirdetail, new_dirblock))
2000
2089
def test_copy_ownership_from_path(self):
2001
2090
"""copy_ownership_from_path test with specified src."""
2003
f = open('test_file', 'wt')
2092
open('test_file', 'wt').close()
2004
2093
osutils.copy_ownership_from_path('test_file', ownsrc)
2006
2095
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)
2096
self.assertEqual(self.path, 'test_file')
2097
self.assertEqual(self.uid, s.st_uid)
2098
self.assertEqual(self.gid, s.st_gid)
2011
2100
def test_copy_ownership_nonesrc(self):
2012
2101
"""copy_ownership_from_path test with src=None."""
2013
f = open('test_file', 'wt')
2102
open('test_file', 'wt').close()
2014
2103
# should use parent dir for permissions
2015
2104
osutils.copy_ownership_from_path('test_file')
2017
2106
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)
2107
self.assertEqual(self.path, 'test_file')
2108
self.assertEqual(self.uid, s.st_uid)
2109
self.assertEqual(self.gid, s.st_gid)
2112
class TestPathFromEnviron(tests.TestCase):
2114
def test_is_unicode(self):
2115
self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
2116
path = osutils.path_from_environ('BRZ_TEST_PATH')
2117
self.assertIsInstance(path, text_type)
2118
self.assertEqual(u'./anywhere at all/', path)
2120
def test_posix_path_env_ascii(self):
2121
self.overrideEnv('BRZ_TEST_PATH', '/tmp')
2122
home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
2123
self.assertIsInstance(home, text_type)
2124
self.assertEqual(u'/tmp', home)
2126
def test_posix_path_env_unicode(self):
2127
self.requireFeature(features.ByteStringNamedFilesystem)
2128
self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
2129
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2130
self.assertEqual(u'/home/\xa7test',
2131
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2132
osutils._fs_enc = "iso8859-5"
2134
# In Python 3, os.environ returns unicode.
2135
self.assertEqual(u'/home/\xa7test',
2136
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2138
self.assertEqual(u'/home/\u0407test',
2139
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2140
osutils._fs_enc = "utf-8"
2142
errors.BadFilenameEncoding,
2143
osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
2146
class TestGetHomeDir(tests.TestCase):
2148
def test_is_unicode(self):
2149
home = osutils._get_home_dir()
2150
self.assertIsInstance(home, text_type)
2152
def test_posix_homeless(self):
2153
self.overrideEnv('HOME', None)
2154
home = osutils._get_home_dir()
2155
self.assertIsInstance(home, text_type)
2157
def test_posix_home_ascii(self):
2158
self.overrideEnv('HOME', '/home/test')
2159
home = osutils._posix_get_home_dir()
2160
self.assertIsInstance(home, text_type)
2161
self.assertEqual(u'/home/test', home)
2163
def test_posix_home_unicode(self):
2164
self.requireFeature(features.ByteStringNamedFilesystem)
2165
self.overrideEnv('HOME', '/home/\xa7test')
2166
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2167
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2168
osutils._fs_enc = "iso8859-5"
2170
# In python 3, os.environ returns unicode
2171
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2173
self.assertEqual(u'/home/\u0407test',
2174
osutils._posix_get_home_dir())
2175
osutils._fs_enc = "utf-8"
2176
self.assertRaises(errors.BadFilenameEncoding,
2177
osutils._posix_get_home_dir)
2180
class TestGetuserUnicode(tests.TestCase):
2182
def test_is_unicode(self):
2183
user = osutils.getuser_unicode()
2184
self.assertIsInstance(user, text_type)
2186
def envvar_to_override(self):
2187
if sys.platform == "win32":
2188
# Disable use of platform calls on windows so envvar is used
2189
self.overrideAttr(win32utils, 'has_ctypes', False)
2190
return 'USERNAME' # only variable used on windows
2191
return 'LOGNAME' # first variable checked by getpass.getuser()
2193
def test_ascii_user(self):
2194
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2195
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2197
def test_unicode_user(self):
2198
ue = osutils.get_user_encoding()
2199
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2201
raise tests.TestSkipped(
2202
'Cannot find a unicode character that works in encoding %s'
2203
% (osutils.get_user_encoding(),))
2204
uni_username = u'jrandom' + uni_val
2205
encoded_username = uni_username.encode(ue)
2207
self.overrideEnv(self.envvar_to_override(), uni_username)
2209
self.overrideEnv(self.envvar_to_override(), encoded_username)
2210
self.assertEqual(uni_username, osutils.getuser_unicode())
2213
class TestBackupNames(tests.TestCase):
2216
super(TestBackupNames, self).setUp()
2219
def backup_exists(self, name):
2220
return name in self.backups
2222
def available_backup_name(self, name):
2223
backup_name = osutils.available_backup_name(name, self.backup_exists)
2224
self.backups.append(backup_name)
2227
def assertBackupName(self, expected, name):
2228
self.assertEqual(expected, self.available_backup_name(name))
2230
def test_empty(self):
2231
self.assertBackupName('file.~1~', 'file')
2233
def test_existing(self):
2234
self.available_backup_name('file')
2235
self.available_backup_name('file')
2236
self.assertBackupName('file.~3~', 'file')
2237
# Empty slots are found, this is not a strict requirement and may be
2238
# revisited if we test against all implementations.
2239
self.backups.remove('file.~2~')
2240
self.assertBackupName('file.~2~', 'file')
2243
class TestFindExecutableInPath(tests.TestCase):
2245
def test_windows(self):
2246
if sys.platform != 'win32':
2247
raise tests.TestSkipped('test requires win32')
2248
self.assertTrue(osutils.find_executable_on_path(
2249
'explorer') is not None)
2251
osutils.find_executable_on_path('explorer.exe') is not None)
2253
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2255
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2256
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2258
def test_windows_app_path(self):
2259
if sys.platform != 'win32':
2260
raise tests.TestSkipped('test requires win32')
2261
# Override PATH env var so that exe can only be found on App Path
2262
self.overrideEnv('PATH', '')
2263
# Internt Explorer is always registered in the App Path
2264
self.assertTrue(osutils.find_executable_on_path(
2265
'iexplore') is not None)
2267
def test_other(self):
2268
if sys.platform == 'win32':
2269
raise tests.TestSkipped('test requires non-win32')
2270
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2272
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2275
class TestEnvironmentErrors(tests.TestCase):
2276
"""Test handling of environmental errors"""
2278
def test_is_oserror(self):
2279
self.assertTrue(osutils.is_environment_error(
2280
OSError(errno.EINVAL, "Invalid parameter")))
2282
def test_is_ioerror(self):
2283
self.assertTrue(osutils.is_environment_error(
2284
IOError(errno.EINVAL, "Invalid parameter")))
2286
def test_is_socket_error(self):
2287
self.assertTrue(osutils.is_environment_error(
2288
socket.error(errno.EINVAL, "Invalid parameter")))
2290
def test_is_select_error(self):
2291
self.assertTrue(osutils.is_environment_error(
2292
select.error(errno.EINVAL, "Invalid parameter")))
2294
def test_is_pywintypes_error(self):
2295
self.requireFeature(features.pywintypes)
2297
self.assertTrue(osutils.is_environment_error(
2298
pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))
2301
class SupportsExecutableTests(tests.TestCaseInTempDir):
2303
def test_returns_bool(self):
2304
self.assertIsInstance(osutils.supports_executable(self.test_dir), bool)
2307
class SupportsSymlinksTests(tests.TestCaseInTempDir):
2309
def test_returns_bool(self):
2310
self.assertIsInstance(osutils.supports_symlinks(self.test_dir), bool)
2313
class MtabReader(tests.TestCaseInTempDir):
2315
def test_read_mtab(self):
2316
self.build_tree_contents([('mtab', """\
2317
/dev/mapper/blah--vg-root / ext4 rw,relatime,errors=remount-ro 0 0
2318
/dev/mapper/blah--vg-home /home vfat rw,relatime 0 0
2324
list(osutils.read_mtab('mtab')),
2326
(b'/home', 'vfat')])
2329
class GetFsTypeTests(tests.TestCaseInTempDir):
2331
def test_returns_string_or_none(self):
2332
ret = osutils.get_fs_type(self.test_dir)
2333
self.assertTrue(isinstance(ret, text_type) or ret is None)
2335
def test_returns_most_specific(self):
2337
osutils, '_FILESYSTEM_FINDER',
2338
osutils.FilesystemFinder(
2339
[(b'/', 'ext4'), (b'/home', 'vfat'),
2340
(b'/home/jelmer', 'ext2')]))
2341
self.assertEqual(osutils.get_fs_type(b'/home/jelmer/blah'), 'ext2')
2342
self.assertEqual(osutils.get_fs_type('/home/jelmer/blah'), 'ext2')
2343
self.assertEqual(osutils.get_fs_type(b'/home/jelmer'), 'ext2')
2344
self.assertEqual(osutils.get_fs_type(b'/home/martin'), 'vfat')
2345
self.assertEqual(osutils.get_fs_type(b'/home'), 'vfat')
2346
self.assertEqual(osutils.get_fs_type(b'/other'), 'ext4')
2348
def test_returns_none(self):
2350
osutils, '_FILESYSTEM_FINDER',
2351
osutils.FilesystemFinder([]))
2352
self.assertIs(osutils.get_fs_type('/home/jelmer/blah'), None)
2353
self.assertIs(osutils.get_fs_type(b'/home/jelmer/blah'), None)
2354
self.assertIs(osutils.get_fs_type('/home/jelmer'), None)