~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: John Arbash Meinel
  • Date: 2009-06-16 13:57:14 UTC
  • mto: This revision was merged to the branch mainline in revision 4449.
  • Revision ID: john@arbash-meinel.com-20090616135714-8o7jdtqqsfuv914z
The new code removes a get_parent_map call.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
 
    trace,
34
32
    win32utils,
35
33
    )
36
34
from bzrlib.tests import (
37
 
    features,
38
35
    file_utils,
39
36
    test__walkdirs_win32,
40
37
    )
55
52
 
56
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
57
54
 
58
 
term_ios_feature = tests.ModuleAvailableFeature('termios')
59
 
 
60
55
 
61
56
def _already_unicode(s):
62
57
    return s
63
58
 
64
59
 
 
60
def _fs_enc_to_unicode(s):
 
61
    return s.decode(osutils._fs_enc)
 
62
 
 
63
 
65
64
def _utf8_to_unicode(s):
66
65
    return s.decode('UTF-8')
67
66
 
84
83
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
85
84
                               _native_to_unicode=_utf8_to_unicode)))
86
85
 
87
 
    if test__walkdirs_win32.win32_readdir_feature.available():
 
86
    if test__walkdirs_win32.Win32ReadDirFeature.available():
88
87
        try:
89
88
            from bzrlib import _walkdirs_win32
 
89
            # TODO: check on windows, it may be that we need to use/add
 
90
            # safe_unicode instead of _fs_enc_to_unicode
90
91
            scenarios.append(
91
92
                ('win32',
92
93
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
93
 
                      _native_to_unicode=_already_unicode)))
 
94
                      _native_to_unicode=_fs_enc_to_unicode)))
94
95
        except ImportError:
95
96
            pass
96
97
    return scenarios
124
125
 
125
126
class TestRename(tests.TestCaseInTempDir):
126
127
 
127
 
    def create_file(self, filename, content):
128
 
        f = open(filename, 'wb')
129
 
        try:
130
 
            f.write(content)
131
 
        finally:
132
 
            f.close()
133
 
 
134
 
    def _fancy_rename(self, a, b):
135
 
        osutils.fancy_rename(a, b, rename_func=os.rename,
136
 
                             unlink_func=os.unlink)
137
 
 
138
128
    def test_fancy_rename(self):
139
129
        # This should work everywhere
140
 
        self.create_file('a', 'something in a\n')
141
 
        self._fancy_rename('a', 'b')
 
130
        def rename(a, b):
 
131
            osutils.fancy_rename(a, b,
 
132
                    rename_func=os.rename,
 
133
                    unlink_func=os.unlink)
 
134
 
 
135
        open('a', 'wb').write('something in a\n')
 
136
        rename('a', 'b')
142
137
        self.failIfExists('a')
143
138
        self.failUnlessExists('b')
144
139
        self.check_file_contents('b', 'something in a\n')
145
140
 
146
 
        self.create_file('a', 'new something in a\n')
147
 
        self._fancy_rename('b', 'a')
 
141
        open('a', 'wb').write('new something in a\n')
 
142
        rename('b', 'a')
148
143
 
149
144
        self.check_file_contents('a', 'something in a\n')
150
145
 
151
 
    def test_fancy_rename_fails_source_missing(self):
152
 
        # An exception should be raised, and the target should be left in place
153
 
        self.create_file('target', 'data in target\n')
154
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
155
 
                          'missingsource', 'target')
156
 
        self.failUnlessExists('target')
157
 
        self.check_file_contents('target', 'data in target\n')
158
 
 
159
 
    def test_fancy_rename_fails_if_source_and_target_missing(self):
160
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
161
 
                          'missingsource', 'missingtarget')
162
 
 
163
146
    def test_rename(self):
164
147
        # Rename should be semi-atomic on all platforms
165
 
        self.create_file('a', 'something in a\n')
 
148
        open('a', 'wb').write('something in a\n')
166
149
        osutils.rename('a', 'b')
167
150
        self.failIfExists('a')
168
151
        self.failUnlessExists('b')
169
152
        self.check_file_contents('b', 'something in a\n')
170
153
 
171
 
        self.create_file('a', 'new something in a\n')
 
154
        open('a', 'wb').write('new something in a\n')
172
155
        osutils.rename('b', 'a')
