~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: 2010-06-28 01:45:12 UTC
  • mfrom: (5320.1.1 statictuple-sizeof)
  • Revision ID: pqm@pqm.ubuntu.com-20100628014512-l4w7dmgpmt1pj5c4
(spiv) Implement __sizeof__ in StaticTuple. (Andrew Bennetts)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
import os
22
22
import re
23
23
import socket
 
24
import stat
24
25
import sys
25
26
import time
26
27
 
27
28
from bzrlib import (
28
29
    errors,
29
 
    lazy_regex,
30
30
    osutils,
31
 
    symbol_versioning,
32
31
    tests,
33
32
    trace,
34
33
    win32utils,
38
37
    file_utils,
39
38
    test__walkdirs_win32,
40
39
    )
41
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
 
 
43
 
 
44
 
class _UTF8DirReaderFeature(features.Feature):
 
40
 
 
41
 
 
42
class _UTF8DirReaderFeature(tests.Feature):
45
43
 
46
44
    def _probe(self):
47
45
        try:
54
52
    def feature_name(self):
55
53
        return 'bzrlib._readdir_pyx'
56
54
 
57
 
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
 
55
UTF8DirReaderFeature = _UTF8DirReaderFeature()
58
56
 
59
 
term_ios_feature = features.ModuleAvailableFeature('termios')
 
57
term_ios_feature = tests.ModuleAvailableFeature('termios')
60
58
 
61
59
 
62
60
def _already_unicode(s):
97
95
    return scenarios
98
96
 
99
97
 
100
 
load_tests = load_tests_apply_scenarios
 
98
def load_tests(basic_tests, module, loader):
 
99
    suite = loader.suiteClass()
 
100
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
 
101
        basic_tests, tests.condition_isinstance(TestDirReader))
 
102
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
 
103
    suite.addTest(remaining_tests)
 
104
    return suite
101
105
 
102
106
 
103
107
class TestContainsWhitespace(tests.TestCase):
104
108
 
105
109
    def test_contains_whitespace(self):
106
 
        self.assertTrue(osutils.contains_whitespace(u' '))
107
 
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
108
 
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
109
 
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
110
 
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
111
 
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
 
110
        self.failUnless(osutils.contains_whitespace(u' '))
 
111
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
112
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
113
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
114
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
115
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
112
116
 
113
117
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
114
118
        # is whitespace, but we do not.
115
 
        self.assertFalse(osutils.contains_whitespace(u''))
116
 
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
117
 
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
 
119
        self.failIf(osutils.contains_whitespace(u''))
 
120
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
121
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
118
122
 
119
123
 
120
124
class TestRename(tests.TestCaseInTempDir):
134
138
        # This should work everywhere
135
139
        self.create_file('a', 'something in a\n')
136
140
        self._fancy_rename('a', 'b')
137
 
        self.assertPathDoesNotExist('a')
138
 
        self.assertPathExists('b')
 
141
        self.failIfExists('a')
 
142
        self.failUnlessExists('b')
139
143
        self.check_file_contents('b', 'something in a\n')
140
144
 
141
145
        self.create_file('a', 'new something in a\n')
148
152
        self.create_file('target', 'data in target\n')
149
153
        self.assertRaises((IOError, OSError), self._fancy_rename,
150
154
                          'missingsource', 'target')
151
 
        self.assertPathExists('target')
 
155
        self.failUnlessExists('target')
152
156
        self.check_file_contents('target', 'data in target\n')
153
157
 
154
158
    def test_fancy_rename_fails_if_source_and_target_missing(self):
159
163
        # Rename should be semi-atomic on all platforms
160
164
        self.create_file('a', 'something in a\n')
161
165
        osutils.rename('a', 'b')
162
 
        self.assertPathDoesNotExist('a')
163
 
        self.assertPathExists('b')
 
166
        self.failIfExists('a')
 
167
        self.failUnlessExists('b')
164
168
        self.check_file_contents('b', 'something in a\n')
165
169
 
166
170
        self.create_file('a', 'new something in a\n')
