~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Patch Queue Manager
  • Date: 2013-02-07 09:25:16 UTC
  • mfrom: (6572.1.2 bug-1107464)
  • Revision ID: pqm@pqm.ubuntu.com-20130207092516-eax0tqbckd3oiaw8
(jameinel) Fix bug #1107464,
 to allow the test suite to pass when python-apport is installed. (Dylan
 McCall)

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
import errno
21
21
import os
22
22
import re
 
23
import select
23
24
import socket
24
25
import sys
25
26
import time
41
42
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
43
 
43
44
 
44
 
class _UTF8DirReaderFeature(tests.Feature):
 
45
class _UTF8DirReaderFeature(features.Feature):
45
46
 
46
47
    def _probe(self):
47
48
        try:
54
55
    def feature_name(self):
55
56
        return 'bzrlib._readdir_pyx'
56
57
 
57
 
UTF8DirReaderFeature = _UTF8DirReaderFeature()
 
58
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
58
59
 
59
 
term_ios_feature = tests.ModuleAvailableFeature('termios')
 
60
term_ios_feature = features.ModuleAvailableFeature('termios')
60
61
 
61
62
 
62
63
def _already_unicode(s):
180
181
        shape = sorted(os.listdir('.'))
181
182
        self.assertEquals(['A', 'B'], shape)
182
183
 
 
184
    def test_rename_exception(self):
 
185
        try:
 
186
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
 
187
        except OSError, e:
 
188
            self.assertEqual(e.old_filename, 'nonexistent_path')
 
189
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
 
190
            self.assertTrue('nonexistent_path' in e.strerror)
 
191
            self.assertTrue('different_nonexistent_path' in e.strerror)
 
192
 
183
193
 
184
194
class TestRandChars(tests.TestCase):
185
195
 
429
439
class TestLinks(tests.TestCaseInTempDir):
430
440
 
431
441
    def test_dereference_path(self):
432
 
        self.requireFeature(tests.SymlinkFeature)
 
442
        self.requireFeature(features.SymlinkFeature)
433
443
        cwd = osutils.realpath('.')
434
444
        os.mkdir('bar')
435
445
        bar_path = osutils.pathjoin(cwd, 'bar')
482
492
 
483
493
class TestCanonicalRelPath(tests.TestCaseInTempDir):
484
494
 
485
 
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
 
495
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
486
496
 
487
497
    def test_canonical_relpath_simple(self):
488
498
        f = file('MixedCaseName', 'w')
544
554
    """Test pumpfile method."""
545
555
 
546
556
    def setUp(self):
547
 
        tests.TestCase.setUp(self)
 
557
        super(TestPumpFile, self).setUp()
548
558
        # create a test datablock
549
559
        self.block_size = 512
550
560
        pattern = '0123456789ABCDEF'
818
828
        self.assertEqual(None, osutils.safe_file_id(None))
819
829
 
820
830
 
 
831
class TestSendAll(tests.TestCase):
 
832
 
 
833
    def test_send_with_disconnected_socket(self):
 
834
        class DisconnectedSocket(object):
 
835
            def __init__(self, err):
 
836
                self.err = err
 
837
            def send(self, content):
 
838
                raise self.err
 
839
            def close(self):
 
840
                pass
 
841
        # All of these should be treated as ConnectionReset
 
842
        errs = []
 
843
        for err_cls in (IOError, socket.error):
 
844
            for errnum in osutils._end_of_stream_errors:
 
845
                errs.append(err_cls(errnum))
 
846
        for err in errs:
 
847
            sock = DisconnectedSocket(err)
 
848
            self.assertRaises(errors.ConnectionReset,
 
849
                osutils.send_all, sock, 'some more content')
 
850
 
 
851
    def test_send_with_no_progress(self):
 
852
        # See https://bugs.launchpad.net/bzr/+bug/1047309
 
853
        # It seems that paramiko can get into a state where it doesn't error,
 