173
156
 
174
157
        self.check_file_contents('a', 'something in a\n')
257
240
        self.failIfExists('dir')
258
241
 
259
242
 
260
 
class TestDeleteAny(tests.TestCaseInTempDir):
261
 
 
262
 
    def test_delete_any_readonly(self):
263
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
264
 
        self.build_tree(['d/', 'f'])
265
 
        osutils.make_readonly('d')
266
 
        osutils.make_readonly('f')
267
 
 
268
 
        osutils.delete_any('f')
269
 
        osutils.delete_any('d')
270
 
 
271
 
 
272
243
class TestKind(tests.TestCaseInTempDir):
273
244
 
274
245
    def test_file_kind(self):
311
282
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
312
283
        self.assertEqual("@", osutils.kind_marker("symlink"))
313
284
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
314
 
        self.assertEqual("", osutils.kind_marker("fifo"))
315
 
        self.assertEqual("", osutils.kind_marker("socket"))
316
 
        self.assertEqual("", osutils.kind_marker("unknown"))
 
285
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
317
286
 
318
287
 
319
288
class TestUmask(tests.TestCaseInTempDir):
384
353
        # Instead blackbox.test_locale should check for localized
385
354
        # dates once they do occur in output strings.
386
355
 
387
 
    def test_format_date_with_offset_in_original_timezone(self):
388
 
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
389
 
            osutils.format_date_with_offset_in_original_timezone(0))
390
 
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
391
 
            osutils.format_date_with_offset_in_original_timezone(100000))
392
 
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
393
 
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
394
 
 
395
356
    def test_local_time_offset(self):
396
357
        """Test that local_time_offset() returns a sane value."""
397
358
        offset = osutils.local_time_offset()
473
434
    def test_canonical_relpath_simple(self):
474
435
        f = file('MixedCaseName', 'w')
475
436
        f.close()
476
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
 
437
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
438
        real_base_dir = osutils.realpath(self.test_base_dir)
 
439
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
477
440
        self.failUnlessEqual('work/MixedCaseName', actual)
478
441
 
479
442
    def test_canonical_relpath_missing_tail(self):
480
443
        os.mkdir('MixedCaseParent')
