~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-08-17 18:13:57 UTC
  • mfrom: (5268.7.29 transport-segments)
  • Revision ID: pqm@pqm.ubuntu.com-20110817181357-y5q5eth1hk8bl3om
(jelmer) Allow specifying the colocated branch to use in the branch URL,
 and retrieving the branch name using ControlDir._get_selected_branch.
 (Jelmer Vernooij)

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
24
23
import socket
25
24
import sys
26
 
import tempfile
27
25
import time
28
26
 
29
27
from bzrlib import (
182
180
        shape = sorted(os.listdir('.'))
183
181
        self.assertEquals(['A', 'B'], shape)
184
182
 
185
 
    def test_rename_exception(self):
186
 
        try:
187
 
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
188
 
        except OSError, e:
189
 
            self.assertEqual(e.old_filename, 'nonexistent_path')
190
 
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
191
 
            self.assertTrue('nonexistent_path' in e.strerror)
192
 
            self.assertTrue('different_nonexistent_path' in e.strerror)
193
 
 
194
183
 
195
184
class TestRandChars(tests.TestCase):
196
185
 
437
426
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
438
427
 
439
428
 
440
 
class TestFdatasync(tests.TestCaseInTempDir):
441
 
 
442
 
    def do_fdatasync(self):
443
 
        f = tempfile.NamedTemporaryFile()
444
 
        osutils.fdatasync(f.fileno())
445
 
        f.close()
446
 
 
447
 
    @staticmethod
448
 
    def raise_eopnotsupp(*args, **kwargs):
449
 
        raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
450
 
 
451
 
    @staticmethod
452
 
    def raise_enotsup(*args, **kwargs):
453
 
        raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
454
 
 
455
 
    def test_fdatasync_handles_system_function(self):
456
 
        self.overrideAttr(os, "fdatasync")
457
 
        self.do_fdatasync()
458
 
 
459
 
    def test_fdatasync_handles_no_fdatasync_no_fsync(self):
460
 
        self.overrideAttr(os, "fdatasync")
461
 
        self.overrideAttr(os, "fsync")
462
 
        self.do_fdatasync()
463
 
 
464
 
    def test_fdatasync_handles_no_EOPNOTSUPP(self):
465
 
        self.overrideAttr(errno, "EOPNOTSUPP")
466
 
        self.do_fdatasync()
467
 
 
468
 
    def test_fdatasync_catches_ENOTSUP(self):
469
 
        enotsup = getattr(errno, "ENOTSUP", None)
470
 
        if enotsup is None:
471
 
            raise tests.TestNotApplicable("No ENOTSUP on this platform")
472
 
        self.overrideAttr(os, "fdatasync", self.raise_enotsup)
473
 
        self.do_fdatasync()
474
 
 
475
 
    def test_fdatasync_catches_EOPNOTSUPP(self):
476
 
        enotsup = getattr(errno, "EOPNOTSUPP", None)
477
 
        if enotsup is None:
478
 
            raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
479
 
        self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
480
 
        self.do_fdatasync()
481
 
 
482
 
 
483
429
class TestLinks(tests.TestCaseInTempDir):
484
430
 
485
431
    def test_dereference_path(self):
598
544
    """Test pumpfile method."""
599
545
 
600
546
    def setUp(self):
601
 
        super(TestPumpFile, self).setUp()
 
547
        tests.TestCase.setUp(self)
602
548
        # create a test datablock
603
549
        self.block_size = 512
604
550
        pattern = '0123456789ABCDEF'
872
818
        self.assertEqual(None, osutils.safe_file_id(None))
873
819
 
874
820
 
875
 
class TestSendAll(tests.TestCase):
876
 
 
877
 
    def test_send_with_disconnected_socket(self):
878
 
        class DisconnectedSocket(object):
879
 
            def __init__(self, err):
880
 
                self.err = err
881
 
            def send(self, content):
882
 
                raise self.err
883
 
            def close(self):
884
 
                pass
885
 
        # All of these should be treated as ConnectionReset
886
 
        errs = []
887
 
        for err_cls in (IOError, socket.error):
888
 
            for errnum in osutils._end_of_stream_errors:
889
 
                errs.append(err_cls(errnum))
890
 
        for err in errs:
891
 
            sock = DisconnectedSocket(err)
892
 
            self.assertRaises(errors.ConnectionReset,
893
 
                osutils.send_all, sock, 'some more content')
894
 
 
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):
900
 
            def __init__(self):
901
 
                self.call_count = 0
902
 
            def send(self, bytes):
903
 
                self.call_count += 1
904
 
                if self.call_count > 100:
905
 
                    # Prevent the test suite from hanging
906
 
                    raise RuntimeError('too many calls')
907
 
                return 0
908
 
        sock = NoSendingSocket()
909
 
        self.assertRaises(errors.ConnectionReset,
910
 
                          osutils.send_all, sock, 'content')