231
235
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
232
236
 
233
237
 
234
 
class TestLstat(tests.TestCaseInTempDir):
235
 
 
236
 
    def test_lstat_matches_fstat(self):
237
 
        # On Windows, lstat and fstat don't always agree, primarily in the
238
 
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
239
 
        # custom implementation.
240
 
        if sys.platform == 'win32':
241
 
            # We only have special lstat/fstat if we have the extension.
242
 
            # Without it, we may end up re-reading content when we don't have
243
 
            # to, but otherwise it doesn't effect correctness.
244
 
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
245
 
        f = open('test-file.txt', 'wb')
246
 
        self.addCleanup(f.close)
247
 
        f.write('some content\n')
248
 
        f.flush()
249
 
        self.assertEqualStat(osutils.fstat(f.fileno()),
250
 
                             osutils.lstat('test-file.txt'))
251
 
 
252
 
 
253
238
class TestRmTree(tests.TestCaseInTempDir):
254
239
 
255
240
    def test_rmtree(self):
267
252
 
268
253
        osutils.rmtree('dir')
269
254
 
270
 
        self.assertPathDoesNotExist('dir/file')
271
 
        self.assertPathDoesNotExist('dir')
 
255
        self.failIfExists('dir/file')
 
256
        self.failIfExists('dir')
272
257
 
273
258
 
274
259
class TestDeleteAny(tests.TestCaseInTempDir):
429
414
class TestLinks(tests.TestCaseInTempDir):
430
415
 
431
416
    def test_dereference_path(self):
432
 
        self.requireFeature(features.SymlinkFeature)
 
417
        self.requireFeature(tests.SymlinkFeature)
433
418
        cwd = osutils.realpath('.')
434
419
        os.mkdir('bar')
435
420
        bar_path = osutils.pathjoin(cwd, 'bar')
482
467
 
483
468
class TestCanonicalRelPath(tests.TestCaseInTempDir):
484
469
 
485
 
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
 
470
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
486
471
 
487
472
    def test_canonical_relpath_simple(self):
488
473
        f = file('MixedCaseName', 'w')
489
474
        f.close()
490
475
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
491
 
        self.assertEqual('work/MixedCaseName', actual)
 
476
        self.failUnlessEqual('work/MixedCaseName', actual)
492
477
 
493
478
    def test_canonical_relpath_missing_tail(self):
494
479
        os.mkdir('MixedCaseParent')
495
480
        actual = osutils.canonical_relpath(self.test_base_dir,
496
481
                                           'mixedcaseparent/nochild')
497
 
        self.assertEqual('work/MixedCaseParent/nochild', actual)
 
482
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
498
483
 
499
484
 
500
485
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
876
861
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
877
862
        # relative path
878
863
        cwd = osutils.getcwd().rstrip('/')
879
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
864
        drive = osutils._nt_splitdrive(cwd)[0]
880
865
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
881
866
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
882
867
        # unicode path
888
873
    """Test win32 functions that create files."""
889
874
 
890
875
    def test_getcwd(self):
891
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
876
        self.requireFeature(tests.UnicodeFilenameFeature)
892
877
        os.mkdir(u'mu-\xb5')
893
878
        os.chdir(u'mu-\xb5')
894
879
        # TODO: jam 20060427 This will probably fail on Mac OSX because
924
909
        b.close()
925
910
 
926
911
        osutils._win32_rename('b', 'a')
927
 
        self.assertPathExists('a')
928
 
        self.assertPathDoesNotExist('b')
 
912
        self.failUnlessExists('a')
 
913
        self.failIfExists('b')
929
914
        self.assertFileEqual('baz\n', 'a')
930
915
 
931
916
    def test_rename_missing_file(self):
984
969
    """Test mac special functions that require directories."""
985
970
 
986
971
    def test_getcwd(self):
987
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
972
        self.requireFeature(tests.UnicodeFilenameFeature)
988
973
        os.mkdir(u'B\xe5gfors')
989
974
        os.chdir(u'B\xe5gfors')
