613
545
self.assertTrue(self.test_data_len > self.block_size)
615
547
from_file = file_utils.FakeReadFile(self.test_data)
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)
550
# read (max / 2) bytes and verify read size wasn't affected
551
num_bytes_to_read = self.block_size / 2
552
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
622
553
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
623
554
self.assertEqual(from_file.get_read_count(), 1)
625
556
# read (max) bytes and verify read size wasn't affected
626
557
num_bytes_to_read = self.block_size
627
558
from_file.reset_read_count()
628
osutils.pumpfile(from_file, to_file,
629
num_bytes_to_read, self.block_size)
559
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
630
560
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
631
561
self.assertEqual(from_file.get_read_count(), 1)
633
563
# read (max + 1) bytes and verify read size was limited
634
564
num_bytes_to_read = self.block_size + 1
635
565
from_file.reset_read_count()
636
osutils.pumpfile(from_file, to_file,
637
num_bytes_to_read, self.block_size)
566
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
638
567
self.assertEqual(from_file.get_max_read_size(), self.block_size)
639
568
self.assertEqual(from_file.get_read_count(), 2)
641
570
# finish reading the rest of the data
642
571
num_bytes_to_read = self.test_data_len - to_file.tell()
643
osutils.pumpfile(from_file, to_file,
644
num_bytes_to_read, self.block_size)
572
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
646
574
# report error if the data wasn't equal (we only report the size due
647
575
# to the length of the data)
733
660
(36, 'write')], activity)
735
662
# And with a limited amount of data
736
from_file = BytesIO(self.test_data)
663
from_file = StringIO(self.test_data)
739
666
osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
740
667
report_activity=log_activity, direction='read')
742
[(500, 'read'), (500, 'read'), (28, 'read')], activity)
668
self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
745
672
class TestPumpStringFile(tests.TestCase):
747
674
def test_empty(self):
749
osutils.pump_string_file(b"", output)
750
self.assertEqual(b"", output.getvalue())
676
osutils.pump_string_file("", output)
677
self.assertEqual("", output.getvalue())
752
679
def test_more_than_segment_size(self):
754
osutils.pump_string_file(b"123456789", output, 2)
755
self.assertEqual(b"123456789", output.getvalue())
681
osutils.pump_string_file("123456789", output, 2)
682
self.assertEqual("123456789", output.getvalue())
757
684
def test_segment_size(self):
759
osutils.pump_string_file(b"12", output, 2)
760
self.assertEqual(b"12", output.getvalue())
686
osutils.pump_string_file("12", output, 2)
687
self.assertEqual("12", output.getvalue())
762
689
def test_segment_size_multiple(self):
764
osutils.pump_string_file(b"1234", output, 2)
765
self.assertEqual(b"1234", output.getvalue())
691
osutils.pump_string_file("1234", output, 2)
692
self.assertEqual("1234", output.getvalue())
768
695
class TestRelpath(tests.TestCase):
796
723
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
798
725
def test_from_utf8_string(self):
799
self.assertEqual(u'foo\xae', osutils.safe_unicode(b'foo\xc2\xae'))
726
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
801
728
def test_bad_utf8_string(self):
802
729
self.assertRaises(errors.BzrBadParameterNotUnicode,
803
730
osutils.safe_unicode,
807
734
class TestSafeUtf8(tests.TestCase):
809
736
def test_from_ascii_string(self):
811
self.assertEqual(b'foobar', osutils.safe_utf8(f))
738
self.assertEqual('foobar', osutils.safe_utf8(f))
813
740
def test_from_unicode_string_ascii_contents(self):
814
self.assertEqual(b'bargam', osutils.safe_utf8(u'bargam'))
741
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
816
743
def test_from_unicode_string_unicode_contents(self):
817
self.assertEqual(b'bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
744
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
819
746
def test_from_utf8_string(self):
820
self.assertEqual(b'foo\xc2\xae', osutils.safe_utf8(b'foo\xc2\xae'))
747
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
822
749
def test_bad_utf8_string(self):
823
750
self.assertRaises(errors.BzrBadParameterNotUnicode,
824
osutils.safe_utf8, b'\xbb\xbb')
751
osutils.safe_utf8, '\xbb\xbb')
827
754
class TestSafeRevisionId(tests.TestCase):
829
756
def test_from_ascii_string(self):
830
757
# this shouldn't give a warning because it's getting an ascii string
831
self.assertEqual(b'foobar', osutils.safe_revision_id(b'foobar'))
758
self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
833
760
def test_from_unicode_string_ascii_contents(self):
834
self.assertRaises(TypeError,
835
osutils.safe_revision_id, u'bargam')
761
self.assertEqual('bargam',
762
osutils.safe_revision_id(u'bargam', warn=False))
764
def test_from_unicode_deprecated(self):
765
self.assertEqual('bargam',
766
self.callDeprecated([osutils._revision_id_warning],
767
osutils.safe_revision_id, u'bargam'))
837
769
def test_from_unicode_string_unicode_contents(self):
838
self.assertRaises(TypeError,
839
osutils.safe_revision_id, u'bargam\xae')
770
self.assertEqual('bargam\xc2\xae',
771
osutils.safe_revision_id(u'bargam\xae', warn=False))
841
773
def test_from_utf8_string(self):
842
self.assertEqual(b'foo\xc2\xae',
843
osutils.safe_revision_id(b'foo\xc2\xae'))
774
self.assertEqual('foo\xc2\xae',
775
osutils.safe_revision_id('foo\xc2\xae'))
845
777
def test_none(self):
846
778
"""Currently, None is a valid revision_id"""
850
782
class TestSafeFileId(tests.TestCase):
852
784
def test_from_ascii_string(self):
853
self.assertEqual(b'foobar', osutils.safe_file_id(b'foobar'))
785
self.assertEqual('foobar', osutils.safe_file_id('foobar'))
855
787
def test_from_unicode_string_ascii_contents(self):
856
self.assertRaises(TypeError, osutils.safe_file_id, u'bargam')
788
self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
790
def test_from_unicode_deprecated(self):
791
self.assertEqual('bargam',
792
self.callDeprecated([osutils._file_id_warning],
793
osutils.safe_file_id, u'bargam'))
858
795
def test_from_unicode_string_unicode_contents(self):
859
self.assertRaises(TypeError,
860
osutils.safe_file_id, u'bargam\xae')
796
self.assertEqual('bargam\xc2\xae',
797
osutils.safe_file_id(u'bargam\xae', warn=False))
862
799
def test_from_utf8_string(self):
863
self.assertEqual(b'foo\xc2\xae',
864
osutils.safe_file_id(b'foo\xc2\xae'))
800
self.assertEqual('foo\xc2\xae',
801
osutils.safe_file_id('foo\xc2\xae'))
866
803
def test_none(self):
867
804
"""Currently, None is a valid revision_id"""
868
805
self.assertEqual(None, osutils.safe_file_id(None))
871
class TestSendAll(tests.TestCase):
873
def test_send_with_disconnected_socket(self):
874
class DisconnectedSocket(object):
875
def __init__(self, err):
878
def send(self, content):
883
# All of these should be treated as ConnectionReset
885
for err_cls in (IOError, socket.error):
886
for errnum in osutils._end_of_stream_errors:
887
errs.append(err_cls(errnum))
889
sock = DisconnectedSocket(err)
890
self.assertRaises(errors.ConnectionReset,
891
osutils.send_all, sock, b'some more content')
893
def test_send_with_no_progress(self):
894
# See https://bugs.launchpad.net/bzr/+bug/1047309
895
# It seems that paramiko can get into a state where it doesn't error,
896
# but it returns 0 bytes sent for requests over and over again.
897
class NoSendingSocket(object):
901
def send(self, bytes):
903
if self.call_count > 100:
904
# Prevent the test suite from hanging
905
raise RuntimeError('too many calls')
907
sock = NoSendingSocket()
908
self.assertRaises(errors.ConnectionReset,
909
osutils.send_all, sock, b'content')
910
self.assertEqual(1, sock.call_count)
913
class TestPosixFuncs(tests.TestCase):
914
"""Test that the posix version of normpath returns an appropriate path
915
when used with 2 leading slashes."""
917
def test_normpath(self):
918
self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
920
'/etc/shadow', osutils._posix_normpath('//etc/shadow'))
922
'/etc/shadow', osutils._posix_normpath('///etc/shadow'))
925
808
class TestWin32Funcs(tests.TestCase):
926
809
"""Test that _win32 versions of os utilities return appropriate paths."""
928
811
def test_abspath(self):
929
self.requireFeature(features.win32_feature)
930
812
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
931
813
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
932
814
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
995
887
def test_minimum_path_selection(self):
996
888
self.assertEqual(set(),
997
osutils.minimum_path_selection([]))
998
self.assertEqual({'a'},
999
osutils.minimum_path_selection(['a']))
1000
self.assertEqual({'a', 'b'},
1001
osutils.minimum_path_selection(['a', 'b']))
1002
self.assertEqual({'a/', 'b'},
1003
osutils.minimum_path_selection(['a/', 'b']))
1004
self.assertEqual({'a/', 'b'},
1005
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
1006
self.assertEqual({'a-b', 'a', 'a0b'},
1007
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
889
osutils.minimum_path_selection([]))
890
self.assertEqual(set(['a']),
891
osutils.minimum_path_selection(['a']))
892
self.assertEqual(set(['a', 'b']),
893
osutils.minimum_path_selection(['a', 'b']))
894
self.assertEqual(set(['a/', 'b']),
895
osutils.minimum_path_selection(['a/', 'b']))
896
self.assertEqual(set(['a/', 'b']),
897
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
898
self.assertEqual(set(['a-b', 'a', 'a0b']),
899
osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
1009
901
def test_mkdtemp(self):
1010
902
tmpdir = osutils._win32_mkdtemp(dir='.')
1011
903
self.assertFalse('\\' in tmpdir)
1013
905
def test_rename(self):
1014
with open('a', 'wb') as a:
1016
with open('b', 'wb') as b:
1019
913
osutils._win32_rename('b', 'a')
1020
self.assertPathExists('a')
1021
self.assertPathDoesNotExist('b')
1022
self.assertFileEqual(b'baz\n', 'a')
914
self.failUnlessExists('a')
915
self.failIfExists('b')
916
self.assertFileEqual('baz\n', 'a')
1024
918
def test_rename_missing_file(self):
1025
with open('a', 'wb') as a:
1029
924
osutils._win32_rename('b', 'a')
1030
except (IOError, OSError) as e:
925
except (IOError, OSError), e:
1031
926
self.assertEqual(errno.ENOENT, e.errno)
1032
self.assertFileEqual(b'foo\n', 'a')
927
self.assertFileEqual('foo\n', 'a')
1034
929
def test_rename_missing_dir(self):
1037
932
osutils._win32_rename('b', 'a')
1038
except (IOError, OSError) as e:
933
except (IOError, OSError), e:
1039
934
self.assertEqual(errno.ENOENT, e.errno)
1041
936
def test_rename_current_dir(self):
1288
1174
dirblock[:] = new_dirblock
1290
1176
def _save_platform_info(self):
1177
self.overrideAttr(win32utils, 'winver')
1291
1178
self.overrideAttr(osutils, '_fs_enc')
1292
1179
self.overrideAttr(osutils, '_selected_dir_reader')
1294
def assertDirReaderIs(self, expected, top):
1181
def assertDirReaderIs(self, expected):
1295
1182
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
1296
1183
# Force it to redetect
1297
1184
osutils._selected_dir_reader = None
1298
1185
# Nothing to list, but should still trigger the selection logic
1299
self.assertEqual([((b'', top), [])], list(osutils._walkdirs_utf8('.')))
1186
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1300
1187
self.assertIsInstance(osutils._selected_dir_reader, expected)
1302
1189
def test_force_walkdirs_utf8_fs_utf8(self):
1303
1190
self.requireFeature(UTF8DirReaderFeature)
1304
1191
self._save_platform_info()
1305
osutils._fs_enc = 'utf-8'
1306
self.assertDirReaderIs(UTF8DirReaderFeature.module.UTF8DirReader, b".")
1192
win32utils.winver = None # Avoid the win32 detection code
1193
osutils._fs_enc = 'UTF-8'
1194
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1308
1196
def test_force_walkdirs_utf8_fs_ascii(self):
1309
1197
self.requireFeature(UTF8DirReaderFeature)
1310
1198
self._save_platform_info()
1311
osutils._fs_enc = 'ascii'
1312
self.assertDirReaderIs(
1313
UTF8DirReaderFeature.module.UTF8DirReader, b".")
1199
win32utils.winver = None # Avoid the win32 detection code
1200
osutils._fs_enc = 'US-ASCII'
1201
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1203
def test_force_walkdirs_utf8_fs_ANSI(self):
1204
self.requireFeature(UTF8DirReaderFeature)
1205
self._save_platform_info()
1206
win32utils.winver = None # Avoid the win32 detection code
1207
osutils._fs_enc = 'ANSI_X3.4-1968'
1208
self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1315
1210
def test_force_walkdirs_utf8_fs_latin1(self):
1316
1211
self._save_platform_info()
1317
osutils._fs_enc = 'iso-8859-1'
1318
self.assertDirReaderIs(osutils.UnicodeDirReader, ".")
1212
win32utils.winver = None # Avoid the win32 detection code
1213
osutils._fs_enc = 'latin1'
1214
self.assertDirReaderIs(osutils.UnicodeDirReader)
1320
1216
def test_force_walkdirs_utf8_nt(self):
1321
1217
# Disabled because the thunk of the whole walkdirs api is disabled.
1322
1218
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1323
1219
self._save_platform_info()
1324
from .._walkdirs_win32 import Win32ReadDir
1325
self.assertDirReaderIs(Win32ReadDir, ".")
1220
win32utils.winver = 'Windows NT'
1221
from bzrlib._walkdirs_win32 import Win32ReadDir
1222
self.assertDirReaderIs(Win32ReadDir)
1224
def test_force_walkdirs_utf8_98(self):
1225
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1226
self._save_platform_info()
1227
win32utils.winver = 'Windows 98'
1228
self.assertDirReaderIs(osutils.UnicodeDirReader)
1327
1230
def test_unicode_walkdirs(self):
1328
1231
"""Walkdirs should always return unicode paths."""
1329
self.requireFeature(features.UnicodeFilenameFeature)
1232
self.requireFeature(tests.UnicodeFilenameFeature)
1330
1233
name0 = u'0file-\xb6'
1331
1234
name1 = u'1dir-\u062c\u0648'
1332
1235
name2 = u'2file-\u0633'
1386
1289
name2 = name2.encode('utf8')
1388
1291
expected_dirblocks = [
1390
[(name0, name0, 'file', b'./' + name0),
1391
(name1, name1, 'directory', b'./' + name1),
1392
(name2, name2, 'file', b'./' + name2),
1395
((name1, b'./' + name1),
1396
[(name1 + b'/' + name0, name0, 'file', b'./' + name1
1398
(name1 + b'/' + name1, name1, 'directory', b'./' + name1
1402
((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1293
[(name0, name0, 'file', './' + name0),
1294
(name1, name1, 'directory', './' + name1),
1295
(name2, name2, 'file', './' + name2),
1298
((name1, './' + name1),
1299
[(name1 + '/' + name0, name0, 'file', './' + name1
1301
(name1 + '/' + name1, name1, 'directory', './' + name1
1305
((name1 + '/' + name1, './' + name1 + '/' + name1),
1408
1311
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1409
1312
# all abspaths are Unicode, and encode them back into utf8.
1410
1313
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1411
self.assertIsInstance(dirdetail[0], bytes)
1412
if isinstance(dirdetail[1], text_type):
1314
self.assertIsInstance(dirdetail[0], str)
1315
if isinstance(dirdetail[1], unicode):
1413
1316
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1414
1317
dirblock = [list(info) for info in dirblock]
1415
1318
for info in dirblock:
1416
self.assertIsInstance(info[4], text_type)
1319
self.assertIsInstance(info[4], unicode)
1417
1320
info[4] = info[4].encode('utf8')
1418
1321
new_dirblock = []
1419
1322
for info in dirblock:
1420
self.assertIsInstance(info[0], bytes)
1421
self.assertIsInstance(info[1], bytes)
1422
self.assertIsInstance(info[4], bytes)
1323
self.assertIsInstance(info[0], str)
1324
self.assertIsInstance(info[1], str)
1325
self.assertIsInstance(info[4], str)
1423
1326
# Remove the stat information
1424
1327
new_dirblock.append((info[0], info[1], info[2], info[4]))
1425
1328
result.append((dirdetail, new_dirblock))
1793
1692
class TestResourceLoading(tests.TestCaseInTempDir):
1795
1694
def test_resource_string(self):
1796
# test resource in breezy
1797
text = osutils.resource_string('breezy', 'debug.py')
1695
# test resource in bzrlib
1696
text = osutils.resource_string('bzrlib', 'debug.py')
1798
1697
self.assertContainsRe(text, "debug_flags = set()")
1799
# test resource under breezy
1800
text = osutils.resource_string('breezy.ui', 'text.py')
1698
# test resource under bzrlib
1699
text = osutils.resource_string('bzrlib.ui', 'text.py')
1801
1700
self.assertContainsRe(text, "class TextUIFactory")
1802
1701
# test unsupported package
1803
1702
self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1805
1704
# test unknown resource
1806
self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
1705
self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1708
class TestReCompile(tests.TestCase):
1710
def _deprecated_re_compile_checked(self, *args, **kwargs):
1711
return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1712
osutils.re_compile_checked, *args, **kwargs)
1714
def test_re_compile_checked(self):
1715
r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1716
self.assertTrue(r.match('aaaa'))
1717
self.assertTrue(r.match('aAaA'))
1719
def test_re_compile_checked_error(self):
1720
# like https://bugs.launchpad.net/bzr/+bug/251352
1722
# Due to possible test isolation error, re.compile is not lazy at
1723
# this point. We re-install lazy compile.
1724
lazy_regex.install_lazy_compile()
1725
err = self.assertRaises(
1726
errors.BzrCommandError,
1727
self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1729
'Invalid regular expression in test case: '
1730
'"*" nothing to repeat',
1809
1734
class TestDirReader(tests.TestCaseInTempDir):
1811
scenarios = dir_reader_scenarios()
1813
1736
# Set by load_tests
1814
1737
_dir_reader_class = None
1815
1738
_native_to_unicode = None
1817
1740
def setUp(self):
1818
super(TestDirReader, self).setUp()
1741
tests.TestCaseInTempDir.setUp(self)
1819
1742
self.overrideAttr(osutils,
1820
1743
'_selected_dir_reader', self._dir_reader_class())
2133
2049
def test_copy_ownership_from_path(self):
2134
2050
"""copy_ownership_from_path test with specified src."""
2136
open('test_file', 'wt').close()
2052
f = open('test_file', 'wt')
2137
2053
osutils.copy_ownership_from_path('test_file', ownsrc)
2139
2055
s = os.stat(ownsrc)
2140
self.assertEqual(self.path, 'test_file')
2141
self.assertEqual(self.uid, s.st_uid)
2142
self.assertEqual(self.gid, s.st_gid)
2056
self.assertEquals(self.path, 'test_file')
2057
self.assertEquals(self.uid, s.st_uid)
2058
self.assertEquals(self.gid, s.st_gid)
2144
2060
def test_copy_ownership_nonesrc(self):
2145
2061
"""copy_ownership_from_path test with src=None."""
2146
open('test_file', 'wt').close()
2062
f = open('test_file', 'wt')
2147
2063
# should use parent dir for permissions
2148
2064
osutils.copy_ownership_from_path('test_file')
2150
2066
s = os.stat('..')
2151
self.assertEqual(self.path, 'test_file')
2152
self.assertEqual(self.uid, s.st_uid)
2153
self.assertEqual(self.gid, s.st_gid)
2156
class TestPathFromEnviron(tests.TestCase):
2158
def test_is_unicode(self):
2159
self.overrideEnv('BRZ_TEST_PATH', './anywhere at all/')
2160
path = osutils.path_from_environ('BRZ_TEST_PATH')
2161
self.assertIsInstance(path, text_type)
2162
self.assertEqual(u'./anywhere at all/', path)
2164
def test_posix_path_env_ascii(self):
2165
self.overrideEnv('BRZ_TEST_PATH', '/tmp')
2166
home = osutils._posix_path_from_environ('BRZ_TEST_PATH')
2167
self.assertIsInstance(home, text_type)
2168
self.assertEqual(u'/tmp', home)
2170
def test_posix_path_env_unicode(self):
2171
self.requireFeature(features.ByteStringNamedFilesystem)
2172
self.overrideEnv('BRZ_TEST_PATH', '/home/\xa7test')
2173
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2174
self.assertEqual(u'/home/\xa7test',
2175
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2176
osutils._fs_enc = "iso8859-5"
2178
# In Python 3, os.environ returns unicode.
2179
self.assertEqual(u'/home/\xa7test',
2180
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2182
self.assertEqual(u'/home/\u0407test',
2183
osutils._posix_path_from_environ('BRZ_TEST_PATH'))
2184
osutils._fs_enc = "utf-8"
2186
errors.BadFilenameEncoding,
2187
osutils._posix_path_from_environ, 'BRZ_TEST_PATH')
2190
class TestGetHomeDir(tests.TestCase):
2192
def test_is_unicode(self):
2193
home = osutils._get_home_dir()
2194
self.assertIsInstance(home, text_type)
2196
def test_posix_homeless(self):
2197
self.overrideEnv('HOME', None)
2198
home = osutils._get_home_dir()
2199
self.assertIsInstance(home, text_type)
2201
def test_posix_home_ascii(self):
2202
self.overrideEnv('HOME', '/home/test')
2203
home = osutils._posix_get_home_dir()
2204
self.assertIsInstance(home, text_type)
2205
self.assertEqual(u'/home/test', home)
2207
def test_posix_home_unicode(self):
2208
self.requireFeature(features.ByteStringNamedFilesystem)
2209
self.overrideEnv('HOME', '/home/\xa7test')
2210
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2211
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2212
osutils._fs_enc = "iso8859-5"
2214
# In python 3, os.environ returns unicode
2215
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2217
self.assertEqual(u'/home/\u0407test',
2218
osutils._posix_get_home_dir())
2219
osutils._fs_enc = "utf-8"
2220
self.assertRaises(errors.BadFilenameEncoding,
2221
osutils._posix_get_home_dir)
2067
self.assertEquals(self.path, 'test_file')
2068
self.assertEquals(self.uid, s.st_uid)
2069
self.assertEquals(self.gid, s.st_gid)
2224
2071
class TestGetuserUnicode(tests.TestCase):
2226
def test_is_unicode(self):
2227
user = osutils.getuser_unicode()
2228
self.assertIsInstance(user, text_type)
2230
def envvar_to_override(self):
2231
if sys.platform == "win32":
2232
# Disable use of platform calls on windows so envvar is used
2233
self.overrideAttr(win32utils, 'has_ctypes', False)
2234
return 'USERNAME' # only variable used on windows
2235
return 'LOGNAME' # first variable checked by getpass.getuser()
2237
2073
def test_ascii_user(self):
2238
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2074
osutils.set_or_unset_env('LOGNAME', 'jrandom')
2239
2075
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2241
2077
def test_unicode_user(self):
2242
2078
ue = osutils.get_user_encoding()
2243
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2245
raise tests.TestSkipped(
2246
'Cannot find a unicode character that works in encoding %s'
2247
% (osutils.get_user_encoding(),))
2248
uni_username = u'jrandom' + uni_val
2249
encoded_username = uni_username.encode(ue)
2251
self.overrideEnv(self.envvar_to_override(), uni_username)
2253
self.overrideEnv(self.envvar_to_override(), encoded_username)
2254
self.assertEqual(uni_username, osutils.getuser_unicode())
2257
class TestBackupNames(tests.TestCase):
2260
super(TestBackupNames, self).setUp()
2263
def backup_exists(self, name):
2264
return name in self.backups
2266
def available_backup_name(self, name):
2267
backup_name = osutils.available_backup_name(name, self.backup_exists)
2268
self.backups.append(backup_name)
2271
def assertBackupName(self, expected, name):
2272
self.assertEqual(expected, self.available_backup_name(name))
2274
def test_empty(self):
2275
self.assertBackupName('file.~1~', 'file')
2277
def test_existing(self):
2278
self.available_backup_name('file')
2279
self.available_backup_name('file')
2280
self.assertBackupName('file.~3~', 'file')
2281
# Empty slots are found, this is not a strict requirement and may be
2282
# revisited if we test against all implementations.
2283
self.backups.remove('file.~2~')
2284
self.assertBackupName('file.~2~', 'file')
2287
class TestFindExecutableInPath(tests.TestCase):
2289
def test_windows(self):
2290
if sys.platform != 'win32':
2291
raise tests.TestSkipped('test requires win32')
2292
self.assertTrue(osutils.find_executable_on_path(
2293
'explorer') is not None)
2295
osutils.find_executable_on_path('explorer.exe') is not None)
2297
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2299
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2300
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2302
def test_windows_app_path(self):
2303
if sys.platform != 'win32':
2304
raise tests.TestSkipped('test requires win32')
2305
# Override PATH env var so that exe can only be found on App Path
2306
self.overrideEnv('PATH', '')
2307
# Internt Explorer is always registered in the App Path
2308
self.assertTrue(osutils.find_executable_on_path(
2309
'iexplore') is not None)
2311
def test_other(self):
2312
if sys.platform == 'win32':
2313
raise tests.TestSkipped('test requires non-win32')
2314
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2316
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2319
class TestEnvironmentErrors(tests.TestCase):
2320
"""Test handling of environmental errors"""
2322
def test_is_oserror(self):
2323
self.assertTrue(osutils.is_environment_error(
2324
OSError(errno.EINVAL, "Invalid parameter")))
2326
def test_is_ioerror(self):
2327
self.assertTrue(osutils.is_environment_error(
2328
IOError(errno.EINVAL, "Invalid parameter")))
2330
def test_is_socket_error(self):
2331
self.assertTrue(osutils.is_environment_error(
2332
socket.error(errno.EINVAL, "Invalid parameter")))
2334
def test_is_select_error(self):
2335
self.assertTrue(osutils.is_environment_error(
2336
select.error(errno.EINVAL, "Invalid parameter")))
2338
def test_is_pywintypes_error(self):
2339
self.requireFeature(features.pywintypes)
2341
self.assertTrue(osutils.is_environment_error(
2342
pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))
2345
class SupportsExecutableTests(tests.TestCaseInTempDir):
2347
def test_returns_bool(self):
2348
self.assertIsInstance(osutils.supports_executable(self.test_dir), bool)
2351
class SupportsSymlinksTests(tests.TestCaseInTempDir):
2353
def test_returns_bool(self):
2354
self.assertIsInstance(osutils.supports_symlinks(self.test_dir), bool)
2357
class MtabReader(tests.TestCaseInTempDir):
2359
def test_read_mtab(self):
2360
self.build_tree_contents([('mtab', """\
2361
/dev/mapper/blah--vg-root / ext4 rw,relatime,errors=remount-ro 0 0
2362
/dev/mapper/blah--vg-home /home vfat rw,relatime 0 0
2368
list(osutils.read_mtab('mtab')),
2370
(b'/home', 'vfat')])
2373
class GetFsTypeTests(tests.TestCaseInTempDir):
2375
def test_returns_string_or_none(self):
2376
ret = osutils.get_fs_type(self.test_dir)
2377
self.assertTrue(isinstance(ret, text_type) or ret is None)
2379
def test_returns_most_specific(self):
2381
osutils, '_FILESYSTEM_FINDER',
2382
osutils.FilesystemFinder(
2383
[(b'/', 'ext4'), (b'/home', 'vfat'),
2384
(b'/home/jelmer', 'ext2')]))
2385
self.assertEqual(osutils.get_fs_type(b'/home/jelmer/blah'), 'ext2')
2386
self.assertEqual(osutils.get_fs_type('/home/jelmer/blah'), 'ext2')
2387
self.assertEqual(osutils.get_fs_type(b'/home/jelmer'), 'ext2')
2388
self.assertEqual(osutils.get_fs_type(b'/home/martin'), 'vfat')
2389
self.assertEqual(osutils.get_fs_type(b'/home'), 'vfat')
2390
self.assertEqual(osutils.get_fs_type(b'/other'), 'ext4')
2392
def test_returns_none(self):
2394
osutils, '_FILESYSTEM_FINDER',
2395
osutils.FilesystemFinder([]))
2396
self.assertIs(osutils.get_fs_type('/home/jelmer/blah'), None)
2397
self.assertIs(osutils.get_fs_type(b'/home/jelmer/blah'), None)
2398
self.assertIs(osutils.get_fs_type('/home/jelmer'), None)
2079
osutils.set_or_unset_env('LOGNAME', u'jrandom\xb6'.encode(ue))
2080
self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())