911
 
        self.assertEqual(1, sock.call_count)
912
 
 
913
 
 
914
 
class TestPosixFuncs(tests.TestCase):
915
 
    """Test that the posix version of normpath returns an appropriate path
916
 
       when used with 2 leading slashes."""
917
 
 
918
 
    def test_normpath(self):
919
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
920
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
921
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
922
 
 
923
 
 
924
821
class TestWin32Funcs(tests.TestCase):
925
822
    """Test that _win32 versions of os utilities return appropriate paths."""
926
823
 
1309
1206
        self.requireFeature(UTF8DirReaderFeature)
1310
1207
        self._save_platform_info()
1311
1208
        win32utils.winver = None # Avoid the win32 detection code
1312
 
        osutils._fs_enc = 'utf-8'
 
1209
        osutils._fs_enc = 'UTF-8'
1313
1210
        self.assertDirReaderIs(
1314
1211
            UTF8DirReaderFeature.module.UTF8DirReader)
1315
1212
 
1317
1214
        self.requireFeature(UTF8DirReaderFeature)
1318
1215
        self._save_platform_info()
1319
1216
        win32utils.winver = None # Avoid the win32 detection code
1320
 
        osutils._fs_enc = 'ascii'
 
1217
        osutils._fs_enc = 'US-ASCII'
 
1218
        self.assertDirReaderIs(
 
1219
            UTF8DirReaderFeature.module.UTF8DirReader)
 
1220
 
 
1221
    def test_force_walkdirs_utf8_fs_ANSI(self):
 
1222
        self.requireFeature(UTF8DirReaderFeature)
 
1223
        self._save_platform_info()
 
1224
        win32utils.winver = None # Avoid the win32 detection code
 
1225
        osutils._fs_enc = 'ANSI_X3.4-1968'
1321
1226
        self.assertDirReaderIs(
1322
1227
            UTF8DirReaderFeature.module.UTF8DirReader)
1323
1228
 
1324
1229
    def test_force_walkdirs_utf8_fs_latin1(self):
1325
1230
        self._save_platform_info()
1326
1231
        win32utils.winver = None # Avoid the win32 detection code
1327
 
        osutils._fs_enc = 'iso-8859-1'
 
1232
        osutils._fs_enc = 'latin1'
1328
1233
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1329
1234
 
1330
1235
    def test_force_walkdirs_utf8_nt(self):
1854
1759
    _native_to_unicode = None
1855
1760
 
1856
1761
    def setUp(self):
1857
 
        super(TestDirReader, self).setUp()
 
1762
        tests.TestCaseInTempDir.setUp(self)
1858
1763
        self.overrideAttr(osutils,
1859
1764
                          '_selected_dir_reader', self._dir_reader_class())
1860
1765
 
2068
1973
class TestTerminalWidth(tests.TestCase):
2069
1974
 
2070
1975
    def setUp(self):
2071
 
        super(TestTerminalWidth, self).setUp()
 
1976
        tests.TestCase.setUp(self)
2072
1977
        self._orig_terminal_size_state = osutils._terminal_size_state
2073
1978
        self._orig_first_terminal_size = osutils._first_terminal_size
2074
1979
        self.addCleanup(self.restore_osutils_globals)
2155
2060
    _test_needs_features = [features.chown_feature]
2156
2061
 
2157
2062
    def setUp(self):
2158
 
        super(TestCreationOps, self).setUp()
 
2063
        tests.TestCaseInTempDir.setUp(self)
2159
2064
        self.overrideAttr(os, 'chown', self._dummy_chown)
2160
2065
 
2161
2066
        # params set by call to _dummy_chown
2187
2092
        self.assertEquals(self.gid, s.st_gid)
2188
2093
 
2189
2094
 
2190
 
class TestPathFromEnviron(tests.TestCase):
2191
 
 
2192
 
    def test_is_unicode(self):
2193
 
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
2194
 
        path = osutils.path_from_environ('BZR_TEST_PATH')
2195
 
        self.assertIsInstance(path, unicode)
2196
 
        self.assertEqual(u'./anywhere at all/', path)
2197
 
 
2198
 
    def test_posix_path_env_ascii(self):
2199
 
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
2200
 
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
2201
 
        self.assertIsInstance(home, unicode)
2202
 
        self.assertEqual(u'/tmp', home)
2203
 
 
2204
 
    def test_posix_path_env_unicode(self):
