550
615
self.assertTrue(self.test_data_len > self.block_size)
552
617
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)
620
# read (max // 2) bytes and verify read size wasn't affected
621
num_bytes_to_read = self.block_size // 2
622
osutils.pumpfile(from_file, to_file,
623
num_bytes_to_read, self.block_size)
558
624
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
559
625
self.assertEqual(from_file.get_read_count(), 1)
561
627
# read (max) bytes and verify read size wasn't affected
562
628
num_bytes_to_read = self.block_size
563
629
from_file.reset_read_count()
564
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)
565
632
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
566
633
self.assertEqual(from_file.get_read_count(), 1)
568
635
# read (max + 1) bytes and verify read size was limited
569
636
num_bytes_to_read = self.block_size + 1
570
637
from_file.reset_read_count()
571
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
638
osutils.pumpfile(from_file, to_file,
639
num_bytes_to_read, self.block_size)
572
640
self.assertEqual(from_file.get_max_read_size(), self.block_size)
573
641
self.assertEqual(from_file.get_read_count(), 2)
575
643
# finish reading the rest of the data
576
644
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)
645
osutils.pumpfile(from_file, to_file,
646
num_bytes_to_read, self.block_size)
579
648
# report error if the data wasn't equal (we only report the size due
580
649
# to the length of the data)
665
735
(36, 'write')], activity)
667
737
# And with a limited amount of data
668
from_file = StringIO(self.test_data)
738
from_file = BytesIO(self.test_data)
671
741
osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
672
742
report_activity=log_activity, direction='read')
673
self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
744
[(500, 'read'), (500, 'read'), (28, 'read')], activity)
677
747
class TestPumpStringFile(tests.TestCase):
679
749
def test_empty(self):
681
osutils.pump_string_file("", output)
682
self.assertEqual("", output.getvalue())
751
osutils.pump_string_file(b"", output)
752
self.assertEqual(b"", output.getvalue())
684
754
def test_more_than_segment_size(self):
686
osutils.pump_string_file("123456789", output, 2)
687
self.assertEqual("123456789", output.getvalue())
756
osutils.pump_string_file(b"123456789", output, 2)
757
self.assertEqual(b"123456789", output.getvalue())
689
759
def test_segment_size(self):
691
osutils.pump_string_file("12", output, 2)
692
self.assertEqual("12", output.getvalue())
761
osutils.pump_string_file(b"12", output, 2)
762
self.assertEqual(b"12", output.getvalue())
694
764
def test_segment_size_multiple(self):
696
osutils.pump_string_file("1234", output, 2)
697
self.assertEqual("1234", output.getvalue())
766
osutils.pump_string_file(b"1234", output, 2)
767
self.assertEqual(b"1234", output.getvalue())
700
770
class TestRelpath(tests.TestCase):
728
798
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
730
800
def test_from_utf8_string(self):
731
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
801
self.assertEqual(u'foo\xae', osutils.safe_unicode(b'foo\xc2\xae'))
733
803
def test_bad_utf8_string(self):
734
804
self.assertRaises(errors.BzrBadParameterNotUnicode,
735
805
osutils.safe_unicode,
739
809
class TestSafeUtf8(tests.TestCase):
741
811
def test_from_ascii_string(self):
743
self.assertEqual('foobar', osutils.safe_utf8(f))
813
self.assertEqual(b'foobar', osutils.safe_utf8(f))
745
815
def test_from_unicode_string_ascii_contents(self):
746
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
816
self.assertEqual(b'bargam', osutils.safe_utf8(u'bargam'))
748
818
def test_from_unicode_string_unicode_contents(self):
749
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
819
self.assertEqual(b'bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
751
821
def test_from_utf8_string(self):
752
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
822
self.assertEqual(b'foo\xc2\xae', osutils.safe_utf8(b'foo\xc2\xae'))
754
824
def test_bad_utf8_string(self):
755
825
self.assertRaises(errors.BzrBadParameterNotUnicode,
756
osutils.safe_utf8, '\xbb\xbb')
826
osutils.safe_utf8, b'\xbb\xbb')
759
829
class TestSafeRevisionId(tests.TestCase):
761
831
def test_from_ascii_string(self):
762
832
# this shouldn't give a warning because it's getting an ascii string
763
self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
833
self.assertEqual(b'foobar', osutils.safe_revision_id(b'foobar'))
765
835
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'))
836
self.assertRaises(TypeError,
837
osutils.safe_revision_id, u'bargam')
774
839
def test_from_unicode_string_unicode_contents(self):
775
self.assertEqual('bargam\xc2\xae',
776
osutils.safe_revision_id(u'bargam\xae', warn=False))
840
self.assertRaises(TypeError,
841
osutils.safe_revision_id, u'bargam\xae')
778
843
def test_from_utf8_string(self):
779
self.assertEqual('foo\xc2\xae',
780
osutils.safe_revision_id('foo\xc2\xae'))
844
self.assertEqual(b'foo\xc2\xae',
845
osutils.safe_revision_id(b'foo\xc2\xae'))
782
847
def test_none(self):
783
848
"""Currently, None is a valid revision_id"""
787
852
class TestSafeFileId(tests.TestCase):
789
854
def test_from_ascii_string(self):
790
self.assertEqual('foobar', osutils.safe_file_id('foobar'))
855
self.assertEqual(b'foobar', osutils.safe_file_id(b'foobar'))
792
857
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'))
858
self.assertRaises(TypeError, osutils.safe_file_id, u'bargam')
800
860
def test_from_unicode_string_unicode_contents(self):
801
self.assertEqual('bargam\xc2\xae',
802
osutils.safe_file_id(u'bargam\xae', warn=False))
861
self.assertRaises(TypeError,
862
osutils.safe_file_id, u'bargam\xae')
804
864
def test_from_utf8_string(self):
805
self.assertEqual('foo\xc2\xae',
806
osutils.safe_file_id('foo\xc2\xae'))
865
self.assertEqual(b'foo\xc2\xae',
866
osutils.safe_file_id(b'foo\xc2\xae'))
808
868
def test_none(self):
809
869
"""Currently, None is a valid revision_id"""
810
870
self.assertEqual(None, osutils.safe_file_id(None))
873
class TestSendAll(tests.TestCase):
875
def test_send_with_disconnected_socket(self):
876
class DisconnectedSocket(object):
877
def __init__(self, err):
880
def send(self, content):
885
# All of these should be treated as ConnectionReset
887
for err_cls in (IOError, socket.error):
888
for errnum in osutils._end_of_stream_errors:
889
errs.append(err_cls(errnum))
891
sock = DisconnectedSocket(err)
892
self.assertRaises(errors.ConnectionReset,
893
osutils.send_all, sock, b'some more content')
895
def test_send_with_no_progress(self):
896
# See https://bugs.launchpad.net/bzr/+bug/1047309
897
# It seems that paramiko can get into a state where it doesn't error,
898
# but it returns 0 bytes sent for requests over and over again.
899
class NoSendingSocket(object):
903
def send(self, bytes):
905
if self.call_count > 100:
906
# Prevent the test suite from hanging
907
raise RuntimeError('too many calls')
909
sock = NoSendingSocket()
910
self.assertRaises(errors.ConnectionReset,
911
osutils.send_all, sock, b'content')
912
self.assertEqual(1, sock.call_count)
915
class TestPosixFuncs(tests.TestCase):
916
"""Test that the posix version of normpath returns an appropriate path
917
when used with 2 leading slashes."""
919
def test_normpath(self):
920
self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
922
'/etc/shadow', osutils._posix_normpath('//etc/shadow'))
924
'/etc/shadow', osutils._posix_normpath('///etc/shadow'))
813
927
class TestWin32Funcs(tests.TestCase):
814
928
"""Test that _win32 versions of os utilities return appropriate paths."""
816
930
def test_abspath(self):
931
self.requireFeature(features.win32_feature)
817
932
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
818
933
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
819
934
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
892
997
def test_minimum_path_selection(self):
893
998
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']))
999
osutils.minimum_path_selection([]))
1000
self.assertEqual({'a'},
1001
osutils.minimum_path_selection(['a']))
1002
self.assertEqual({'a', 'b'},
1003
osutils.minimum_path_selection(['a', 'b']))
1004
self.assertEqual({'a/', 'b'},
1005
osutils.minimum_path_selection(['a/', 'b']))
1006
self.assertEqual({'a/', 'b'},
1007
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
1008
self.assertEqual({'a-b', 'a', 'a0b'},
1009
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
906
1011
def test_mkdtemp(self):
907
1012
tmpdir = osutils._win32_mkdtemp(dir='.')
908
1013
self.assertFalse('\\' in tmpdir)
910
1015
def test_rename(self):
1016
with open('a', 'wb') as a:
1018
with open('b', 'wb') as b:
918
1021
osutils._win32_rename('b', 'a')
919
self.failUnlessExists('a')
920
self.failIfExists('b')
921
self.assertFileEqual('baz\n', 'a')
1022
self.assertPathExists('a')
1023
self.assertPathDoesNotExist('b')
1024
self.assertFileEqual(b'baz\n', 'a')
923
1026
def test_rename_missing_file(self):
1027
with open('a', 'wb') as a:
929
1031
osutils._win32_rename('b', 'a')
930
except (IOError, OSError), e:
1032
except (IOError, OSError) as e:
931
1033
self.assertEqual(errno.ENOENT, e.errno)
932
self.assertFileEqual('foo\n', 'a')
1034
self.assertFileEqual(b'foo\n', 'a')
934
1036
def test_rename_missing_dir(self):
937
1039
osutils._win32_rename('b', 'a')
938
except (IOError, OSError), e:
1040
except (IOError, OSError) as e:
939
1041
self.assertEqual(errno.ENOENT, e.errno)
941
1043
def test_rename_current_dir(self):
1071
1176
self.assertExpectedBlocks(expected_dirblocks[1:], result)
1073
1178
def test_walkdirs_os_error(self):
1074
# <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1179
# <https://bugs.launchpad.net/bzr/+bug/338653>
1075
1180
# Pyrex readdir didn't raise useful messages if it had an error
1076
1181
# reading the directory
1077
1182
if sys.platform == 'win32':
1078
1183
raise tests.TestNotApplicable(
1079
1184
"readdir IOError not tested on win32")
1185
self.requireFeature(features.not_running_as_root)
1080
1186
os.mkdir("test-unreadable")
1081
1187
os.chmod("test-unreadable", 0000)
1082
1188
# must chmod it back so that it can be removed
1083
self.addCleanup(os.chmod, "test-unreadable", 0700)
1189
self.addCleanup(os.chmod, "test-unreadable", 0o700)
1084
1190
# The error is not raised until the generator is actually evaluated.
1085
1191
# (It would be ok if it happened earlier but at the moment it
1087
1193
e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1088
self.assertEquals('./test-unreadable', e.filename)
1089
self.assertEquals(errno.EACCES, e.errno)
1194
self.assertEqual('./test-unreadable', osutils.safe_unicode(e.filename))
1195
self.assertEqual(errno.EACCES, e.errno)
1090
1196
# Ensure the message contains the file name
1091
self.assertContainsRe(str(e), "\./test-unreadable")
1197
self.assertContainsRe(str(e), "\\./test-unreadable")
1199
def test_walkdirs_encoding_error(self):
1200
# <https://bugs.launchpad.net/bzr/+bug/488519>
1201
# walkdirs didn't raise a useful message when the filenames
1202
# are not using the filesystem's encoding
1204
# require a bytestring based filesystem
1205
self.requireFeature(features.ByteStringNamedFilesystem)
1216
self.build_tree(tree)
1218
# rename the 1file to a latin-1 filename
1219
os.rename(b"./1file", b"\xe8file")
1220
if b"\xe8file" not in os.listdir("."):
1221
self.skipTest("Lack filesystem that preserves arbitrary bytes")
1223
self._save_platform_info()
1224
osutils._fs_enc = 'UTF-8'
1226
# this should raise on error
1228
for dirdetail, dirblock in osutils.walkdirs(b'.'):
1231
self.assertRaises(errors.BadFilenameEncoding, attempt)
1093
1233
def test__walkdirs_utf8(self):
1145
1290
dirblock[:] = new_dirblock
1147
1292
def _save_platform_info(self):
1148
self.overrideAttr(win32utils, 'winver')
1149
1293
self.overrideAttr(osutils, '_fs_enc')
1150
1294
self.overrideAttr(osutils, '_selected_dir_reader')
1152
def assertDirReaderIs(self, expected):
1296
def assertDirReaderIs(self, expected, top):
1153
1297
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
1154
1298
# Force it to redetect
1155
1299
osutils._selected_dir_reader = None
1156
1300
# Nothing to list, but should still trigger the selection logic
1157
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1301
self.assertEqual([((b'', top), [])], list(osutils._walkdirs_utf8('.')))
1158
1302
self.assertIsInstance(osutils._selected_dir_reader, expected)
1160
1304
def test_force_walkdirs_utf8_fs_utf8(self):
1161
1305
self.requireFeature(UTF8DirReaderFeature)
1162
1306
self._save_platform_info()
1163
win32utils.winver = None # Avoid the win32 detection code
1164
osutils._fs_enc = 'UTF-8'
1165
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1307
osutils._fs_enc = 'utf-8'
1308
self.assertDirReaderIs(UTF8DirReaderFeature.module.UTF8DirReader, b".")
1167
1310
def test_force_walkdirs_utf8_fs_ascii(self):
1168
1311
self.requireFeature(UTF8DirReaderFeature)
1169
1312
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)
1313
osutils._fs_enc = 'ascii'
1314
self.assertDirReaderIs(
1315
UTF8DirReaderFeature.module.UTF8DirReader, b".")
1181
1317
def test_force_walkdirs_utf8_fs_latin1(self):
1182
1318
self._save_platform_info()
1183
win32utils.winver = None # Avoid the win32 detection code
1184
osutils._fs_enc = 'latin1'
1185
self.assertDirReaderIs(osutils.UnicodeDirReader)
1319
osutils._fs_enc = 'iso-8859-1'
1320
self.assertDirReaderIs(osutils.UnicodeDirReader, ".")
1187
1322
def test_force_walkdirs_utf8_nt(self):
1188
1323
# Disabled because the thunk of the whole walkdirs api is disabled.
1189
1324
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1190
1325
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)
1326
from .._walkdirs_win32 import Win32ReadDir
1327
self.assertDirReaderIs(Win32ReadDir, ".")
1201
1329
def test_unicode_walkdirs(self):
1202
1330
"""Walkdirs should always return unicode paths."""
1203
self.requireFeature(tests.UnicodeFilenameFeature)
1331
self.requireFeature(features.UnicodeFilenameFeature)
1204
1332
name0 = u'0file-\xb6'
1205
1333
name1 = u'1dir-\u062c\u0648'
1206
1334
name2 = u'2file-\u0633'
1260
1388
name2 = name2.encode('utf8')
1262
1390
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),
1392
[(name0, name0, 'file', b'./' + name0),
1393
(name1, name1, 'directory', b'./' + name1),
1394
(name2, name2, 'file', b'./' + name2),
1397
((name1, b'./' + name1),
1398
[(name1 + b'/' + name0, name0, 'file', b'./' + name1
1400
(name1 + b'/' + name1, name1, 'directory', b'./' + name1
1404
((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1282
1410
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1283
1411
# all abspaths are Unicode, and encode them back into utf8.
1284
1412
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1285
self.assertIsInstance(dirdetail[0], str)
1286
if isinstance(dirdetail[1], unicode):
1413
self.assertIsInstance(dirdetail[0], bytes)
1414
if isinstance(dirdetail[1], text_type):
1287
1415
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1288
1416
dirblock = [list(info) for info in dirblock]
1289
1417
for info in dirblock:
1290
self.assertIsInstance(info[4], unicode)
1418
self.assertIsInstance(info[4], text_type)
1291
1419
info[4] = info[4].encode('utf8')
1292
1420
new_dirblock = []
1293
1421
for info in dirblock:
1294
self.assertIsInstance(info[0], str)
1295
self.assertIsInstance(info[1], str)
1296
self.assertIsInstance(info[4], str)
1422
self.assertIsInstance(info[0], bytes)
1423
self.assertIsInstance(info[1], bytes)
1424
self.assertIsInstance(info[4], bytes)
1297
1425
# Remove the stat information
1298
1426
new_dirblock.append((info[0], info[1], info[2], info[4]))
1299
1427
result.append((dirdetail, new_dirblock))
2000
2135
def test_copy_ownership_from_path(self):
2001
2136
"""copy_ownership_from_path test with specified src."""
2003
f = open('test_file', 'wt')
2138
open('test_file', 'wt').close()
2004
2139
osutils.copy_ownership_from_path('test_file', ownsrc)
2006
2141
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)
2142
self.assertEqual(self.path, 'test_file')
2143
self.assertEqual(self.uid, s.st_uid)
2144
self.assertEqual(self.gid, s.st_gid)
2011
2146
def test_copy_ownership_nonesrc(self):
2012
2147
"""copy_ownership_from_path test with src=None."""
2013
f = open('test_file', 'wt')
2148
open('test_file', 'wt').close()
2014
2149
# should use parent dir for permissions
2015
2150
osutils.copy_ownership_from_path('test_file')
2017
2152
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)
2153
self.assertEqual(self.path, 'test_file')
2154
self.assertEqual(self.uid, s.st_uid)
2155
self.assertEqual(self.gid, s.st_gid)
2158
class TestPathFromEnviron(tests.TestCase):
2160
def test_is_unicode(self):
2161
self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
2162
path = osutils.path_from_environ('BRZ_TEST_PATH')
2163
self.assertIsInstance(path, text_type)
2164
self.assertEqual(u'./anywhere at all/', path)
2166
def test_posix_path_env_ascii(self):
2167
self.overrideEnv('BRZ_TEST_PATH', '/tmp')
2168
home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
2169
self.assertIsInstance(home, text_type)
2170
self.assertEqual(u'/tmp', home)
2172
def test_posix_path_env_unicode(self):
2173
self.requireFeature(features.ByteStringNamedFilesystem)
2174
self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
2175
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2176
self.assertEqual(u'/home/\xa7test',
2177
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2178
osutils._fs_enc = "iso8859-5"
2180
# In Python 3, os.environ returns unicode.
2181
self.assertEqual(u'/home/\xa7test',
2182
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2184
self.assertEqual(u'/home/\u0407test',
2185
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2186
osutils._fs_enc = "utf-8"
2188
errors.BadFilenameEncoding,
2189
osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
2192
class TestGetHomeDir(tests.TestCase):
2194
def test_is_unicode(self):
2195
home = osutils._get_home_dir()
2196
self.assertIsInstance(home, text_type)
2198
def test_posix_homeless(self):
2199
self.overrideEnv('HOME', None)
2200
home = osutils._get_home_dir()
2201
self.assertIsInstance(home, text_type)
2203
def test_posix_home_ascii(self):
2204
self.overrideEnv('HOME', '/home/test')
2205
home = osutils._posix_get_home_dir()
2206
self.assertIsInstance(home, text_type)
2207
self.assertEqual(u'/home/test', home)
2209
def test_posix_home_unicode(self):
2210
self.requireFeature(features.ByteStringNamedFilesystem)
2211
self.overrideEnv('HOME', '/home/\xa7test')
2212
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2213
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2214
osutils._fs_enc = "iso8859-5"
2216
# In python 3, os.environ returns unicode
2217
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2219
self.assertEqual(u'/home/\u0407test',
2220
osutils._posix_get_home_dir())
2221
osutils._fs_enc = "utf-8"
2222
self.assertRaises(errors.BadFilenameEncoding,
2223
osutils._posix_get_home_dir)
2226
class TestGetuserUnicode(tests.TestCase):
2228
def test_is_unicode(self):
2229
user = osutils.getuser_unicode()
2230
self.assertIsInstance(user, text_type)
2232
def envvar_to_override(self):
2233
if sys.platform == "win32":
2234
# Disable use of platform calls on windows so envvar is used
2235
self.overrideAttr(win32utils, 'has_ctypes', False)
2236
return 'USERNAME' # only variable used on windows
2237
return 'LOGNAME' # first variable checked by getpass.getuser()
2239
def test_ascii_user(self):
2240
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2241
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2243
def test_unicode_user(self):
2244
ue = osutils.get_user_encoding()
2245
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2247
raise tests.TestSkipped(
2248
'Cannot find a unicode character that works in encoding %s'
2249
% (osutils.get_user_encoding(),))
2250
uni_username = u'jrandom' + uni_val
2251
encoded_username = uni_username.encode(ue)
2253
self.overrideEnv(self.envvar_to_override(), uni_username)
2255
self.overrideEnv(self.envvar_to_override(), encoded_username)
2256
self.assertEqual(uni_username, osutils.getuser_unicode())
2259
class TestBackupNames(tests.TestCase):
2262
super(TestBackupNames, self).setUp()
2265
def backup_exists(self, name):
2266
return name in self.backups
2268
def available_backup_name(self, name):
2269
backup_name = osutils.available_backup_name(name, self.backup_exists)
2270
self.backups.append(backup_name)
2273
def assertBackupName(self, expected, name):
2274
self.assertEqual(expected, self.available_backup_name(name))
2276
def test_empty(self):
2277
self.assertBackupName('file.~1~', 'file')
2279
def test_existing(self):
2280
self.available_backup_name('file')
2281
self.available_backup_name('file')
2282
self.assertBackupName('file.~3~', 'file')
2283
# Empty slots are found, this is not a strict requirement and may be
2284
# revisited if we test against all implementations.
2285
self.backups.remove('file.~2~')
2286
self.assertBackupName('file.~2~', 'file')
2289
class TestFindExecutableInPath(tests.TestCase):
2291
def test_windows(self):
2292
if sys.platform != 'win32':
2293
raise tests.TestSkipped('test requires win32')
2294
self.assertTrue(osutils.find_executable_on_path(
2295
'explorer') is not None)
2297
osutils.find_executable_on_path('explorer.exe') is not None)
2299
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2301
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2302
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2304
def test_windows_app_path(self):
2305
if sys.platform != 'win32':
2306
raise tests.TestSkipped('test requires win32')
2307
# Override PATH env var so that exe can only be found on App Path
2308
self.overrideEnv('PATH', '')
2309
# Internt Explorer is always registered in the App Path
2310
self.assertTrue(osutils.find_executable_on_path(
2311
'iexplore') is not None)
2313
def test_other(self):
2314
if sys.platform == 'win32':
2315
raise tests.TestSkipped('test requires non-win32')
2316
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2318
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2321
class TestEnvironmentErrors(tests.TestCase):
2322
"""Test handling of environmental errors"""
2324
def test_is_oserror(self):
2325
self.assertTrue(osutils.is_environment_error(
2326
OSError(errno.EINVAL, "Invalid parameter")))
2328
def test_is_ioerror(self):
2329
self.assertTrue(osutils.is_environment_error(
2330
IOError(errno.EINVAL, "Invalid parameter")))
2332
def test_is_socket_error(self):
2333
self.assertTrue(osutils.is_environment_error(
2334
socket.error(errno.EINVAL, "Invalid parameter")))
2336
def test_is_select_error(self):
2337
self.assertTrue(osutils.is_environment_error(
2338
select.error(errno.EINVAL, "Invalid parameter")))
2340
def test_is_pywintypes_error(self):
2341
self.requireFeature(features.pywintypes)
2343
self.assertTrue(osutils.is_environment_error(
2344
pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))
2347
class TestXDGCacheDir(tests.TestCaseInTempDir):
2348
# must be in temp dir because tests for the existence of the breezy
2349
# subdirectory of $XDG_CACHE_HOME
2352
super(TestXDGCacheDir, self).setUp()
2353
if sys.platform in ('darwin', 'win32'):
2354
raise tests.TestNotApplicable(
2355
'XDG cache dir not used on this platform')
2356
self.overrideEnv('HOME', self.test_home_dir)
2357
# BZR_HOME overrides everything we want to test so unset it.
2358
self.overrideEnv('BZR_HOME', None)
2360
def test_xdg_cache_dir_exists(self):
2361
"""When ~/.cache/breezy exists, use it as the cache dir."""
2362
cachedir = osutils.pathjoin(self.test_home_dir, '.cache')
2363
newdir = osutils.pathjoin(cachedir, 'breezy')
2365
from xdg import BaseDirectory
2369
self.overrideAttr(BaseDirectory, "xdg_cache_home", cachedir)
2371
self.assertEqual(osutils.cache_dir(), newdir)
2373
def test_xdg_cache_home_unix(self):
2374
"""When XDG_CACHE_HOME is set, use it."""
2375
if sys.platform in ('nt', 'win32'):
2376
raise tests.TestNotApplicable(
2377
'XDG cache dir not used on this platform')
2378
xdgcachedir = osutils.pathjoin(self.test_home_dir, 'xdgcache')
2379
self.overrideEnv('XDG_CACHE_HOME', xdgcachedir)
2381
from xdg import BaseDirectory
2385
self.overrideAttr(BaseDirectory, "xdg_cache_home", xdgcachedir)
2386
newdir = osutils.pathjoin(xdgcachedir, 'breezy')
2388
self.assertEqual(osutils.cache_dir(), newdir)
2390
class SupportsExecutableTests(tests.TestCaseInTempDir):
2392
def test_returns_bool(self):
2393
self.assertIsInstance(osutils.supports_executable(self.test_dir), bool)
2396
class SupportsSymlinksTests(tests.TestCaseInTempDir):
2398
def test_returns_bool(self):
2399
self.assertIsInstance(osutils.supports_symlinks(self.test_dir), bool)
2402
class GetFsTypeTests(tests.TestCaseInTempDir):
2404
def test_returns_string(self):
2405
self.requireFeature(psutil_feature)
2406
self.assertIsInstance(osutils.get_fs_type(self.test_dir), str)