854
        # but it returns 0 bytes sent for requests over and over again.
 
855
        class NoSendingSocket(object):
 
856
            def __init__(self):
 
857
                self.call_count = 0
 
858
            def send(self, bytes):
 
859
                self.call_count += 1
 
860
                if self.call_count > 100:
 
861
                    # Prevent the test suite from hanging
 
862
                    raise RuntimeError('too many calls')
 
863
                return 0
 
864
        sock = NoSendingSocket()
 
865
        self.assertRaises(errors.ConnectionReset,
 
866
                          osutils.send_all, sock, 'content')
 
867
        self.assertEqual(1, sock.call_count)
 
868
 
 
869
 
 
870
class TestPosixFuncs(tests.TestCase):
 
871
    """Test that the posix version of normpath returns an appropriate path
 
872
       when used with 2 leading slashes."""
 
873
 
 
874
    def test_normpath(self):
 
875
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
 
876
        self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
 
877
        self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
 
878
 
 
879
 
821
880
class TestWin32Funcs(tests.TestCase):
822
881
    """Test that _win32 versions of os utilities return appropriate paths."""
823
882
 
888
947
    """Test win32 functions that create files."""
889
948
 
890
949
    def test_getcwd(self):
891
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
950
        self.requireFeature(features.UnicodeFilenameFeature)
892
951
        os.mkdir(u'mu-\xb5')
893
952
        os.chdir(u'mu-\xb5')
894
953
        # TODO: jam 20060427 This will probably fail on Mac OSX because
984
1043
    """Test mac special functions that require directories."""
985
1044
 
986
1045
    def test_getcwd(self):
987
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1046
        self.requireFeature(features.UnicodeFilenameFeature)
988
1047
        os.mkdir(u'B\xe5gfors')
989
1048
        os.chdir(u'B\xe5gfors')
990
1049
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
991
1050
 
992
1051
    def test_getcwd_nonnorm(self):
993
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1052
        self.requireFeature(features.UnicodeFilenameFeature)
994
1053
        # Test that _mac_getcwd() will normalize this path
995
1054
        os.mkdir(u'Ba\u030agfors')
996
1055
        os.chdir(u'Ba\u030agfors')
1106
1165
        # are not using the filesystem's encoding
1107
1166
 
1108
1167
        # require a bytestring based filesystem
1109
 
        self.requireFeature(tests.ByteStringNamedFilesystem)
 
1168
        self.requireFeature(features.ByteStringNamedFilesystem)
1110
1169
 