2205
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2206
 
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
2207
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2208
 
        self.assertEqual(u'/home/\xa7test',
2209
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2210
 
        osutils._fs_enc = "iso8859-5"
2211
 
        self.assertEqual(u'/home/\u0407test',
2212
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2213
 
        osutils._fs_enc = "utf-8"
2214
 
        self.assertRaises(errors.BadFilenameEncoding,
2215
 
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
2216
 
 
2217
 
 
2218
 
class TestGetHomeDir(tests.TestCase):
2219
 
 
2220
 
    def test_is_unicode(self):
2221
 
        home = osutils._get_home_dir()
2222
 
        self.assertIsInstance(home, unicode)
2223
 
 
2224
 
    def test_posix_homeless(self):
2225
 
        self.overrideEnv('HOME', None)
2226
 
        home = osutils._get_home_dir()
2227
 
        self.assertIsInstance(home, unicode)
2228
 
 
2229
 
    def test_posix_home_ascii(self):
2230
 
        self.overrideEnv('HOME', '/home/test')
2231
 
        home = osutils._posix_get_home_dir()
2232
 
        self.assertIsInstance(home, unicode)
2233
 
        self.assertEqual(u'/home/test', home)
2234
 
 
2235
 
    def test_posix_home_unicode(self):
2236
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2237
 
        self.overrideEnv('HOME', '/home/\xa7test')
2238
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2239
 
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2240
 
        osutils._fs_enc = "iso8859-5"
2241
 
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
2242
 
        osutils._fs_enc = "utf-8"
2243
 
        self.assertRaises(errors.BadFilenameEncoding,
2244
 
            osutils._posix_get_home_dir)
2245
 
 
2246
 
 
2247
2095
class TestGetuserUnicode(tests.TestCase):
2248
2096
 
2249
 
    def test_is_unicode(self):
2250
 
        user = osutils.getuser_unicode()
2251
 
        self.assertIsInstance(user, unicode)
2252
 
 
2253
 
    def envvar_to_override(self):
2254
 
        if sys.platform == "win32":
2255
 
            # Disable use of platform calls on windows so envvar is used
2256
 
            self.overrideAttr(win32utils, 'has_ctypes', False)
2257
 
            return 'USERNAME' # only variable used on windows
2258
 
        return 'LOGNAME' # first variable checked by getpass.getuser()
2259
 
 
2260
2097
    def test_ascii_user(self):
2261
 
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
 
2098
        self.overrideEnv('LOGNAME', 'jrandom')
2262
2099
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2263
2100
 
2264
2101
    def test_unicode_user(self):
2270
2107
                % (osutils.get_user_encoding(),))
2271
2108
        uni_username = u'jrandom' + uni_val
2272
2109
        encoded_username = uni_username.encode(ue)
2273
 
        self.overrideEnv(self.envvar_to_override(), encoded_username)
 
2110
        self.overrideEnv('LOGNAME', encoded_username)
2274
2111
        self.assertEqual(uni_username, osutils.getuser_unicode())
 
2112
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
 
2113
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
 
2114
 
 
2115
    def test_no_username_bug_660174(self):
 
2116
        self.requireFeature(features.win32_feature)
 
2117
        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
 
2118
            self.overrideEnv(name, None)
 
2119
        self.assertEqual(u'UNKNOWN', osutils.getuser_unicode())
2275
2120
 
2276
2121
 
2277
2122
class TestBackupNames(tests.TestCase):
2317
2162
        self.assertTrue(
2318
2163
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2319
2164
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2320
 
        
2321
 
    def test_windows_app_path(self):
2322
 
        if sys.platform != 'win32':
2323
 
            raise tests.TestSkipped('test requires win32')
2324
 
        # Override PATH env var so that exe can only be found on App Path
2325
 
        self.overrideEnv('PATH', '')
2326
 
        # Internt Explorer is always registered in the App Path
2327
 
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2328
2165
 
2329
2166
    def test_other(self):
2330
2167
        if sys.platform == 'win32':
2332
2169
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2333
2170
        self.assertTrue(
2334
2171
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2335
 
 
2336
 
 
2337
 
class TestEnvironmentErrors(tests.TestCase):
2338
 
    """Test handling of environmental errors"""
2339
 
 
2340
 
    def test_is_oserror(self):
2341
 
        self.assertTrue(osutils.is_environment_error(
2342
 
            OSError(errno.EINVAL, "Invalid parameter")))
2343
 
 
2344
 
    def test_is_ioerror(self):
2345
 
        self.assertTrue(osutils.is_environment_error(
2346
 
            IOError(errno.EINVAL, "Invalid parameter")))
2347
 
 
2348
 
    def test_is_socket_error(self):
2349
 
        self.assertTrue(osutils.is_environment_error(
2350
 
            socket.error(errno.EINVAL, "Invalid parameter")))
2351
 
 
2352
 
    def test_is_select_error(self):
2353
 
        self.assertTrue(osutils.is_environment_error(
2354
 
            select.error(errno.EINVAL, "Invalid parameter")))
2355
 
 
2356
 
    def test_is_pywintypes_error(self):
2357
 
        self.requireFeature(features.pywintypes)
2358
 
        import pywintypes
2359
 
        self.assertTrue(osutils.is_environment_error(
2360
 
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))