481
 
        actual = osutils.canonical_relpath(self.test_base_dir,
 
444
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
445
        real_base_dir = osutils.realpath(self.test_base_dir)
 
446
        actual = osutils.canonical_relpath(real_base_dir,
482
447
                                           'mixedcaseparent/nochild')
483
448
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
484
449
 
485
450
 
486
 
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
487
 
 
488
 
    def assertRelpath(self, expected, base, path):
489
 
        actual = osutils._cicp_canonical_relpath(base, path)
490
 
        self.assertEqual(expected, actual)
491
 
 
492
 
    def test_simple(self):
493
 
        self.build_tree(['MixedCaseName'])
494
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
495
 
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
496
 
 
497
 
    def test_subdir_missing_tail(self):
498
 
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
499
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
500
 
        self.assertRelpath('MixedCaseParent/a_child', base,
501
 
                           'MixedCaseParent/a_child')
502
 
        self.assertRelpath('MixedCaseParent/a_child', base,
503
 
                           'MixedCaseParent/A_Child')
504
 
        self.assertRelpath('MixedCaseParent/not_child', base,
505
 
                           'MixedCaseParent/not_child')
506
 
 
507
 
    def test_at_root_slash(self):
508
 
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
509
 
        # check...
510
 
        if osutils.MIN_ABS_PATHLENGTH > 1:
511
 
            raise tests.TestSkipped('relpath requires %d chars'
512
 
                                    % osutils.MIN_ABS_PATHLENGTH)
513
 
        self.assertRelpath('foo', '/', '/foo')
514
 
 
515
 
    def test_at_root_drive(self):
516
 
        if sys.platform != 'win32':
517
 
            raise tests.TestNotApplicable('we can only test drive-letter relative'
518
 
                                          ' paths on Windows where we have drive'
519
 
                                          ' letters.')
520
 
        # see bug #322807
521
 
        # The specific issue is that when at the root of a drive, 'abspath'
522
 
        # returns "C:/" or just "/". However, the code assumes that abspath
523
 
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
524
 
        self.assertRelpath('foo', 'C:/', 'C:/foo')
525
 
        self.assertRelpath('foo', 'X:/', 'X:/foo')
526
 
        self.assertRelpath('foo', 'X:/', 'X://foo')
527
 
 
528
 
 
529
451
class TestPumpFile(tests.TestCase):
530
452
    """Test pumpfile method."""
531
453
 
691
613
        self.assertEqual("1234", output.getvalue())
692
614
 
693
615
 
694
 
class TestRelpath(tests.TestCase):
695
 
 
696
 
    def test_simple_relpath(self):
697
 
        cwd = osutils.getcwd()
698
 
        subdir = cwd + '/subdir'
699
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
700
 
 
701
 
    def test_deep_relpath(self):
702
 
        cwd = osutils.getcwd()
703
 
        subdir = cwd + '/sub/subsubdir'
704
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
705
 
 
706
 
    def test_not_relative(self):
707
 
        self.assertRaises(errors.PathNotChild,
708
 
                          osutils.relpath, 'C:/path', 'H:/path')
709
 
        self.assertRaises(errors.PathNotChild,
710
 
                          osutils.relpath, 'C:/', 'H:/path')
711
 
 
712
 
 
713
616
class TestSafeUnicode(tests.TestCase):
714
617
 
715
618
    def test_from_ascii_string(self):
862
765
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
863
766
        # relative path
864
767
        cwd = osutils.getcwd().rstrip('/')
865
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
768
        drive = osutils._nt_splitdrive(cwd)[0]
866
769
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
867
770
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
868
771
        # unicode path
993
896
 
994
897
    def test_osutils_binding(self):
995
898
        from bzrlib.tests import test__chunks_to_lines
996
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
 
899
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
997
900
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
998
901
        else:
999
902
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1065
968
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1066
969
 
1067
970
    def test_walkdirs_os_error(self):
1068
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
971
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1069
972
        # Pyrex readdir didn't raise useful messages if it had an error
1070
973
        # reading the directory
1071
974
        if sys.platform == 'win32':
1072
975
            raise tests.TestNotApplicable(
1073
976
                "readdir IOError not tested on win32")
1074
 
        self.requireFeature(features.not_running_as_root)
1075
977
        os.mkdir("test-unreadable")
1076
978
        os.chmod("test-unreadable", 0000)
1077
979
        # must chmod it back so that it can be removed
1085
987
        # Ensure the message contains the file name
1086
988
        self.assertContainsRe(str(e), "\./test-unreadable")
1087
989
 
1088
 
 
1089
 
    def test_walkdirs_encoding_error(self):
1090
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1091
 
        # walkdirs didn't raise a useful message when the filenames
1092
 
        # are not using the filesystem's encoding
1093
 
 
1094
 
        # require a bytestring based filesystem
1095
 
        self.requireFeature(tests.ByteStringNamedFilesystem)
1096
 
 
1097
 
        tree = [
1098
 
            '.bzr',
1099
 
            '0file',
1100
 
            '1dir/',
1101
 
            '1dir/0file',
1102
 
            '1dir/1dir/',
1103
 
            '1file'
1104
 
            ]
1105
 
 
1106
 
        self.build_tree(tree)
1107
 
 
1108
 
        # rename the 1file to a latin-1 filename
1109
 
        os.rename("./1file", "\xe8file")
1110
 
 
1111
 
        self._save_platform_info()
1112
 
        win32utils.winver = None # Avoid the win32 detection code
1113
 
        osutils._fs_enc = 'UTF-8'
1114
 
 
1115
 
        # this should raise on error
1116
 
        def attempt():
1117
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1118
 
                pass
1119
 
 
1120
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1121
 
 
1122
990
    def test__walkdirs_utf8(self):
1123
991
        tree = [
1124
992
            '.bzr',
1174
1042
            dirblock[:] = new_dirblock
1175
1043
 
1176
1044
    def _save_platform_info(self):
1177
 
        self.overrideAttr(win32utils, 'winver')
1178
 
        self.overrideAttr(osutils, '_fs_enc')
1179
 
        self.overrideAttr(osutils, '_selected_dir_reader')
 
1045
        cur_winver = win32utils.winver
 
1046
        cur_fs_enc = osutils._fs_enc
 
1047
        cur_dir_reader = osutils._selected_dir_reader
 
1048
        def restore():
 
1049
            win32utils.winver = cur_winver
 
1050
            osutils._fs_enc = cur_fs_enc
 
1051
            osutils._selected_dir_reader = cur_dir_reader
 
1052
        self.addCleanup(restore)
1180
1053
 
1181
1054
    def assertDirReaderIs(self, expected):
1182
1055
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1215
1088
 
1216
1089
    def test_force_walkdirs_utf8_nt(self):
1217
1090
        # Disabled because the thunk of the whole walkdirs api is disabled.
1218
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1091
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1219
1092
        self._save_platform_info()
1220
1093
        win32utils.winver = 'Windows NT'
1221
1094
        from bzrlib._walkdirs_win32 import Win32ReadDir
1222
1095
        self.assertDirReaderIs(Win32ReadDir)
1223
1096
 
1224
1097
    def test_force_walkdirs_utf8_98(self):
1225
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1098
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1226
1099
        self._save_platform_info()
1227
1100
        win32utils.winver = 'Windows 98'
1228
1101
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1379
1252
        self.assertEqual(expected_dirblocks, result)
1380
1253
 
1381
1254
    def test__walkdirs_utf8_win32readdir(self):
1382
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1255
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1383
1256
        self.requireFeature(tests.UnicodeFilenameFeature)
1384
1257
        from bzrlib._walkdirs_win32 import Win32ReadDir
1385
1258
        self._save_platform_info()
1436
1309
 
1437
1310
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1438
1311
        """make sure our Stat values are valid"""
1439
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1312
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1440
1313
        self.requireFeature(tests.UnicodeFilenameFeature)
1441
1314
        from bzrlib._walkdirs_win32 import Win32ReadDir
1442
1315
        name0u = u'0file-\xb6'
1460
1333
 
1461
1334
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1462
1335
        """make sure our Stat values are valid"""
1463
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1336
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1464
1337
        self.requireFeature(tests.UnicodeFilenameFeature)
1465
1338
        from bzrlib._walkdirs_win32 import Win32ReadDir
1466
1339
        name0u = u'0dir-\u062c\u0648'
1615
1488
        def cleanup():
1616
1489
            if 'BZR_TEST_ENV_VAR' in os.environ:
1617
1490
                del os.environ['BZR_TEST_ENV_VAR']
 
1491
 
1618
1492
        self.addCleanup(cleanup)
1619
1493
 
1620
1494
    def test_set(self):
1668
1542
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1669
1543
        self.build_tree_contents([('foo', text)])
1670
1544
        expected_sha = osutils.sha_string(text)
1671
 
        f = open('foo', 'rb')
 
1545
        f = open('foo')
1672
1546
        self.addCleanup(f.close)
1673
1547
        size, sha = osutils.size_sha_file(f)
1674
1548
        self.assertEqual(38, size)
1707
1581
 
1708
1582
class TestReCompile(tests.TestCase):
1709
1583
 
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)
1713
 
 
1714
1584
    def test_re_compile_checked(self):
1715
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1585
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1716
1586
        self.assertTrue(r.match('aaaa'))
1717
1587
        self.assertTrue(r.match('aAaA'))
1718
1588
 
1719
1589
    def test_re_compile_checked_error(self):
1720
1590
        # like https://bugs.launchpad.net/bzr/+bug/251352
1721
 
 
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
1591
        err = self.assertRaises(
1726
1592
            errors.BzrCommandError,
1727
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1593
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1728
1594
        self.assertEqual(
1729
 
            'Invalid regular expression in test case: '
1730
 
            '"*" nothing to repeat',
 
1595
            "Invalid regular expression in test case: '*': "
 
1596
            "nothing to repeat",
1731
1597
            str(err))
1732
1598
 
1733
1599
 
1739
1605
 
1740
1606
    def setUp(self):
1741
1607
        tests.TestCaseInTempDir.setUp(self)
1742
 
        self.overrideAttr(osutils,
1743
 
                          '_selected_dir_reader', self._dir_reader_class())
 
1608
 
 
1609
        # Save platform specific info and reset it
 
1610
        cur_dir_reader = osutils._selected_dir_reader
 
1611
 
 
1612
        def restore():
 
1613
            osutils._selected_dir_reader = cur_dir_reader
 
1614
        self.addCleanup(restore)
 
1615
 
 
1616
        osutils._selected_dir_reader = self._dir_reader_class()
1744
1617
 
1745
1618
    def _get_ascii_tree(self):
1746
1619
        tree = [
1891
1764
 
1892
1765
class TestConcurrency(tests.TestCase):
1893
1766
 
1894
 
    def setUp(self):
1895
 
        super(TestConcurrency, self).setUp()
1896
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
1897
 
 
1898
1767
    def test_local_concurrency(self):
1899
1768
        concurrency = osutils.local_concurrency()
1900
1769
        self.assertIsInstance(concurrency, int)
1901
 
 
1902
 
    def test_local_concurrency_environment_variable(self):
1903
 
        os.environ['BZR_CONCURRENCY'] = '2'
1904
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1905
 
        os.environ['BZR_CONCURRENCY'] = '3'
1906
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1907
 
        os.environ['BZR_CONCURRENCY'] = 'foo'
1908
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1909
 
 
1910
 
    def test_option_concurrency(self):
1911
 
        os.environ['BZR_CONCURRENCY'] = '1'
1912
 
        self.run_bzr('rocks --concurrency 42')
1913
 
        # Command line overrides envrionment variable
1914
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1915
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1916
 
 
1917
 
 
1918
 
class TestFailedToLoadExtension(tests.TestCase):
1919
 
 
1920
 
    def _try_loading(self):
1921
 
        try:
1922
 
            import bzrlib._fictional_extension_py
1923
 
        except ImportError, e:
1924
 
            osutils.failed_to_load_extension(e)
1925
 
            return True
1926
 
 
1927
 
    def setUp(self):
1928
 
        super(TestFailedToLoadExtension, self).setUp()
1929
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
1930
 
 
1931
 
    def test_failure_to_load(self):
1932
 
        self._try_loading()
1933
 
        self.assertLength(1, osutils._extension_load_failures)
1934
 
        self.assertEquals(osutils._extension_load_failures[0],
1935
 
            "No module named _fictional_extension_py")
1936
 
 
1937
 
    def test_report_extension_load_failures_no_warning(self):
1938
 
        self.assertTrue(self._try_loading())
1939
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1940
 
        # it used to give a Python warning; it no longer does
1941
 
        self.assertLength(0, warnings)
1942
 
 
1943
 
    def test_report_extension_load_failures_message(self):
1944
 
        log = StringIO()
1945
 
        trace.push_log_file(log)
1946
 
        self.assertTrue(self._try_loading())
1947
 
        osutils.report_extension_load_failures()
1948
 
        self.assertContainsRe(
1949
 
            log.getvalue(),
1950
 
            r"bzr: warning: some compiled extensions could not be loaded; "
1951
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1952
 
            )
1953
 
 
1954
 
 
1955
 
class TestTerminalWidth(tests.TestCase):
1956
 
 
1957
 
    def setUp(self):
1958
 
        tests.TestCase.setUp(self)
1959
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1960
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1961
 
        self.addCleanup(self.restore_osutils_globals)
1962
 
        osutils._terminal_size_state = 'no_data'
1963
 
        osutils._first_terminal_size = None
1964
 
 
1965
 
    def restore_osutils_globals(self):
1966
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1967
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1968
 
 
1969
 
    def replace_stdout(self, new):
1970
 
        self.overrideAttr(sys, 'stdout', new)
1971
 
 
1972
 
    def replace__terminal_size(self, new):
1973
 
        self.overrideAttr(osutils, '_terminal_size', new)
1974
 
 
1975
 
    def set_fake_tty(self):
1976
 
 
1977
 
        class I_am_a_tty(object):
1978
 
            def isatty(self):
1979
 
                return True
1980
 
 
1981
 
        self.replace_stdout(I_am_a_tty())
1982
 
 
1983
 
    def test_default_values(self):
1984
 
        self.assertEqual(80, osutils.default_terminal_width)
1985
 
 
1986
 
    def test_defaults_to_BZR_COLUMNS(self):
1987
 
        # BZR_COLUMNS is set by the test framework
1988
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
1989
 
        os.environ['BZR_COLUMNS'] = '12'
1990
 
        self.assertEqual(12, osutils.terminal_width())
1991
 
 
1992
 
    def test_falls_back_to_COLUMNS(self):
1993
 
        del os.environ['BZR_COLUMNS']
1994
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
1995
 
        self.set_fake_tty()
1996
 
        os.environ['COLUMNS'] = '42'
1997
 
        self.assertEqual(42, osutils.terminal_width())
1998
 
 
1999
 
    def test_tty_default_without_columns(self):
2000
 
        del os.environ['BZR_COLUMNS']
2001
 
        del os.environ['COLUMNS']
2002
 
 
2003
 
        def terminal_size(w, h):
2004
 
            return 42, 42
2005
 
 
2006
 
        self.set_fake_tty()
2007
 
        # We need to override the osutils definition as it depends on the
2008
 
        # running environment that we can't control (PQM running without a
2009
 
        # controlling terminal is one example).
2010
 
        self.replace__terminal_size(terminal_size)
2011
 
        self.assertEqual(42, osutils.terminal_width())
2012
 
 
2013
 
    def test_non_tty_default_without_columns(self):
2014
 
        del os.environ['BZR_COLUMNS']
2015
 
        del os.environ['COLUMNS']
2016
 
        self.replace_stdout(None)
2017
 
        self.assertEqual(None, osutils.terminal_width())
2018
 
 
2019
 
    def test_no_TIOCGWINSZ(self):
2020
 
        self.requireFeature(term_ios_feature)
2021
 
        termios = term_ios_feature.module
2022
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2023
 
        try:
2024
 
            orig = termios.TIOCGWINSZ
2025
 
        except AttributeError:
2026
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2027
 
            pass
2028
 
        else:
2029
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2030
 
            del termios.TIOCGWINSZ
2031
 
        del os.environ['BZR_COLUMNS']
2032
 
        del os.environ['COLUMNS']
2033
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2034
 
        osutils.terminal_width()
2035
 
 
2036
 
class TestCreationOps(tests.TestCaseInTempDir):
2037
 
    _test_needs_features = [features.chown_feature]
2038
 
 
2039
 
    def setUp(self):
2040
 
        tests.TestCaseInTempDir.setUp(self)
2041
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2042
 
 
2043
 
        # params set by call to _dummy_chown
2044
 
        self.path = self.uid = self.gid = None
2045
 
 
2046
 
    def _dummy_chown(self, path, uid, gid):
2047
 
        self.path, self.uid, self.gid = path, uid, gid
2048
 
 
2049
 
    def test_copy_ownership_from_path(self):
2050
 
        """copy_ownership_from_path test with specified src."""
2051
 
        ownsrc = '/'
2052
 
        f = open('test_file', 'wt')
2053
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2054
 
 
2055
 
        s = os.stat(ownsrc)
2056
 
        self.assertEquals(self.path, 'test_file')
2057
 
        self.assertEquals(self.uid, s.st_uid)
2058
 
        self.assertEquals(self.gid, s.st_gid)
2059
 
 
2060
 
    def test_copy_ownership_nonesrc(self):
2061
 
        """copy_ownership_from_path test with src=None."""
2062
 
        f = open('test_file', 'wt')
2063
 
        # should use parent dir for permissions
2064
 
        osutils.copy_ownership_from_path('test_file')
2065
 
 
2066
 
        s = os.stat('..')
2067
 
        self.assertEquals(self.path, 'test_file')
2068
 
        self.assertEquals(self.uid, s.st_uid)
2069
 
        self.assertEquals(self.gid, s.st_gid)
2070
 
 
2071
 
class TestGetuserUnicode(tests.TestCase):
2072
 
 
2073
 
    def test_ascii_user(self):
2074
 
        osutils.set_or_unset_env('LOGNAME', 'jrandom')
2075
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2076
 
 
2077
 
    def test_unicode_user(self):
2078
 
        ue = osutils.get_user_encoding()
2079
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2080
 
        if uni_val is None:
2081
 
            raise tests.TestSkipped(
2082
 
                'Cannot find a unicode character that works in encoding %s'
2083
 
                % (osutils.get_user_encoding(),))
2084
 
        uni_username = u'jrandom' + uni_val
2085
 
        encoded_username = uni_username.encode(ue)
2086
 
        osutils.set_or_unset_env('LOGNAME', encoded_username)
2087
 
        self.assertEqual(uni_username, osutils.getuser_unicode())