990
975
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
991
976
 
992
977
    def test_getcwd_nonnorm(self):
993
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
978
        self.requireFeature(tests.UnicodeFilenameFeature)
994
979
        # Test that _mac_getcwd() will normalize this path
995
980
        os.mkdir(u'Ba\u030agfors')
996
981
        os.chdir(u'Ba\u030agfors')
1085
1070
        if sys.platform == 'win32':
1086
1071
            raise tests.TestNotApplicable(
1087
1072
                "readdir IOError not tested on win32")
1088
 
        self.requireFeature(features.not_running_as_root)
1089
1073
        os.mkdir("test-unreadable")
1090
1074
        os.chmod("test-unreadable", 0000)
1091
1075
        # must chmod it back so that it can be removed
1106
1090
        # are not using the filesystem's encoding
1107
1091
 
1108
1092
        # require a bytestring based filesystem
1109
 
        self.requireFeature(features.ByteStringNamedFilesystem)
 
1093
        self.requireFeature(tests.ByteStringNamedFilesystem)
1110
1094
 
1111
1095
        tree = [
1112
1096
            '.bzr',
1121
1105
 
1122
1106
        # rename the 1file to a latin-1 filename
1123
1107
        os.rename("./1file", "\xe8file")
1124
 
        if "\xe8file" not in os.listdir("."):
1125
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1126
1108
 
1127
1109
        self._save_platform_info()
1128
1110
        win32utils.winver = None # Avoid the win32 detection code
1207
1189
        self._save_platform_info()
1208
1190
        win32utils.winver = None # Avoid the win32 detection code
1209
1191
        osutils._fs_enc = 'UTF-8'
1210
 
        self.assertDirReaderIs(
1211
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
1192
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1212
1193
 
1213
1194
    def test_force_walkdirs_utf8_fs_ascii(self):
1214
1195
        self.requireFeature(UTF8DirReaderFeature)
1215
1196
        self._save_platform_info()
1216
1197
        win32utils.winver = None # Avoid the win32 detection code
1217
1198
        osutils._fs_enc = 'US-ASCII'
1218
 
        self.assertDirReaderIs(
1219
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
1199
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1220
1200
 
1221
1201
    def test_force_walkdirs_utf8_fs_ANSI(self):
1222
1202
        self.requireFeature(UTF8DirReaderFeature)
1223
1203
        self._save_platform_info()
1224
1204
        win32utils.winver = None # Avoid the win32 detection code
1225
1205
        osutils._fs_enc = 'ANSI_X3.4-1968'
1226
 
        self.assertDirReaderIs(
1227
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
1206
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
1228
1207
 
1229
1208
    def test_force_walkdirs_utf8_fs_latin1(self):
1230
1209
        self._save_platform_info()
1248
1227
 
1249
1228
    def test_unicode_walkdirs(self):
1250
1229
        """Walkdirs should always return unicode paths."""
1251
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1230
        self.requireFeature(tests.UnicodeFilenameFeature)
1252
1231
        name0 = u'0file-\xb6'
1253
1232
        name1 = u'1dir-\u062c\u0648'
1254
1233
        name2 = u'2file-\u0633'
1291
1270
 
1292
1271
        The abspath portion might be in unicode or utf-8
1293
1272
        """
1294
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1273
        self.requireFeature(tests.UnicodeFilenameFeature)
1295
1274
        name0 = u'0file-\xb6'
1296
1275
        name1 = u'1dir-\u062c\u0648'
1297
1276
        name2 = u'2file-\u0633'
1352
1331
 
1353
1332
        The abspath portion should be in unicode
1354
1333
        """
1355
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1334
        self.requireFeature(tests.UnicodeFilenameFeature)
1356
1335
        # Use the unicode reader. TODO: split into driver-and-driven unit
1357
1336
        # tests.
1358
1337
        self._save_platform_info()
1399
1378
 
1400
1379
    def test__walkdirs_utf8_win32readdir(self):
1401
1380
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1402
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1381
        self.requireFeature(tests.UnicodeFilenameFeature)
1403
1382
        from bzrlib._walkdirs_win32 import Win32ReadDir
1404
1383
        self._save_platform_info()
1405
1384
        osutils._selected_dir_reader = Win32ReadDir()
1456
1435
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1457
1436
        """make sure our Stat values are valid"""
1458
1437
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1459
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1438
        self.requireFeature(tests.UnicodeFilenameFeature)
1460
1439
        from bzrlib._walkdirs_win32 import Win32ReadDir
1461
1440
        name0u = u'0file-\xb6'
1462
1441
        name0 = name0u.encode('utf8')
1480
1459
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1481
1460
        """make sure our Stat values are valid"""
1482
1461
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1483
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1462
        self.requireFeature(tests.UnicodeFilenameFeature)
1484
1463
        from bzrlib._walkdirs_win32 import Win32ReadDir
1485
1464
        name0u = u'0dir-\u062c\u0648'
1486
1465
        name0 = name0u.encode('utf8')
1586
1565
        self.assertEqual(['c'], os.listdir('target/b'))
1587
1566
 
1588
1567
    def test_copy_tree_symlinks(self):
1589
 
        self.requireFeature(features.SymlinkFeature)
 
1568
        self.requireFeature(tests.SymlinkFeature)
1590
1569
        self.build_tree(['source/'])
1591
1570
        os.symlink('a/generic/path', 'source/lnk')
1592
1571
        osutils.copy_tree('source', 'target')
1617
1596
                          ('d', 'source/b', 'target/b'),
1618
1597
                          ('f', 'source/b/c', 'target/b/c'),
1619
1598
                         ], processed_files)
1620
 
        self.assertPathDoesNotExist('target')
 
1599
        self.failIfExists('target')
1621
1600
        if osutils.has_symlinks():
1622
1601
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1623
1602
 
1669
1648
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1670
1649
        self.assertEqual('foo', old)
1671
1650
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1672
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
 
1651
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1673
1652
 
1674
1653
 
1675
1654
class TestSizeShaFile(tests.TestCaseInTempDir):
1726
1705
 
1727
1706
class TestReCompile(tests.TestCase):
1728
1707
 
1729
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1730
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1731
 
            osutils.re_compile_checked, *args, **kwargs)
1732
 
 
1733
1708
    def test_re_compile_checked(self):
1734
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1709
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1735
1710
        self.assertTrue(r.match('aaaa'))
1736
1711
        self.assertTrue(r.match('aAaA'))
1737
1712
 
1738
1713
    def test_re_compile_checked_error(self):
1739
1714
        # like https://bugs.launchpad.net/bzr/+bug/251352
1740
 
 
1741
 
        # Due to possible test isolation error, re.compile is not lazy at
1742
 
        # this point. We re-install lazy compile.
1743
 
        lazy_regex.install_lazy_compile()
1744
1715
        err = self.assertRaises(
1745
1716
            errors.BzrCommandError,
1746
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1717
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1747
1718
        self.assertEqual(
1748
 
            'Invalid regular expression in test case: '
1749
 
            '"*" nothing to repeat',
 
1719
            "Invalid regular expression in test case: '*': "
 
1720
            "nothing to repeat",
1750
1721
            str(err))
1751
1722
 
1752
1723
 
1753
1724
class TestDirReader(tests.TestCaseInTempDir):
1754
1725
 
1755
 
    scenarios = dir_reader_scenarios()
1756
 
 
1757
1726
    # Set by load_tests
1758
1727
    _dir_reader_class = None
1759
1728
    _native_to_unicode = None
1859
1828
        return filtered_dirblocks
1860
1829
 
1861
1830
    def test_walk_unicode_tree(self):
1862
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1831
        self.requireFeature(tests.UnicodeFilenameFeature)
1863
1832
        tree, expected_dirblocks = self._get_unicode_tree()
1864
1833
        self.build_tree(tree)
1865
1834
        result = list(osutils._walkdirs_utf8('.'))
1866
1835
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1867
1836
 
1868
1837
    def test_symlink(self):
1869
 
        self.requireFeature(features.SymlinkFeature)
1870
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1838
        self.requireFeature(tests.SymlinkFeature)
 
1839
        self.requireFeature(tests.UnicodeFilenameFeature)
1871
1840
        target = u'target\N{Euro Sign}'
1872
1841
        link_name = u'l\N{Euro Sign}nk'
1873
1842
        os.symlink(target, link_name)
1891
1860
    But prior python versions failed to properly encode the passed unicode
1892
1861
    string.
1893
1862
    """
1894
 
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
 
1863
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
1895
1864
 
1896
1865
    def setUp(self):
1897
1866
        super(tests.TestCaseInTempDir, self).setUp()
1900
1869
        os.symlink(self.target, self.link)
1901
1870
 
1902
1871
    def test_os_readlink_link_encoding(self):
1903
 
        self.assertEquals(self.target,  os.readlink(self.link))
 
1872
        if sys.version_info < (2, 6):
 
1873
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
 
1874
        else:
 
1875
            self.assertEquals(self.target,  os.readlink(self.link))
1904
1876
 
1905
1877
    def test_os_readlink_link_decoding(self):
1906
1878
        self.assertEquals(self.target.encode(osutils._fs_enc),
1918
1890
        self.assertIsInstance(concurrency, int)
1919
1891
 
1920
1892
    def test_local_concurrency_environment_variable(self):
1921
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
 
1893
        os.environ['BZR_CONCURRENCY'] = '2'
1922
1894
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1923
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
 
1895
        os.environ['BZR_CONCURRENCY'] = '3'
1924
1896
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1925
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
 
1897
        os.environ['BZR_CONCURRENCY'] = 'foo'
1926
1898
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1927
1899
 
1928
1900
    def test_option_concurrency(self):
1929
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
 
1901
        os.environ['BZR_CONCURRENCY'] = '1'
1930
1902
        self.run_bzr('rocks --concurrency 42')
1931
 
        # Command line overrides environment variable
 
1903
        # Command line overrides envrionment variable
1932
1904
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1933
1905
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1934
1906
 
2004
1976
    def test_defaults_to_BZR_COLUMNS(self):
2005
1977
        # BZR_COLUMNS is set by the test framework
2006
1978
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2007
 
        self.overrideEnv('BZR_COLUMNS', '12')
 
1979
        os.environ['BZR_COLUMNS'] = '12'
2008
1980
        self.assertEqual(12, osutils.terminal_width())
2009
1981
 
2010
 
    def test_BZR_COLUMNS_0_no_limit(self):
2011
 
        self.overrideEnv('BZR_COLUMNS', '0')
2012
 
        self.assertEqual(None, osutils.terminal_width())
2013
 
 
2014
1982
    def test_falls_back_to_COLUMNS(self):
2015
 
        self.overrideEnv('BZR_COLUMNS', None)
 
1983
        del os.environ['BZR_COLUMNS']
2016
1984
        self.assertNotEqual('42', os.environ['COLUMNS'])
2017
1985
        self.set_fake_tty()
2018
 
        self.overrideEnv('COLUMNS', '42')
 
1986
        os.environ['COLUMNS'] = '42'
2019
1987
        self.assertEqual(42, osutils.terminal_width())
2020
1988
 
2021
1989
    def test_tty_default_without_columns(self):
2022
 
        self.overrideEnv('BZR_COLUMNS', None)
2023
 
        self.overrideEnv('COLUMNS', None)
 
1990
        del os.environ['BZR_COLUMNS']
 
1991
        del os.environ['COLUMNS']
2024
1992
 
2025
1993
        def terminal_size(w, h):
2026
1994
            return 42, 42
2033
2001
        self.assertEqual(42, osutils.terminal_width())
2034
2002
 
2035
2003
    def test_non_tty_default_without_columns(self):
2036
 
        self.overrideEnv('BZR_COLUMNS', None)
2037
 
        self.overrideEnv('COLUMNS', None)
 
2004
        del os.environ['BZR_COLUMNS']
 
2005
        del os.environ['COLUMNS']
2038
2006
        self.replace_stdout(None)
2039
2007
        self.assertEqual(None, osutils.terminal_width())
2040
2008
 
2050
2018
        else:
2051
2019
            self.overrideAttr(termios, 'TIOCGWINSZ')
2052
2020
            del termios.TIOCGWINSZ
2053
 
        self.overrideEnv('BZR_COLUMNS', None)
2054
 
        self.overrideEnv('COLUMNS', None)
 
2021
        del os.environ['BZR_COLUMNS']
 
2022
        del os.environ['COLUMNS']
2055
2023
        # Whatever the result is, if we don't raise an exception, it's ok.
2056
2024
        osutils.terminal_width()
2057
2025
 
2058
 
 
2059
2026
class TestCreationOps(tests.TestCaseInTempDir):
2060
2027
    _test_needs_features = [features.chown_feature]
2061
2028
 
2091
2058
        self.assertEquals(self.uid, s.st_uid)
2092
2059
        self.assertEquals(self.gid, s.st_gid)
2093
2060
 
2094
 
 
2095
2061
class TestGetuserUnicode(tests.TestCase):
2096
2062
 
2097
2063
    def test_ascii_user(self):
2098
 
        self.overrideEnv('LOGNAME', 'jrandom')
 
2064
        osutils.set_or_unset_env('LOGNAME', 'jrandom')
2099
2065
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2100
2066
 
2101
2067
    def test_unicode_user(self):
2102
2068
        ue = osutils.get_user_encoding()
2103
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2104
 
        if uni_val is None:
2105
 
            raise tests.TestSkipped(
2106
 
                'Cannot find a unicode character that works in encoding %s'
2107
 
                % (osutils.get_user_encoding(),))
2108
 
        uni_username = u'jrandom' + uni_val
2109
 
        encoded_username = uni_username.encode(ue)
2110
 
        self.overrideEnv('LOGNAME', encoded_username)
2111
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2112
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
 
2069
        osutils.set_or_unset_env('LOGNAME', u'jrandom\xb6'.encode(ue))
2113
2070
        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())
2120
 
 
2121
 
 
2122
 
class TestBackupNames(tests.TestCase):
2123
 
 
2124
 
    def setUp(self):
2125
 
        super(TestBackupNames, self).setUp()
2126
 
        self.backups = []
2127
 
 
2128
 
    def backup_exists(self, name):
2129
 
        return name in self.backups
2130
 
 
2131
 
    def available_backup_name(self, name):
2132
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2133
 
        self.backups.append(backup_name)
2134
 
        return backup_name
2135
 
 
2136
 
    def assertBackupName(self, expected, name):
2137
 
        self.assertEqual(expected, self.available_backup_name(name))
2138
 
 
2139
 
    def test_empty(self):
2140
 
        self.assertBackupName('file.~1~', 'file')
2141
 
 
2142
 
    def test_existing(self):
2143
 
        self.available_backup_name('file')
2144
 
        self.available_backup_name('file')
2145
 
        self.assertBackupName('file.~3~', 'file')
2146
 
        # Empty slots are found, this is not a strict requirement and may be
2147
 
        # revisited if we test against all implementations.
2148
 
        self.backups.remove('file.~2~')
2149
 
        self.assertBackupName('file.~2~', 'file')
2150
 
 
2151
 
 
2152
 
class TestFindExecutableInPath(tests.TestCase):
2153
 
 
2154
 
    def test_windows(self):
2155
 
        if sys.platform != 'win32':
2156
 
            raise tests.TestSkipped('test requires win32')
2157
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2158
 
        self.assertTrue(
2159
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2160
 
        self.assertTrue(
2161
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2162
 
        self.assertTrue(
2163
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2164
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2165
 
 
2166
 
    def test_other(self):
2167
 
        if sys.platform == 'win32':
2168
 
            raise tests.TestSkipped('test requires non-win32')
2169
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2170
 
        self.assertTrue(
2171
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)