83
56
def feature_name(self):
84
57
return 'bzrlib._readdir_pyx'
86
ReadDirFeature = _ReadDirFeature()
89
class TestOSUtils(TestCaseInTempDir):
59
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
61
term_ios_feature = features.ModuleAvailableFeature('termios')
64
def _already_unicode(s):
68
def _utf8_to_unicode(s):
69
return s.decode('UTF-8')
72
def dir_reader_scenarios():
73
# For each dir reader we define:
75
# - native_to_unicode: a function converting the native_abspath as returned
76
# by DirReader.read_dir to its unicode representation
78
# UnicodeDirReader is the fallback, it should be tested on all platforms.
79
scenarios = [('unicode',
80
dict(_dir_reader_class=osutils.UnicodeDirReader,
81
_native_to_unicode=_already_unicode))]
82
# Some DirReaders are platform specific and even there they may not be
84
if UTF8DirReaderFeature.available():
85
from bzrlib import _readdir_pyx
86
scenarios.append(('utf8',
87
dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
88
_native_to_unicode=_utf8_to_unicode)))
90
if test__walkdirs_win32.win32_readdir_feature.available():
92
from bzrlib import _walkdirs_win32
95
dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
96
_native_to_unicode=_already_unicode)))
102
load_tests = load_tests_apply_scenarios
105
class TestContainsWhitespace(tests.TestCase):
91
107
def test_contains_whitespace(self):
92
self.failUnless(osutils.contains_whitespace(u' '))
93
self.failUnless(osutils.contains_whitespace(u'hello there'))
94
self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
95
self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
96
self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
97
self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
108
self.assertTrue(osutils.contains_whitespace(u' '))
109
self.assertTrue(osutils.contains_whitespace(u'hello there'))
110
self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
111
self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
112
self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
113
self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
99
115
# \xa0 is "Non-breaking-space" which on some python locales thinks it
100
116
# is whitespace, but we do not.
101
self.failIf(osutils.contains_whitespace(u''))
102
self.failIf(osutils.contains_whitespace(u'hellothere'))
103
self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
117
self.assertFalse(osutils.contains_whitespace(u''))
118
self.assertFalse(osutils.contains_whitespace(u'hellothere'))
119
self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
122
class TestRename(tests.TestCaseInTempDir):
124
def create_file(self, filename, content):
125
f = open(filename, 'wb')
131
def _fancy_rename(self, a, b):
132
osutils.fancy_rename(a, b, rename_func=os.rename,
133
unlink_func=os.unlink)
105
135
def test_fancy_rename(self):
106
136
# This should work everywhere
108
osutils.fancy_rename(a, b,
109
rename_func=os.rename,
110
unlink_func=os.unlink)
112
open('a', 'wb').write('something in a\n')
114
self.failIfExists('a')
115
self.failUnlessExists('b')
137
self.create_file('a', 'something in a\n')
138
self._fancy_rename('a', 'b')
139
self.assertPathDoesNotExist('a')
140
self.assertPathExists('b')
116
141
self.check_file_contents('b', 'something in a\n')
118
open('a', 'wb').write('new something in a\n')
143
self.create_file('a', 'new something in a\n')
144
self._fancy_rename('b', 'a')
121
146
self.check_file_contents('a', 'something in a\n')
148
def test_fancy_rename_fails_source_missing(self):
149
# An exception should be raised, and the target should be left in place
150
self.create_file('target', 'data in target\n')
151
self.assertRaises((IOError, OSError), self._fancy_rename,
152
'missingsource', 'target')
153
self.assertPathExists('target')
154
self.check_file_contents('target', 'data in target\n')
156
def test_fancy_rename_fails_if_source_and_target_missing(self):
157
self.assertRaises((IOError, OSError), self._fancy_rename,
158
'missingsource', 'missingtarget')
123
160
def test_rename(self):
124
161
# Rename should be semi-atomic on all platforms
125
open('a', 'wb').write('something in a\n')
162
self.create_file('a', 'something in a\n')
126
163
osutils.rename('a', 'b')
127
self.failIfExists('a')
128
self.failUnlessExists('b')
164
self.assertPathDoesNotExist('a')
165
self.assertPathExists('b')
129
166
self.check_file_contents('b', 'something in a\n')
131
open('a', 'wb').write('new something in a\n')
168
self.create_file('a', 'new something in a\n')
132
169
osutils.rename('b', 'a')
134
171
self.check_file_contents('a', 'something in a\n')
912
1300
new_dirblock.append((info[0], info[1], info[2], info[4]))
913
1301
dirblock[:] = new_dirblock
915
def test__walkdirs_utf8_selection(self):
916
# Just trigger the function once, to make sure it has selected a real
918
list(osutils._walkdirs_utf8('.'))
919
if WalkdirsWin32Feature.available():
920
# If the compiled form is available, make sure it is used
921
from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
922
self.assertIs(_walkdirs_utf8_win32_find_file,
923
osutils._real_walkdirs_utf8)
924
elif sys.platform == 'win32':
925
self.assertIs(osutils._walkdirs_unicode_to_utf8,
926
osutils._real_walkdirs_utf8)
927
elif osutils._fs_enc.upper() in ('UTF-8', 'ASCII', 'ANSI_X3.4-1968'): # ascii
928
self.assertIs(osutils._walkdirs_fs_utf8,
929
osutils._real_walkdirs_utf8)
931
self.assertIs(osutils._walkdirs_unicode_to_utf8,
932
osutils._real_walkdirs_utf8)
934
1303
def _save_platform_info(self):
935
cur_winver = win32utils.winver
936
cur_fs_enc = osutils._fs_enc
937
cur_real_walkdirs_utf8 = osutils._real_walkdirs_utf8
939
win32utils.winver = cur_winver
940
osutils._fs_enc = cur_fs_enc
941
osutils._real_walkdirs_utf8 = cur_real_walkdirs_utf8
942
self.addCleanup(restore)
1304
self.overrideAttr(win32utils, 'winver')
1305
self.overrideAttr(osutils, '_fs_enc')
1306
self.overrideAttr(osutils, '_selected_dir_reader')
944
def assertWalkdirsUtf8Is(self, expected):
1308
def assertDirReaderIs(self, expected):
945
1309
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
946
1310
# Force it to redetect
947
osutils._real_walkdirs_utf8 = None
1311
osutils._selected_dir_reader = None
948
1312
# Nothing to list, but should still trigger the selection logic
949
1313
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
950
self.assertIs(expected, osutils._real_walkdirs_utf8)
1314
self.assertIsInstance(osutils._selected_dir_reader, expected)
952
1316
def test_force_walkdirs_utf8_fs_utf8(self):
1317
self.requireFeature(UTF8DirReaderFeature)
953
1318
self._save_platform_info()
954
1319
win32utils.winver = None # Avoid the win32 detection code
955
osutils._fs_enc = 'UTF-8'
956
self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1320
osutils._fs_enc = 'utf-8'
1321
self.assertDirReaderIs(
1322
UTF8DirReaderFeature.module.UTF8DirReader)
958
1324
def test_force_walkdirs_utf8_fs_ascii(self):
959
self._save_platform_info()
960
win32utils.winver = None # Avoid the win32 detection code
961
osutils._fs_enc = 'US-ASCII'
962
self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
964
def test_force_walkdirs_utf8_fs_ANSI(self):
965
self._save_platform_info()
966
win32utils.winver = None # Avoid the win32 detection code
967
osutils._fs_enc = 'ANSI_X3.4-1968'
968
self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1325
self.requireFeature(UTF8DirReaderFeature)
1326
self._save_platform_info()
1327
win32utils.winver = None # Avoid the win32 detection code
1328
osutils._fs_enc = 'ascii'
1329
self.assertDirReaderIs(
1330
UTF8DirReaderFeature.module.UTF8DirReader)
970
1332
def test_force_walkdirs_utf8_fs_latin1(self):
971
1333
self._save_platform_info()
972
1334
win32utils.winver = None # Avoid the win32 detection code
973
osutils._fs_enc = 'latin1'
974
self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1335
osutils._fs_enc = 'iso-8859-1'
1336
self.assertDirReaderIs(osutils.UnicodeDirReader)
976
1338
def test_force_walkdirs_utf8_nt(self):
977
self.requireFeature(WalkdirsWin32Feature)
1339
# Disabled because the thunk of the whole walkdirs api is disabled.
1340
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
978
1341
self._save_platform_info()
979
1342
win32utils.winver = 'Windows NT'
980
from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
981
self.assertWalkdirsUtf8Is(_walkdirs_utf8_win32_find_file)
1343
from bzrlib._walkdirs_win32 import Win32ReadDir
1344
self.assertDirReaderIs(Win32ReadDir)
983
def test_force_walkdirs_utf8_nt(self):
984
self.requireFeature(WalkdirsWin32Feature)
1346
def test_force_walkdirs_utf8_98(self):
1347
self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
985
1348
self._save_platform_info()
986
1349
win32utils.winver = 'Windows 98'
987
self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1350
self.assertDirReaderIs(osutils.UnicodeDirReader)
989
1352
def test_unicode_walkdirs(self):
990
1353
"""Walkdirs should always return unicode paths."""
1354
self.requireFeature(features.UnicodeFilenameFeature)
991
1355
name0 = u'0file-\xb6'
992
1356
name1 = u'1dir-\u062c\u0648'
993
1357
name2 = u'2file-\u0633'
1416
1772
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1417
1773
self.assertEqual('foo', old)
1418
1774
self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1419
self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1422
class TestLocalTimeOffset(TestCase):
1424
def test_local_time_offset(self):
1425
"""Test that local_time_offset() returns a sane value."""
1426
offset = osutils.local_time_offset()
1427
self.assertTrue(isinstance(offset, int))
1428
# Test that the offset is no more than a eighteen hours in
1430
# Time zone handling is system specific, so it is difficult to
1431
# do more specific tests, but a value outside of this range is
1433
eighteen_hours = 18 * 3600
1434
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
1436
def test_local_time_offset_with_timestamp(self):
1437
"""Test that local_time_offset() works with a timestamp."""
1438
offset = osutils.local_time_offset(1000000000.1234567)
1439
self.assertTrue(isinstance(offset, int))
1440
eighteen_hours = 18 * 3600
1441
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
1444
class TestShaFileByName(TestCaseInTempDir):
1446
def test_sha_empty(self):
1447
self.build_tree_contents([('foo', '')])
1448
expected_sha = osutils.sha_string('')
1449
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1451
def test_sha_mixed_endings(self):
1452
text = 'test\r\nwith\nall\rpossible line endings\r\n'
1453
self.build_tree_contents([('foo', text)])
1454
expected_sha = osutils.sha_string(text)
1455
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1459
r'''# Copyright (C) 2005, 2006 Canonical Ltd
1461
# This program is free software; you can redistribute it and/or modify
1462
# it under the terms of the GNU General Public License as published by
1463
# the Free Software Foundation; either version 2 of the License, or
1464
# (at your option) any later version.
1466
# This program is distributed in the hope that it will be useful,
1467
# but WITHOUT ANY WARRANTY; without even the implied warranty of
1468
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1469
# GNU General Public License for more details.
1471
# You should have received a copy of the GNU General Public License
1472
# along with this program; if not, write to the Free Software
1473
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1476
# NOTE: If update these, please also update the help for global-options in
1477
# bzrlib/help_topics/__init__.py
1480
"""Set of flags that enable different debug behaviour.
1482
These are set with eg ``-Dlock`` on the bzr command line.
1486
* auth - show authentication sections used
1487
* error - show stack traces for all top level exceptions
1488
* evil - capture call sites that do expensive or badly-scaling operations.
1489
* fetch - trace history copying between repositories
1490
* graph - trace graph traversal information
1491
* hashcache - log every time a working file is read to determine its hash
1492
* hooks - trace hook execution
1493
* hpss - trace smart protocol requests and responses
1494
* http - trace http connections, requests and responses
1495
* index - trace major index operations
1496
* knit - trace knit operations
1497
* lock - trace when lockdir locks are taken or released
1498
* merge - emit information for debugging merges
1499
* pack - emit information about pack operations
1505
class TestResourceLoading(TestCaseInTempDir):
1775
self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1778
class TestSizeShaFile(tests.TestCaseInTempDir):
1780
def test_sha_empty(self):
1781
self.build_tree_contents([('foo', '')])
1782
expected_sha = osutils.sha_string('')
1784
self.addCleanup(f.close)
1785
size, sha = osutils.size_sha_file(f)
1786
self.assertEqual(0, size)
1787
self.assertEqual(expected_sha, sha)
1789
def test_sha_mixed_endings(self):
1790
text = 'test\r\nwith\nall\rpossible line endings\r\n'
1791
self.build_tree_contents([('foo', text)])
1792
expected_sha = osutils.sha_string(text)
1793
f = open('foo', 'rb')
1794
self.addCleanup(f.close)
1795
size, sha = osutils.size_sha_file(f)
1796
self.assertEqual(38, size)
1797
self.assertEqual(expected_sha, sha)
1800
class TestShaFileByName(tests.TestCaseInTempDir):
1802
def test_sha_empty(self):
1803
self.build_tree_contents([('foo', '')])
1804
expected_sha = osutils.sha_string('')
1805
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1807
def test_sha_mixed_endings(self):
1808
text = 'test\r\nwith\nall\rpossible line endings\r\n'
1809
self.build_tree_contents([('foo', text)])
1810
expected_sha = osutils.sha_string(text)
1811
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1814
class TestResourceLoading(tests.TestCaseInTempDir):
1507
1816
def test_resource_string(self):
1508
1817
# test resource in bzrlib
1509
1818
text = osutils.resource_string('bzrlib', 'debug.py')
1510
self.assertEquals(_debug_text, text)
1819
self.assertContainsRe(text, "debug_flags = set()")
1511
1820
# test resource under bzrlib
1512
1821
text = osutils.resource_string('bzrlib.ui', 'text.py')
1513
1822
self.assertContainsRe(text, "class TextUIFactory")
1517
1826
# test unknown resource
1518
1827
self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1830
class TestReCompile(tests.TestCase):
1832
def _deprecated_re_compile_checked(self, *args, **kwargs):
1833
return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1834
osutils.re_compile_checked, *args, **kwargs)
1836
def test_re_compile_checked(self):
1837
r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1838
self.assertTrue(r.match('aaaa'))
1839
self.assertTrue(r.match('aAaA'))
1841
def test_re_compile_checked_error(self):
1842
# like https://bugs.launchpad.net/bzr/+bug/251352
1844
# Due to possible test isolation error, re.compile is not lazy at
1845
# this point. We re-install lazy compile.
1846
lazy_regex.install_lazy_compile()
1847
err = self.assertRaises(
1848
errors.BzrCommandError,
1849
self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1851
'Invalid regular expression in test case: '
1852
'"*" nothing to repeat',
1856
class TestDirReader(tests.TestCaseInTempDir):
1858
scenarios = dir_reader_scenarios()
1861
_dir_reader_class = None
1862
_native_to_unicode = None
1865
super(TestDirReader, self).setUp()
1866
self.overrideAttr(osutils,
1867
'_selected_dir_reader', self._dir_reader_class())
1869
def _get_ascii_tree(self):
1877
expected_dirblocks = [
1879
[('0file', '0file', 'file'),
1880
('1dir', '1dir', 'directory'),
1881
('2file', '2file', 'file'),
1884
(('1dir', './1dir'),
1885
[('1dir/0file', '0file', 'file'),
1886
('1dir/1dir', '1dir', 'directory'),
1889
(('1dir/1dir', './1dir/1dir'),
1894
return tree, expected_dirblocks
1896
def test_walk_cur_dir(self):
1897
tree, expected_dirblocks = self._get_ascii_tree()
1898
self.build_tree(tree)
1899
result = list(osutils._walkdirs_utf8('.'))
1900
# Filter out stat and abspath
1901
self.assertEqual(expected_dirblocks,
1902
[(dirinfo, [line[0:3] for line in block])
1903
for dirinfo, block in result])
1905
def test_walk_sub_dir(self):
1906
tree, expected_dirblocks = self._get_ascii_tree()
1907
self.build_tree(tree)
1908
# you can search a subdir only, with a supplied prefix.
1909
result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1910
# Filter out stat and abspath
1911
self.assertEqual(expected_dirblocks[1:],
1912
[(dirinfo, [line[0:3] for line in block])
1913
for dirinfo, block in result])
1915
def _get_unicode_tree(self):
1916
name0u = u'0file-\xb6'
1917
name1u = u'1dir-\u062c\u0648'
1918
name2u = u'2file-\u0633'
1922
name1u + '/' + name0u,
1923
name1u + '/' + name1u + '/',
1926
name0 = name0u.encode('UTF-8')
1927
name1 = name1u.encode('UTF-8')
1928
name2 = name2u.encode('UTF-8')
1929
expected_dirblocks = [
1931
[(name0, name0, 'file', './' + name0u),
1932
(name1, name1, 'directory', './' + name1u),
1933
(name2, name2, 'file', './' + name2u),
1936
((name1, './' + name1u),
1937
[(name1 + '/' + name0, name0, 'file', './' + name1u
1939
(name1 + '/' + name1, name1, 'directory', './' + name1u
1943
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1948
return tree, expected_dirblocks
1950
def _filter_out(self, raw_dirblocks):
1951
"""Filter out a walkdirs_utf8 result.
1953
stat field is removed, all native paths are converted to unicode
1955
filtered_dirblocks = []
1956
for dirinfo, block in raw_dirblocks:
1957
dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1960
details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1961
filtered_dirblocks.append((dirinfo, details))
1962
return filtered_dirblocks
1964
def test_walk_unicode_tree(self):
1965
self.requireFeature(features.UnicodeFilenameFeature)
1966
tree, expected_dirblocks = self._get_unicode_tree()
1967
self.build_tree(tree)
1968
result = list(osutils._walkdirs_utf8('.'))
1969
self.assertEqual(expected_dirblocks, self._filter_out(result))
1971
def test_symlink(self):
1972
self.requireFeature(features.SymlinkFeature)
1973
self.requireFeature(features.UnicodeFilenameFeature)
1974
target = u'target\N{Euro Sign}'
1975
link_name = u'l\N{Euro Sign}nk'
1976
os.symlink(target, link_name)
1977
target_utf8 = target.encode('UTF-8')
1978
link_name_utf8 = link_name.encode('UTF-8')
1979
expected_dirblocks = [
1981
[(link_name_utf8, link_name_utf8,
1982
'symlink', './' + link_name),],
1984
result = list(osutils._walkdirs_utf8('.'))
1985
self.assertEqual(expected_dirblocks, self._filter_out(result))
1988
class TestReadLink(tests.TestCaseInTempDir):
1989
"""Exposes os.readlink() problems and the osutils solution.
1991
The only guarantee offered by os.readlink(), starting with 2.6, is that a
1992
unicode string will be returned if a unicode string is passed.
1994
But prior python versions failed to properly encode the passed unicode
1997
_test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
2000
super(tests.TestCaseInTempDir, self).setUp()
2001
self.link = u'l\N{Euro Sign}ink'
2002
self.target = u'targe\N{Euro Sign}t'
2003
os.symlink(self.target, self.link)
2005
def test_os_readlink_link_encoding(self):
2006
self.assertEqual(self.target, os.readlink(self.link))
2008
def test_os_readlink_link_decoding(self):
2009
self.assertEqual(self.target.encode(osutils._fs_enc),
2010
os.readlink(self.link.encode(osutils._fs_enc)))
2013
class TestConcurrency(tests.TestCase):
2016
super(TestConcurrency, self).setUp()
2017
self.overrideAttr(osutils, '_cached_local_concurrency')
2019
def test_local_concurrency(self):
2020
concurrency = osutils.local_concurrency()
2021
self.assertIsInstance(concurrency, int)
2023
def test_local_concurrency_environment_variable(self):
2024
self.overrideEnv('BZR_CONCURRENCY', '2')
2025
self.assertEqual(2, osutils.local_concurrency(use_cache=False))
2026
self.overrideEnv('BZR_CONCURRENCY', '3')
2027
self.assertEqual(3, osutils.local_concurrency(use_cache=False))
2028
self.overrideEnv('BZR_CONCURRENCY', 'foo')
2029
self.assertEqual(1, osutils.local_concurrency(use_cache=False))
2031
def test_option_concurrency(self):
2032
self.overrideEnv('BZR_CONCURRENCY', '1')
2033
self.run_bzr('rocks --concurrency 42')
2034
# Command line overrides environment variable
2035
self.assertEqual('42', os.environ['BZR_CONCURRENCY'])
2036
self.assertEqual(42, osutils.local_concurrency(use_cache=False))
2039
class TestFailedToLoadExtension(tests.TestCase):
2041
def _try_loading(self):
2043
import bzrlib._fictional_extension_py
2044
except ImportError, e:
2045
osutils.failed_to_load_extension(e)
2049
super(TestFailedToLoadExtension, self).setUp()
2050
self.overrideAttr(osutils, '_extension_load_failures', [])
2052
def test_failure_to_load(self):
2054
self.assertLength(1, osutils._extension_load_failures)
2055
self.assertEqual(osutils._extension_load_failures[0],
2056
"No module named _fictional_extension_py")
2058
def test_report_extension_load_failures_no_warning(self):
2059
self.assertTrue(self._try_loading())
2060
warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
2061
# it used to give a Python warning; it no longer does
2062
self.assertLength(0, warnings)
2064
def test_report_extension_load_failures_message(self):
2066
trace.push_log_file(log)
2067
self.assertTrue(self._try_loading())
2068
osutils.report_extension_load_failures()
2069
self.assertContainsRe(
2071
r"bzr: warning: some compiled extensions could not be loaded; "
2072
"see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
2076
class TestTerminalWidth(tests.TestCase):
2079
super(TestTerminalWidth, self).setUp()
2080
self._orig_terminal_size_state = osutils._terminal_size_state
2081
self._orig_first_terminal_size = osutils._first_terminal_size
2082
self.addCleanup(self.restore_osutils_globals)
2083
osutils._terminal_size_state = 'no_data'
2084
osutils._first_terminal_size = None
2086
def restore_osutils_globals(self):
2087
osutils._terminal_size_state = self._orig_terminal_size_state
2088
osutils._first_terminal_size = self._orig_first_terminal_size
2090
def replace_stdout(self, new):
2091
self.overrideAttr(sys, 'stdout', new)
2093
def replace__terminal_size(self, new):
2094
self.overrideAttr(osutils, '_terminal_size', new)
2096
def set_fake_tty(self):
2098
class I_am_a_tty(object):
2102
self.replace_stdout(I_am_a_tty())
2104
def test_default_values(self):
2105
self.assertEqual(80, osutils.default_terminal_width)
2107
def test_defaults_to_BZR_COLUMNS(self):
2108
# BZR_COLUMNS is set by the test framework
2109
self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2110
self.overrideEnv('BZR_COLUMNS', '12')
2111
self.assertEqual(12, osutils.terminal_width())
2113
def test_BZR_COLUMNS_0_no_limit(self):
2114
self.overrideEnv('BZR_COLUMNS', '0')
2115
self.assertEqual(None, osutils.terminal_width())
2117
def test_falls_back_to_COLUMNS(self):
2118
self.overrideEnv('BZR_COLUMNS', None)
2119
self.assertNotEqual('42', os.environ['COLUMNS'])
2121
self.overrideEnv('COLUMNS', '42')
2122
self.assertEqual(42, osutils.terminal_width())
2124
def test_tty_default_without_columns(self):
2125
self.overrideEnv('BZR_COLUMNS', None)
2126
self.overrideEnv('COLUMNS', None)
2128
def terminal_size(w, h):
2132
# We need to override the osutils definition as it depends on the
2133
# running environment that we can't control (PQM running without a
2134
# controlling terminal is one example).
2135
self.replace__terminal_size(terminal_size)
2136
self.assertEqual(42, osutils.terminal_width())
2138
def test_non_tty_default_without_columns(self):
2139
self.overrideEnv('BZR_COLUMNS', None)
2140
self.overrideEnv('COLUMNS', None)
2141
self.replace_stdout(None)
2142
self.assertEqual(None, osutils.terminal_width())
2144
def test_no_TIOCGWINSZ(self):
2145
self.requireFeature(term_ios_feature)
2146
termios = term_ios_feature.module
2147
# bug 63539 is about a termios without TIOCGWINSZ attribute
2149
orig = termios.TIOCGWINSZ
2150
except AttributeError:
2151
# We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2154
self.overrideAttr(termios, 'TIOCGWINSZ')
2155
del termios.TIOCGWINSZ
2156
self.overrideEnv('BZR_COLUMNS', None)
2157
self.overrideEnv('COLUMNS', None)
2158
# Whatever the result is, if we don't raise an exception, it's ok.
2159
osutils.terminal_width()
2162
class TestCreationOps(tests.TestCaseInTempDir):
2163
_test_needs_features = [features.chown_feature]
2166
super(TestCreationOps, self).setUp()
2167
self.overrideAttr(os, 'chown', self._dummy_chown)
2169
# params set by call to _dummy_chown
2170
self.path = self.uid = self.gid = None
2172
def _dummy_chown(self, path, uid, gid):
2173
self.path, self.uid, self.gid = path, uid, gid
2175
def test_copy_ownership_from_path(self):
2176
"""copy_ownership_from_path test with specified src."""
2178
f = open('test_file', 'wt')
2179
osutils.copy_ownership_from_path('test_file', ownsrc)
2182
self.assertEqual(self.path, 'test_file')
2183
self.assertEqual(self.uid, s.st_uid)
2184
self.assertEqual(self.gid, s.st_gid)
2186
def test_copy_ownership_nonesrc(self):
2187
"""copy_ownership_from_path test with src=None."""
2188
f = open('test_file', 'wt')
2189
# should use parent dir for permissions
2190
osutils.copy_ownership_from_path('test_file')
2193
self.assertEqual(self.path, 'test_file')
2194
self.assertEqual(self.uid, s.st_uid)
2195
self.assertEqual(self.gid, s.st_gid)
2198
class TestPathFromEnviron(tests.TestCase):
2200
def test_is_unicode(self):
2201
self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
2202
path = osutils.path_from_environ('BZR_TEST_PATH')
2203
self.assertIsInstance(path, unicode)
2204
self.assertEqual(u'./anywhere at all/', path)
2206
def test_posix_path_env_ascii(self):
2207
self.overrideEnv('BZR_TEST_PATH', '/tmp')
2208
home = osutils._posix_path_from_environ('BZR_TEST_PATH')
2209
self.assertIsInstance(home, unicode)
2210
self.assertEqual(u'/tmp', home)
2212
def test_posix_path_env_unicode(self):
2213
self.requireFeature(features.ByteStringNamedFilesystem)
2214
self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
2215
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2216
self.assertEqual(u'/home/\xa7test',
2217
osutils._posix_path_from_environ('BZR_TEST_PATH'))
2218
osutils._fs_enc = "iso8859-5"
2219
self.assertEqual(u'/home/\u0407test',
2220
osutils._posix_path_from_environ('BZR_TEST_PATH'))
2221
osutils._fs_enc = "utf-8"
2222
self.assertRaises(errors.BadFilenameEncoding,
2223
osutils._posix_path_from_environ, 'BZR_TEST_PATH')
2226
class TestGetHomeDir(tests.TestCase):
2228
def test_is_unicode(self):
2229
home = osutils._get_home_dir()
2230
self.assertIsInstance(home, unicode)
2232
def test_posix_homeless(self):
2233
self.overrideEnv('HOME', None)
2234
home = osutils._get_home_dir()
2235
self.assertIsInstance(home, unicode)
2237
def test_posix_home_ascii(self):
2238
self.overrideEnv('HOME', '/home/test')
2239
home = osutils._posix_get_home_dir()
2240
self.assertIsInstance(home, unicode)
2241
self.assertEqual(u'/home/test', home)
2243
def test_posix_home_unicode(self):
2244
self.requireFeature(features.ByteStringNamedFilesystem)
2245
self.overrideEnv('HOME', '/home/\xa7test')
2246
self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2247
self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2248
osutils._fs_enc = "iso8859-5"
2249
self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
2250
osutils._fs_enc = "utf-8"
2251
self.assertRaises(errors.BadFilenameEncoding,
2252
osutils._posix_get_home_dir)
2255
class TestGetuserUnicode(tests.TestCase):
2257
def test_is_unicode(self):
2258
user = osutils.getuser_unicode()
2259
self.assertIsInstance(user, unicode)
2261
def envvar_to_override(self):
2262
if sys.platform == "win32":
2263
# Disable use of platform calls on windows so envvar is used
2264
self.overrideAttr(win32utils, 'has_ctypes', False)
2265
return 'USERNAME' # only variable used on windows
2266
return 'LOGNAME' # first variable checked by getpass.getuser()
2268
def test_ascii_user(self):
2269
self.overrideEnv(self.envvar_to_override(), 'jrandom')
2270
self.assertEqual(u'jrandom', osutils.getuser_unicode())
2272
def test_unicode_user(self):
2273
ue = osutils.get_user_encoding()
2274
uni_val, env_val = tests.probe_unicode_in_user_encoding()
2276
raise tests.TestSkipped(
2277
'Cannot find a unicode character that works in encoding %s'
2278
% (osutils.get_user_encoding(),))
2279
uni_username = u'jrandom' + uni_val
2280
encoded_username = uni_username.encode(ue)
2281
self.overrideEnv(self.envvar_to_override(), encoded_username)
2282
self.assertEqual(uni_username, osutils.getuser_unicode())
2285
class TestBackupNames(tests.TestCase):
2288
super(TestBackupNames, self).setUp()
2291
def backup_exists(self, name):
2292
return name in self.backups
2294
def available_backup_name(self, name):
2295
backup_name = osutils.available_backup_name(name, self.backup_exists)
2296
self.backups.append(backup_name)
2299
def assertBackupName(self, expected, name):
2300
self.assertEqual(expected, self.available_backup_name(name))
2302
def test_empty(self):
2303
self.assertBackupName('file.~1~', 'file')
2305
def test_existing(self):
2306
self.available_backup_name('file')
2307
self.available_backup_name('file')
2308
self.assertBackupName('file.~3~', 'file')
2309
# Empty slots are found, this is not a strict requirement and may be
2310
# revisited if we test against all implementations.
2311
self.backups.remove('file.~2~')
2312
self.assertBackupName('file.~2~', 'file')
2315
class TestFindExecutableInPath(tests.TestCase):
2317
def test_windows(self):
2318
if sys.platform != 'win32':
2319
raise tests.TestSkipped('test requires win32')
2320
self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2322
osutils.find_executable_on_path('explorer.exe') is not None)
2324
osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2326
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2327
self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2329
def test_windows_app_path(self):
2330
if sys.platform != 'win32':
2331
raise tests.TestSkipped('test requires win32')
2332
# Override PATH env var so that exe can only be found on App Path
2333
self.overrideEnv('PATH', '')
2334
# Internt Explorer is always registered in the App Path
2335
self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2337
def test_other(self):
2338
if sys.platform == 'win32':
2339
raise tests.TestSkipped('test requires non-win32')
2340
self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2342
osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2345
class TestEnvironmentErrors(tests.TestCase):
2346
"""Test handling of environmental errors"""
2348
def test_is_oserror(self):
2349
self.assertTrue(osutils.is_environment_error(
2350
OSError(errno.EINVAL, "Invalid parameter")))
2352
def test_is_ioerror(self):
2353
self.assertTrue(osutils.is_environment_error(
2354
IOError(errno.EINVAL, "Invalid parameter")))
2356
def test_is_socket_error(self):
2357
self.assertTrue(osutils.is_environment_error(
2358
socket.error(errno.EINVAL, "Invalid parameter")))
2360
def test_is_select_error(self):
2361
self.assertTrue(osutils.is_environment_error(
2362
select.error(errno.EINVAL, "Invalid parameter")))
2364
def test_is_pywintypes_error(self):
2365
self.requireFeature(features.pywintypes)
2367
self.assertTrue(osutils.is_environment_error(
2368
pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))