1111
1170
        tree = [
1112
1171
            '.bzr',
1206
1265
        self.requireFeature(UTF8DirReaderFeature)
1207
1266
        self._save_platform_info()
1208
1267
        win32utils.winver = None # Avoid the win32 detection code
1209
 
        osutils._fs_enc = 'UTF-8'
1210
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1268
        osutils._fs_enc = 'utf-8'
 
1269
        self.assertDirReaderIs(
 
1270
            UTF8DirReaderFeature.module.UTF8DirReader)
1211
1271
 
1212
1272
    def test_force_walkdirs_utf8_fs_ascii(self):
1213
1273
        self.requireFeature(UTF8DirReaderFeature)
1214
1274
        self._save_platform_info()
1215
1275
        win32utils.winver = None # Avoid the win32 detection code
1216
 
        osutils._fs_enc = 'US-ASCII'
1217
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1218
 
 
1219
 
    def test_force_walkdirs_utf8_fs_ANSI(self):
1220
 
        self.requireFeature(UTF8DirReaderFeature)
1221
 
        self._save_platform_info()
1222
 
        win32utils.winver = None # Avoid the win32 detection code
1223
 
        osutils._fs_enc = 'ANSI_X3.4-1968'
1224
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1276
        osutils._fs_enc = 'ascii'
 
1277
        self.assertDirReaderIs(
 
1278
            UTF8DirReaderFeature.module.UTF8DirReader)
1225
1279
 
1226
1280
    def test_force_walkdirs_utf8_fs_latin1(self):
1227
1281
        self._save_platform_info()
1228
1282
        win32utils.winver = None # Avoid the win32 detection code
1229
 
        osutils._fs_enc = 'latin1'
 
1283
        osutils._fs_enc = 'iso-8859-1'
1230
1284
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1231
1285
 
1232
1286
    def test_force_walkdirs_utf8_nt(self):
1245
1299
 
1246
1300
    def test_unicode_walkdirs(self):
1247
1301
        """Walkdirs should always return unicode paths."""
1248
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1302
        self.requireFeature(features.UnicodeFilenameFeature)
1249
1303
        name0 = u'0file-\xb6'
1250
1304
        name1 = u'1dir-\u062c\u0648'
1251
1305
        name2 = u'2file-\u0633'
1288
1342
 
1289
1343
        The abspath portion might be in unicode or utf-8
1290
1344
        """
1291
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1345
        self.requireFeature(features.UnicodeFilenameFeature)
1292
1346
        name0 = u'0file-\xb6'
1293
1347
        name1 = u'1dir-\u062c\u0648'
1294
1348
        name2 = u'2file-\u0633'
1349
1403
 
1350
1404
        The abspath portion should be in unicode
1351
1405
        """
1352
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1406
        self.requireFeature(features.UnicodeFilenameFeature)
1353
1407
        # Use the unicode reader. TODO: split into driver-and-driven unit
1354
1408
        # tests.
1355
1409
        self._save_platform_info()
1396
1450
 
1397
1451
    def test__walkdirs_utf8_win32readdir(self):
1398
1452
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1399
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1453
        self.requireFeature(features.UnicodeFilenameFeature)
1400
1454
        from bzrlib._walkdirs_win32 import Win32ReadDir
1401
1455
        self._save_platform_info()
1402
1456
        osutils._selected_dir_reader = Win32ReadDir()
1453
1507
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1454
1508
        """make sure our Stat values are valid"""
1455
1509
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1456
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1510
        self.requireFeature(features.UnicodeFilenameFeature)
1457
1511
        from bzrlib._walkdirs_win32 import Win32ReadDir
1458
1512
        name0u = u'0file-\xb6'
1459
1513
        name0 = name0u.encode('utf8')
1477
1531
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1478
1532
        """make sure our Stat values are valid"""
1479
1533
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1480
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1534
        self.requireFeature(features.UnicodeFilenameFeature)
1481
1535
        from bzrlib._walkdirs_win32 import Win32ReadDir
1482
1536
        name0u = u'0dir-\u062c\u0648'
1483
1537
        name0 = name0u.encode('utf8')
1583
1637
        self.assertEqual(['c'], os.listdir('target/b'))
1584
1638
 
1585
1639
    def test_copy_tree_symlinks(self):
1586
 
        self.requireFeature(tests.SymlinkFeature)
 
1640
        self.requireFeature(features.SymlinkFeature)
1587
1641
        self.build_tree(['source/'])
1588
1642
        os.symlink('a/generic/path', 'source/lnk')
1589
1643
        osutils.copy_tree('source', 'target')
1756
1810
    _native_to_unicode = None
1757
1811
 
1758
1812
    def setUp(self):
1759
 
        tests.TestCaseInTempDir.setUp(self)
 
1813
        super(TestDirReader, self).setUp()
1760
1814
        self.overrideAttr(osutils,
1761
1815
                          '_selected_dir_reader', self._dir_reader_class())
1762
1816
 
1856
1910
        return filtered_dirblocks
1857
1911
 
1858
1912
    def test_walk_unicode_tree(self):
1859
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1913
        self.requireFeature(features.UnicodeFilenameFeature)
1860
1914
        tree, expected_dirblocks = self._get_unicode_tree()
1861
1915
        self.build_tree(tree)
1862
1916
        result = list(osutils._walkdirs_utf8('.'))
1863
1917
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1864
1918
 
1865
1919
    def test_symlink(self):
1866
 
        self.requireFeature(tests.SymlinkFeature)
1867
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1920
        self.requireFeature(features.SymlinkFeature)
 
1921
        self.requireFeature(features.UnicodeFilenameFeature)
1868
1922
        target = u'target\N{Euro Sign}'
1869
1923
        link_name = u'l\N{Euro Sign}nk'
1870
1924
        os.symlink(target, link_name)
1888
1942
    But prior python versions failed to properly encode the passed unicode
1889
1943
    string.
1890
1944
    """
1891
 
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
 
1945
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1892
1946
 
1893
1947
    def setUp(self):
1894
1948
        super(tests.TestCaseInTempDir, self).setUp()
1970
2024
class TestTerminalWidth(tests.TestCase):
1971
2025
 
1972
2026
    def setUp(self):
1973
 
        tests.TestCase.setUp(self)
 
2027
        super(TestTerminalWidth, self).setUp()
1974
2028
        self._orig_terminal_size_state = osutils._terminal_size_state
1975
2029
        self._orig_first_terminal_size = osutils._first_terminal_size
1976
2030
        self.addCleanup(self.restore_osutils_globals)
2057
2111
    _test_needs_features = [features.chown_feature]
2058
2112
 
2059
2113
    def setUp(self):
2060
 
        tests.TestCaseInTempDir.setUp(self)
 
2114
        super(TestCreationOps, self).setUp()
2061
2115
        self.overrideAttr(os, 'chown', self._dummy_chown)
2062
2116
 
2063
2117
        # params set by call to _dummy_chown
2089
2143
        self.assertEquals(self.gid, s.st_gid)
2090
2144
 
2091
2145
 
 
2146
class TestPathFromEnviron(tests.TestCase):
 
2147
 
 
2148
    def test_is_unicode(self):
 
2149
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
 
2150
        path = osutils.path_from_environ('BZR_TEST_PATH')
 
2151
        self.assertIsInstance(path, unicode)
 
2152
        self.assertEqual(u'./anywhere at all/', path)
 
2153
 
 
2154
    def test_posix_path_env_ascii(self):
 
2155
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
 
2156
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
 
2157
        self.assertIsInstance(home, unicode)
 
2158
        self.assertEqual(u'/tmp', home)
 
2159
 
 
2160
    def test_posix_path_env_unicode(self):
 
2161
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2162
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
 
2163
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2164
        self.assertEqual(u'/home/\xa7test',
 
2165
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
 
2166
        osutils._fs_enc = "iso8859-5"
 
2167
        self.assertEqual(u'/home/\u0407test',
 
2168
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
 
2169
        osutils._fs_enc = "utf-8"
 
2170
        self.assertRaises(errors.BadFilenameEncoding,
 
2171
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
 
2172
 
 
2173
 
 
2174
class TestGetHomeDir(tests.TestCase):
 
2175
 
 
2176
    def test_is_unicode(self):
 
2177
        home = osutils._get_home_dir()
 
2178
        self.assertIsInstance(home, unicode)
 
2179
 
 
2180
    def test_posix_homeless(self):
 
2181
        self.overrideEnv('HOME', None)
 
2182
        home = osutils._get_home_dir()
 
2183
        self.assertIsInstance(home, unicode)
 
2184
 
 
2185
    def test_posix_home_ascii(self):
 
2186
        self.overrideEnv('HOME', '/home/test')
 
2187
        home = osutils._posix_get_home_dir()
 
2188
        self.assertIsInstance(home, unicode)
 
2189
        self.assertEqual(u'/home/test', home)
 
2190
 
 
2191
    def test_posix_home_unicode(self):
 
2192
        self.requireFeature(features.ByteStringNamedFilesystem)
 
2193
        self.overrideEnv('HOME', '/home/\xa7test')
 
2194
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
 
2195
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
 
2196
        osutils._fs_enc = "iso8859-5"
 
2197
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
 
2198
        osutils._fs_enc = "utf-8"
 
2199
        self.assertRaises(errors.BadFilenameEncoding,
 
2200
            osutils._posix_get_home_dir)
 
2201
 
 
2202
 
2092
2203
class TestGetuserUnicode(tests.TestCase):
2093
2204
 
 
2205
    def test_is_unicode(self):
 
2206
        user = osutils.getuser_unicode()
 
2207
        self.assertIsInstance(user, unicode)
 
2208
 
 
2209
    def envvar_to_override(self):
 
2210
        if sys.platform == "win32":
 
2211
            # Disable use of platform calls on windows so envvar is used
 
2212
            self.overrideAttr(win32utils, 'has_ctypes', False)
 
2213
            return 'USERNAME' # only variable used on windows
 
2214
        return 'LOGNAME' # first variable checked by getpass.getuser()
 
2215
 
2094
2216
    def test_ascii_user(self):
2095
 
        self.overrideEnv('LOGNAME', 'jrandom')
 
2217
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
2096
2218
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2097
2219
 
2098
2220
    def test_unicode_user(self):
2104
2226
                % (osutils.get_user_encoding(),))
2105
2227
        uni_username = u'jrandom' + uni_val
2106
2228
        encoded_username = uni_username.encode(ue)
2107
 
        self.overrideEnv('LOGNAME', encoded_username)
 
2229
        self.overrideEnv(self.envvar_to_override(), encoded_username)
2108
2230
        self.assertEqual(uni_username, osutils.getuser_unicode())
2109
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
2110
 
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
2111
 
 
2112
 
    def test_no_username_bug_660174(self):
2113
 
        self.requireFeature(features.win32_feature)
2114
 
        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
2115
 
            self.overrideEnv(name, None)
2116
 
        self.assertEqual(u'UNKNOWN', osutils.getuser_unicode())
2117
2231
 
2118
2232
 
2119
2233
class TestBackupNames(tests.TestCase):
2159
2273
        self.assertTrue(
2160
2274
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2161
2275
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
 
2276
        
 
2277
    def test_windows_app_path(self):
 
2278
        if sys.platform != 'win32':
 
2279
            raise tests.TestSkipped('test requires win32')
 
2280
        # Override PATH env var so that exe can only be found on App Path
 
2281
        self.overrideEnv('PATH', '')
 
2282
        # Internt Explorer is always registered in the App Path
 
2283
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2162
2284
 
2163
2285
    def test_other(self):
2164
2286
        if sys.platform == 'win32':
2166
2288
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2167
2289
        self.assertTrue(
2168
2290
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
 
2291
 
 
2292
 
 
2293
class TestEnvironmentErrors(tests.TestCase):
 
2294
    """Test handling of environmental errors"""
 
2295
 
 
2296
    def test_is_oserror(self):
 
2297
        self.assertTrue(osutils.is_environment_error(
 
2298
            OSError(errno.EINVAL, "Invalid parameter")))
 
2299
 
 
2300
    def test_is_ioerror(self):
 
2301
        self.assertTrue(osutils.is_environment_error(
 
2302
            IOError(errno.EINVAL, "Invalid parameter")))
 
2303
 
 
2304
    def test_is_socket_error(self):
 
2305
        self.assertTrue(osutils.is_environment_error(
 
2306
            socket.error(errno.EINVAL, "Invalid parameter")))
 
2307
 
 
2308
    def test_is_select_error(self):
 
2309
        self.assertTrue(osutils.is_environment_error(
 
2310
            select.error(errno.EINVAL, "Invalid parameter")))
 
2311
 
 
2312
    def test_is_pywintypes_error(self):
 
2313
        self.requireFeature(features.pywintypes)
 
2314
        import pywintypes
 
2315
        self.assertTrue(osutils.is_environment_error(
 
2316
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))