/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3959.1.4 by Martin Pool
test_resource_string shouldn't depend on the precise source file contents
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
16
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
17
"""Tests for the osutils wrapper."""
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
18
3504.4.12 by John Arbash Meinel
A couple small cleanups, make test_osutils more correct
19
from cStringIO import StringIO
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
20
import errno
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
21
import os
4183.6.4 by Martin Pool
Separate out re_compile_checked
22
import re
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
23
import socket
24
import stat
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
25
import sys
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
26
import time
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
27
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
28
from bzrlib import (
29
    errors,
30
    osutils,
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
31
    tests,
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
32
    trace,
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
33
    win32utils,
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
34
    )
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
35
from bzrlib.tests import (
36
    file_utils,
37
    test__walkdirs_win32,
38
    )
4297.1.1 by Vincent Ladeuil
Trivial cleanups.
39
40
4241.14.3 by Vincent Ladeuil
Cleanup imports.
41
class _UTF8DirReaderFeature(tests.Feature):
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
42
43
    def _probe(self):
44
        try:
45
            from bzrlib import _readdir_pyx
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
46
            self.reader = _readdir_pyx.UTF8DirReader
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
47
            return True
48
        except ImportError:
49
            return False
50
51
    def feature_name(self):
1739.2.13 by Robert Collins
Fix typo in ReadDirFeature.
52
        return 'bzrlib._readdir_pyx'
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
53
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
54
UTF8DirReaderFeature = _UTF8DirReaderFeature()
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
55
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
56
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
57
def _already_unicode(s):
58
    return s
59
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
60
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
61
def _utf8_to_unicode(s):
62
    return s.decode('UTF-8')
63
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
64
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
65
def dir_reader_scenarios():
66
    # For each dir reader we define:
67
68
    # - native_to_unicode: a function converting the native_abspath as returned
69
    #   by DirReader.read_dir to its unicode representation
70
71
    # UnicodeDirReader is the fallback, it should be tested on all platforms.
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
72
    scenarios = [('unicode',
73
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
74
                       _native_to_unicode=_already_unicode))]
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
75
    # Some DirReaders are platform specific and even there they may not be
76
    # available.
77
    if UTF8DirReaderFeature.available():
78
        from bzrlib import _readdir_pyx
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
79
        scenarios.append(('utf8',
80
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
81
                               _native_to_unicode=_utf8_to_unicode)))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
82
83
    if test__walkdirs_win32.Win32ReadDirFeature.available():
84
        try:
85
            from bzrlib import _walkdirs_win32
4241.14.24 by Vincent Ladeuil
Fixed as per John's review.
86
            scenarios.append(
87
                ('win32',
88
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
4789.25.3 by John Arbash Meinel
For DirReader tests, the 'fs path' on win32 is a Unicode string, no need to decode/encode.
89
                      _native_to_unicode=_already_unicode)))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
90
        except ImportError:
91
            pass
92
    return scenarios
93
94
95
def load_tests(basic_tests, module, loader):
96
    suite = loader.suiteClass()
97
    dir_reader_tests, remaining_tests = tests.split_suite_by_condition(
98
        basic_tests, tests.condition_isinstance(TestDirReader))
99
    tests.multiply_tests(dir_reader_tests, dir_reader_scenarios(), suite)
100
    suite.addTest(remaining_tests)
101
    return suite
102
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
103
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
104
class TestContainsWhitespace(tests.TestCase):
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
105
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
106
    def test_contains_whitespace(self):
107
        self.failUnless(osutils.contains_whitespace(u' '))
108
        self.failUnless(osutils.contains_whitespace(u'hello there'))
109
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
110
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
111
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
112
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
113
114
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
115
        # is whitespace, but we do not.
116
        self.failIf(osutils.contains_whitespace(u''))
117
        self.failIf(osutils.contains_whitespace(u'hellothere'))
118
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
119
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
120
121
class TestRename(tests.TestCaseInTempDir):
122
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
123
    def create_file(self, filename, content):
124
        f = open(filename, 'wb')
125
        try:
126
            f.write(content)
127
        finally:
128
            f.close()
129
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
130
    def _fancy_rename(self, a, b):
131
        osutils.fancy_rename(a, b, rename_func=os.rename,
132
                             unlink_func=os.unlink)
133
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
134
    def test_fancy_rename(self):
135
        # This should work everywhere
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
136
        self.create_file('a', 'something in a\n')
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
137
        self._fancy_rename('a', 'b')
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
138
        self.failIfExists('a')
139
        self.failUnlessExists('b')
140
        self.check_file_contents('b', 'something in a\n')
141
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
142
        self.create_file('a', 'new something in a\n')
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
143
        self._fancy_rename('b', 'a')
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
144
145
        self.check_file_contents('a', 'something in a\n')
146
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
147
    def test_fancy_rename_fails_source_missing(self):
148
        # An exception should be raised, and the target should be left in place
149
        self.create_file('target', 'data in target\n')
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
150
        self.assertRaises((IOError, OSError), self._fancy_rename,
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
151
                          'missingsource', 'target')
152
        self.failUnlessExists('target')
153
        self.check_file_contents('target', 'data in target\n')
154
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
155
    def test_fancy_rename_fails_if_source_and_target_missing(self):
156
        self.assertRaises((IOError, OSError), self._fancy_rename,
157
                          'missingsource', 'missingtarget')
158
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
159
    def test_rename(self):
160
        # Rename should be semi-atomic on all platforms
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
161
        self.create_file('a', 'something in a\n')
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
162
        osutils.rename('a', 'b')
163
        self.failIfExists('a')
164
        self.failUnlessExists('b')
165
        self.check_file_contents('b', 'something in a\n')
166
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
167
        self.create_file('a', 'new something in a\n')
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
168
        osutils.rename('b', 'a')
169
170
        self.check_file_contents('a', 'something in a\n')
171
172
    # TODO: test fancy_rename using a MemoryTransport
173
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
174
    def test_rename_change_case(self):
175
        # on Windows we should be able to change filename case by rename
2978.8.1 by Alexander Belchenko
Rename on Windows is able to change filename case. (#77740)
176
        self.build_tree(['a', 'b/'])
177
        osutils.rename('a', 'A')
178
        osutils.rename('b', 'B')
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
179
        # we can't use failUnlessExists on case-insensitive filesystem
180
        # so try to check shape of the tree
2978.8.1 by Alexander Belchenko
Rename on Windows is able to change filename case. (#77740)
181
        shape = sorted(os.listdir('.'))
182
        self.assertEquals(['A', 'B'], shape)
183
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
184
185
class TestRandChars(tests.TestCase):
186
1553.5.5 by Martin Pool
New utility routine rand_chars
187
    def test_01_rand_chars_empty(self):
188
        result = osutils.rand_chars(0)
189
        self.assertEqual(result, '')
190
191
    def test_02_rand_chars_100(self):
192
        result = osutils.rand_chars(100)
193
        self.assertEqual(len(result), 100)
194
        self.assertEqual(type(result), str)
195
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
196
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
197
198
class TestIsInside(tests.TestCase):
199
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
200
    def test_is_inside(self):
201
        is_inside = osutils.is_inside
202
        self.assertTrue(is_inside('src', 'src/foo.c'))
203
        self.assertFalse(is_inside('src', 'srccontrol'))
204
        self.assertTrue(is_inside('src', 'src/a/a/a/foo.c'))
205
        self.assertTrue(is_inside('foo.c', 'foo.c'))
206
        self.assertFalse(is_inside('foo.c', ''))
207
        self.assertTrue(is_inside('', 'foo.c'))
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
208
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
209
    def test_is_inside_any(self):
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
210
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
211
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
212
                         (['src'], SRC_FOO_C),
213
                         (['src'], 'src'),
214
                         ]:
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
215
            self.assert_(osutils.is_inside_any(dirs, fn))
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
216
        for dirs, fn in [(['src'], 'srccontrol'),
217
                         (['src'], 'srccontrol/foo')]:
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
218
            self.assertFalse(osutils.is_inside_any(dirs, fn))
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
219
220
    def test_is_inside_or_parent_of_any(self):
221
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
222
                         (['src'], 'src/foo.c'),
223
                         (['src/bar.c'], 'src'),
224
                         (['src/bar.c', 'bla/foo.c'], 'src'),
225
                         (['src'], 'src'),
226
                         ]:
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
227
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
228
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
229
        for dirs, fn in [(['src'], 'srccontrol'),
230
                         (['srccontrol/foo.c'], 'src'),
231
                         (['src'], 'srccontrol/foo')]:
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
232
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
233
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
234
235
class TestRmTree(tests.TestCaseInTempDir):
236
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
237
    def test_rmtree(self):
238
        # Check to remove tree with read-only files/dirs
239
        os.mkdir('dir')
240
        f = file('dir/file', 'w')
241
        f.write('spam')
242
        f.close()
243
        # would like to also try making the directory readonly, but at the
244
        # moment python shutil.rmtree doesn't handle that properly - it would
245
        # need to chmod the directory before removing things inside it - deferred
246
        # for now -- mbp 20060505
247
        # osutils.make_readonly('dir')
248
        osutils.make_readonly('dir/file')
249
250
        osutils.rmtree('dir')
251
252
        self.failIfExists('dir/file')
253
        self.failIfExists('dir')
254
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
255
4490.1.2 by Martin Pool
test and news for forcing readonly deletion
256
class TestDeleteAny(tests.TestCaseInTempDir):
257
258
    def test_delete_any_readonly(self):
259
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
260
        self.build_tree(['d/', 'f'])
261
        osutils.make_readonly('d')
262
        osutils.make_readonly('f')
263
264
        osutils.delete_any('f')
265
        osutils.delete_any('d')
266
267
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
268
class TestKind(tests.TestCaseInTempDir):
269
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
270
    def test_file_kind(self):
271
        self.build_tree(['file', 'dir/'])
272
        self.assertEquals('file', osutils.file_kind('file'))
273
        self.assertEquals('directory', osutils.file_kind('dir/'))
274
        if osutils.has_symlinks():
275
            os.symlink('symlink', 'symlink')
276
            self.assertEquals('symlink', osutils.file_kind('symlink'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
277
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
278
        # TODO: jam 20060529 Test a block device
279
        try:
280
            os.lstat('/dev/null')
281
        except OSError, e:
282
            if e.errno not in (errno.ENOENT,):
283
                raise
284
        else:
285
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
286
287
        mkfifo = getattr(os, 'mkfifo', None)
288
        if mkfifo:
289
            mkfifo('fifo')
290
            try:
291
                self.assertEquals('fifo', osutils.file_kind('fifo'))
292
            finally:
293
                os.remove('fifo')
294
295
        AF_UNIX = getattr(socket, 'AF_UNIX', None)
296
        if AF_UNIX:
297
            s = socket.socket(AF_UNIX)
298
            s.bind('socket')
299
            try:
300
                self.assertEquals('socket', osutils.file_kind('socket'))
301
            finally:
302
                os.remove('socket')
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
303
1551.10.27 by Aaron Bentley
Add a kind marker for subtrees
304
    def test_kind_marker(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
305
        self.assertEqual("", osutils.kind_marker("file"))
306
        self.assertEqual("/", osutils.kind_marker('directory'))
307
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
308
        self.assertEqual("@", osutils.kind_marker("symlink"))
309
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
310
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
311
312
313
class TestUmask(tests.TestCaseInTempDir):
1551.10.27 by Aaron Bentley
Add a kind marker for subtrees
314
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
315
    def test_get_umask(self):
316
        if sys.platform == 'win32':
317
            # umask always returns '0', no way to set it
318
            self.assertEqual(0, osutils.get_umask())
319
            return
320
321
        orig_umask = osutils.get_umask()
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
322
        self.addCleanup(os.umask, orig_umask)
323
        os.umask(0222)
324
        self.assertEqual(0222, osutils.get_umask())
325
        os.umask(0022)
326
        self.assertEqual(0022, osutils.get_umask())
327
        os.umask(0002)
328
        self.assertEqual(0002, osutils.get_umask())
329
        os.umask(0027)
330
        self.assertEqual(0027, osutils.get_umask())
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
331
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
332
333
class TestDateTime(tests.TestCase):
334
1957.1.15 by John Arbash Meinel
Review feedback from Robert
335
    def assertFormatedDelta(self, expected, seconds):
336
        """Assert osutils.format_delta formats as expected"""
337
        actual = osutils.format_delta(seconds)
338
        self.assertEqual(expected, actual)
339
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
340
    def test_format_delta(self):
1957.1.15 by John Arbash Meinel
Review feedback from Robert
341
        self.assertFormatedDelta('0 seconds ago', 0)
342
        self.assertFormatedDelta('1 second ago', 1)
343
        self.assertFormatedDelta('10 seconds ago', 10)
344
        self.assertFormatedDelta('59 seconds ago', 59)
345
        self.assertFormatedDelta('89 seconds ago', 89)
346
        self.assertFormatedDelta('1 minute, 30 seconds ago', 90)
347
        self.assertFormatedDelta('3 minutes, 0 seconds ago', 180)
348
        self.assertFormatedDelta('3 minutes, 1 second ago', 181)
349
        self.assertFormatedDelta('10 minutes, 15 seconds ago', 615)
350
        self.assertFormatedDelta('30 minutes, 59 seconds ago', 1859)
351
        self.assertFormatedDelta('31 minutes, 0 seconds ago', 1860)
352
        self.assertFormatedDelta('60 minutes, 0 seconds ago', 3600)
353
        self.assertFormatedDelta('89 minutes, 59 seconds ago', 5399)
354
        self.assertFormatedDelta('1 hour, 30 minutes ago', 5400)
355
        self.assertFormatedDelta('2 hours, 30 minutes ago', 9017)
356
        self.assertFormatedDelta('10 hours, 0 minutes ago', 36000)
357
        self.assertFormatedDelta('24 hours, 0 minutes ago', 86400)
358
        self.assertFormatedDelta('35 hours, 59 minutes ago', 129599)
359
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129600)
360
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129601)
361
        self.assertFormatedDelta('36 hours, 1 minute ago', 129660)
362
        self.assertFormatedDelta('36 hours, 1 minute ago', 129661)
363
        self.assertFormatedDelta('84 hours, 10 minutes ago', 303002)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
364
365
        # We handle when time steps the wrong direction because computers
366
        # don't have synchronized clocks.
1957.1.15 by John Arbash Meinel
Review feedback from Robert
367
        self.assertFormatedDelta('84 hours, 10 minutes in the future', -303002)
368
        self.assertFormatedDelta('1 second in the future', -1)
369
        self.assertFormatedDelta('2 seconds in the future', -2)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
370
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
371
    def test_format_date(self):
372
        self.assertRaises(errors.UnsupportedTimezoneFormat,
373
            osutils.format_date, 0, timezone='foo')
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
374
        self.assertIsInstance(osutils.format_date(0), str)
375
        self.assertIsInstance(osutils.format_local_date(0), unicode)
376
        # Testing for the actual value of the local weekday without
3526.5.2 by Martin von Gagern
Check output type of format_date
377
        # duplicating the code from format_date is difficult.
378
        # Instead blackbox.test_locale should check for localized
379
        # dates once they do occur in output strings.
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
380
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
381
    def test_local_time_offset(self):
382
        """Test that local_time_offset() returns a sane value."""
383
        offset = osutils.local_time_offset()
384
        self.assertTrue(isinstance(offset, int))
385
        # Test that the offset is no more than a eighteen hours in
386
        # either direction.
387
        # Time zone handling is system specific, so it is difficult to
388
        # do more specific tests, but a value outside of this range is
389
        # probably wrong.
390
        eighteen_hours = 18 * 3600
391
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
392
393
    def test_local_time_offset_with_timestamp(self):
394
        """Test that local_time_offset() works with a timestamp."""
395
        offset = osutils.local_time_offset(1000000000.1234567)
396
        self.assertTrue(isinstance(offset, int))
397
        eighteen_hours = 18 * 3600
398
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
399
400
401
class TestLinks(tests.TestCaseInTempDir):
402
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
403
    def test_dereference_path(self):
4241.14.3 by Vincent Ladeuil
Cleanup imports.
404
        self.requireFeature(tests.SymlinkFeature)
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
405
        cwd = osutils.realpath('.')
406
        os.mkdir('bar')
407
        bar_path = osutils.pathjoin(cwd, 'bar')
408
        # Using './' to avoid bug #1213894 (first path component not
409
        # dereferenced) in Python 2.4.1 and earlier
410
        self.assertEqual(bar_path, osutils.realpath('./bar'))
411
        os.symlink('bar', 'foo')
412
        self.assertEqual(bar_path, osutils.realpath('./foo'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
413
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
414
        # Does not dereference terminal symlinks
415
        foo_path = osutils.pathjoin(cwd, 'foo')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
416
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
417
418
        # Dereferences parent symlinks
419
        os.mkdir('bar/baz')
420
        baz_path = osutils.pathjoin(bar_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
421
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
422
423
        # Dereferences parent symlinks that are the first path element
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
424
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
425
426
        # Dereferences parent symlinks in absolute paths
427
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
428
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
429
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
430
    def test_changing_access(self):
431
        f = file('file', 'w')
432
        f.write('monkey')
433
        f.close()
434
435
        # Make a file readonly
436
        osutils.make_readonly('file')
2949.6.2 by Alexander Belchenko
more changes osutils.lstat -> os.lstat
437
        mode = os.lstat('file').st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
438
        self.assertEqual(mode, mode & 0777555)
439
440
        # Make a file writable
441
        osutils.make_writable('file')
2949.6.2 by Alexander Belchenko
more changes osutils.lstat -> os.lstat
442
        mode = os.lstat('file').st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
443
        self.assertEqual(mode, mode | 0200)
444
445
        if osutils.has_symlinks():
446
            # should not error when handed a symlink
447
            os.symlink('nonexistent', 'dangling')
448
            osutils.make_readonly('dangling')
449
            osutils.make_writable('dangling')
450
3287.18.26 by Matt McClure
Addresses concerns raised in
451
    def test_host_os_dereferences_symlinks(self):
452
        osutils.host_os_dereferences_symlinks()
453
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
454
4241.14.3 by Vincent Ladeuil
Cleanup imports.
455
class TestCanonicalRelPath(tests.TestCaseInTempDir):
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
456
4241.14.3 by Vincent Ladeuil
Cleanup imports.
457
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
458
459
    def test_canonical_relpath_simple(self):
460
        f = file('MixedCaseName', 'w')
461
        f.close()
4707.1.1 by Vincent Ladeuil
Fix OSX and FreeBSD failures.
462
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
463
        self.failUnlessEqual('work/MixedCaseName', actual)
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
464
465
    def test_canonical_relpath_missing_tail(self):
466
        os.mkdir('MixedCaseParent')
4707.1.1 by Vincent Ladeuil
Fix OSX and FreeBSD failures.
467
        actual = osutils.canonical_relpath(self.test_base_dir,
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
468
                                           'mixedcaseparent/nochild')
469
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
470
471
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
472
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
473
474
    def assertRelpath(self, expected, base, path):
475
        actual = osutils._cicp_canonical_relpath(base, path)
476
        self.assertEqual(expected, actual)
477
478
    def test_simple(self):
479
        self.build_tree(['MixedCaseName'])
480
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
481
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
482
483
    def test_subdir_missing_tail(self):
484
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
485
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
486
        self.assertRelpath('MixedCaseParent/a_child', base,
487
                           'MixedCaseParent/a_child')
488
        self.assertRelpath('MixedCaseParent/a_child', base,
489
                           'MixedCaseParent/A_Child')
490
        self.assertRelpath('MixedCaseParent/not_child', base,
491
                           'MixedCaseParent/not_child')
492
4634.70.6 by John Arbash Meinel
Mix up the test a bit. On Windows we don't run the '/' test
493
    def test_at_root_slash(self):
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
494
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
495
        # check...
4634.70.4 by John Arbash Meinel
Take spiv's suggestion and move the '/' test to another test case.
496
        if osutils.MIN_ABS_PATHLENGTH > 1:
4634.70.6 by John Arbash Meinel
Mix up the test a bit. On Windows we don't run the '/' test
497
            raise tests.TestSkipped('relpath requires %d chars'
498
                                    % osutils.MIN_ABS_PATHLENGTH)
4634.70.4 by John Arbash Meinel
Take spiv's suggestion and move the '/' test to another test case.
499
        self.assertRelpath('foo', '/', '/foo')
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
500
4634.70.6 by John Arbash Meinel
Mix up the test a bit. On Windows we don't run the '/' test
501
    def test_at_root_drive(self):
502
        if sys.platform != 'win32':
503
            raise tests.TestNotApplicable('we can only test drive-letter relative'
504
                                          ' paths on Windows where we have drive'
505
                                          ' letters.')
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
506
        # see bug #322807
507
        # The specific issue is that when at the root of a drive, 'abspath'
508
        # returns "C:/" or just "/". However, the code assumes that abspath
509
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
510
        self.assertRelpath('foo', 'C:/', 'C:/foo')
511
        self.assertRelpath('foo', 'X:/', 'X:/foo')
512
        self.assertRelpath('foo', 'X:/', 'X://foo')
513
514
4241.14.3 by Vincent Ladeuil
Cleanup imports.
515
class TestPumpFile(tests.TestCase):
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
516
    """Test pumpfile method."""
4241.14.3 by Vincent Ladeuil
Cleanup imports.
517
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
518
    def setUp(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
519
        tests.TestCase.setUp(self)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
520
        # create a test datablock
521
        self.block_size = 512
522
        pattern = '0123456789ABCDEF'
523
        self.test_data = pattern * (3 * self.block_size / len(pattern))
524
        self.test_data_len = len(self.test_data)
525
526
    def test_bracket_block_size(self):
527
        """Read data in blocks with the requested read size bracketing the
528
        block size."""
529
        # make sure test data is larger than max read size
530
        self.assertTrue(self.test_data_len > self.block_size)
531
4241.14.3 by Vincent Ladeuil
Cleanup imports.
532
        from_file = file_utils.FakeReadFile(self.test_data)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
533
        to_file = StringIO()
534
535
        # read (max / 2) bytes and verify read size wasn't affected
536
        num_bytes_to_read = self.block_size / 2
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
537
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
538
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
539
        self.assertEqual(from_file.get_read_count(), 1)
540
541
        # read (max) bytes and verify read size wasn't affected
542
        num_bytes_to_read = self.block_size
543
        from_file.reset_read_count()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
544
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
545
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
546
        self.assertEqual(from_file.get_read_count(), 1)
547
548
        # read (max + 1) bytes and verify read size was limited
549
        num_bytes_to_read = self.block_size + 1
550
        from_file.reset_read_count()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
551
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
552
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
553
        self.assertEqual(from_file.get_read_count(), 2)
554
555
        # finish reading the rest of the data
556
        num_bytes_to_read = self.test_data_len - to_file.tell()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
557
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
558
559
        # report error if the data wasn't equal (we only report the size due
560
        # to the length of the data)
561
        response_data = to_file.getvalue()
562
        if response_data != self.test_data:
563
            message = "Data not equal.  Expected %d bytes, received %d."
564
            self.fail(message % (len(response_data), self.test_data_len))
565
566
    def test_specified_size(self):
567
        """Request a transfer larger than the maximum block size and verify
568
        that the maximum read doesn't exceed the block_size."""
569
        # make sure test data is larger than max read size
570
        self.assertTrue(self.test_data_len > self.block_size)
571
572
        # retrieve data in blocks
4241.14.3 by Vincent Ladeuil
Cleanup imports.
573
        from_file = file_utils.FakeReadFile(self.test_data)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
574
        to_file = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
575
        osutils.pumpfile(from_file, to_file, self.test_data_len,
576
                         self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
577
578
        # verify read size was equal to the maximum read size
579
        self.assertTrue(from_file.get_max_read_size() > 0)
580
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
581
        self.assertEqual(from_file.get_read_count(), 3)
582
583
        # report error if the data wasn't equal (we only report the size due
584
        # to the length of the data)
585
        response_data = to_file.getvalue()
586
        if response_data != self.test_data:
587
            message = "Data not equal.  Expected %d bytes, received %d."
588
            self.fail(message % (len(response_data), self.test_data_len))
589
590
    def test_to_eof(self):
591
        """Read to end-of-file and verify that the reads are not larger than
592
        the maximum read size."""
593
        # make sure test data is larger than max read size
594
        self.assertTrue(self.test_data_len > self.block_size)
595
596
        # retrieve data to EOF
4241.14.3 by Vincent Ladeuil
Cleanup imports.
597
        from_file = file_utils.FakeReadFile(self.test_data)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
598
        to_file = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
599
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
600
601
        # verify read size was equal to the maximum read size
602
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
603
        self.assertEqual(from_file.get_read_count(), 4)
604
605
        # report error if the data wasn't equal (we only report the size due
606
        # to the length of the data)
607
        response_data = to_file.getvalue()
608
        if response_data != self.test_data:
609
            message = "Data not equal.  Expected %d bytes, received %d."
610
            self.fail(message % (len(response_data), self.test_data_len))
611
612
    def test_defaults(self):
613
        """Verifies that the default arguments will read to EOF -- this
614
        test verifies that any existing usages of pumpfile will not be broken
615
        with this new version."""
616
        # retrieve data using default (old) pumpfile method
4241.14.3 by Vincent Ladeuil
Cleanup imports.
617
        from_file = file_utils.FakeReadFile(self.test_data)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
618
        to_file = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
619
        osutils.pumpfile(from_file, to_file)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
620
621
        # report error if the data wasn't equal (we only report the size due
622
        # to the length of the data)
623
        response_data = to_file.getvalue()
624
        if response_data != self.test_data:
625
            message = "Data not equal.  Expected %d bytes, received %d."
626
            self.fail(message % (len(response_data), self.test_data_len))
627
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
628
    def test_report_activity(self):
629
        activity = []
630
        def log_activity(length, direction):
631
            activity.append((length, direction))
632
        from_file = StringIO(self.test_data)
633
        to_file = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
634
        osutils.pumpfile(from_file, to_file, buff_size=500,
635
                         report_activity=log_activity, direction='read')
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
636
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
637
                          (36, 'read')], activity)
638
639
        from_file = StringIO(self.test_data)
640
        to_file = StringIO()
641
        del activity[:]
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
642
        osutils.pumpfile(from_file, to_file, buff_size=500,
643
                         report_activity=log_activity, direction='write')
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
644
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
645
                          (36, 'write')], activity)
646
647
        # And with a limited amount of data
648
        from_file = StringIO(self.test_data)
649
        to_file = StringIO()
650
        del activity[:]
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
651
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
652
                         report_activity=log_activity, direction='read')
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
653
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
654
655
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
656
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
657
class TestPumpStringFile(tests.TestCase):
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
658
659
    def test_empty(self):
660
        output = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
661
        osutils.pump_string_file("", output)
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
662
        self.assertEqual("", output.getvalue())
663
664
    def test_more_than_segment_size(self):
665
        output = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
666
        osutils.pump_string_file("123456789", output, 2)
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
667
        self.assertEqual("123456789", output.getvalue())
668
669
    def test_segment_size(self):
670
        output = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
671
        osutils.pump_string_file("12", output, 2)
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
672
        self.assertEqual("12", output.getvalue())
673
674
    def test_segment_size_multiple(self):
675
        output = StringIO()
4241.9.3 by Vincent Ladeuil
Fix two more test failures specific to OSX.
676
        osutils.pump_string_file("1234", output, 2)
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
677
        self.assertEqual("1234", output.getvalue())
678
679
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
680
class TestRelpath(tests.TestCase):
681
682
    def test_simple_relpath(self):
683
        cwd = osutils.getcwd()
684
        subdir = cwd + '/subdir'
685
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
686
4555.2.3 by John Arbash Meinel
Fix a trivial bug that should have been caught earlier. :)
687
    def test_deep_relpath(self):
688
        cwd = osutils.getcwd()
689
        subdir = cwd + '/sub/subsubdir'
690
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
691
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
692
    def test_not_relative(self):
693
        self.assertRaises(errors.PathNotChild,
694
                          osutils.relpath, 'C:/path', 'H:/path')
695
        self.assertRaises(errors.PathNotChild,
696
                          osutils.relpath, 'C:/', 'H:/path')
697
698
4241.14.3 by Vincent Ladeuil
Cleanup imports.
699
class TestSafeUnicode(tests.TestCase):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
700
701
    def test_from_ascii_string(self):
702
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
703
1534.3.2 by Robert Collins
An extra test for John.
704
    def test_from_unicode_string_ascii_contents(self):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
705
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
706
1534.3.2 by Robert Collins
An extra test for John.
707
    def test_from_unicode_string_unicode_contents(self):
708
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
709
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
710
    def test_from_utf8_string(self):
711
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
712
713
    def test_bad_utf8_string(self):
4241.14.3 by Vincent Ladeuil
Cleanup imports.
714
        self.assertRaises(errors.BzrBadParameterNotUnicode,
1185.65.29 by Robert Collins
Implement final review suggestions.
715
                          osutils.safe_unicode,
716
                          '\xbb\xbb')
1666.1.6 by Robert Collins
Make knit the default format.
717
718
4241.14.3 by Vincent Ladeuil
Cleanup imports.
719
class TestSafeUtf8(tests.TestCase):
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
720
721
    def test_from_ascii_string(self):
722
        f = 'foobar'
723
        self.assertEqual('foobar', osutils.safe_utf8(f))
724
725
    def test_from_unicode_string_ascii_contents(self):
726
        self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
727
728
    def test_from_unicode_string_unicode_contents(self):
729
        self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
730
731
    def test_from_utf8_string(self):
732
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
733
734
    def test_bad_utf8_string(self):
4241.14.3 by Vincent Ladeuil
Cleanup imports.
735
        self.assertRaises(errors.BzrBadParameterNotUnicode,
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
736
                          osutils.safe_utf8, '\xbb\xbb')
737
738
4241.14.3 by Vincent Ladeuil
Cleanup imports.
739
class TestSafeRevisionId(tests.TestCase):
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
740
741
    def test_from_ascii_string(self):
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
742
        # this shouldn't give a warning because it's getting an ascii string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
743
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
744
745
    def test_from_unicode_string_ascii_contents(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
746
        self.assertEqual('bargam',
747
                         osutils.safe_revision_id(u'bargam', warn=False))
748
749
    def test_from_unicode_deprecated(self):
750
        self.assertEqual('bargam',
751
            self.callDeprecated([osutils._revision_id_warning],
752
                                osutils.safe_revision_id, u'bargam'))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
753
754
    def test_from_unicode_string_unicode_contents(self):
755
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
756
                         osutils.safe_revision_id(u'bargam\xae', warn=False))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
757
758
    def test_from_utf8_string(self):
759
        self.assertEqual('foo\xc2\xae',
760
                         osutils.safe_revision_id('foo\xc2\xae'))
761
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
762
    def test_none(self):
763
        """Currently, None is a valid revision_id"""
764
        self.assertEqual(None, osutils.safe_revision_id(None))
765
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
766
4241.14.3 by Vincent Ladeuil
Cleanup imports.
767
class TestSafeFileId(tests.TestCase):
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
768
769
    def test_from_ascii_string(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
770
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
771
772
    def test_from_unicode_string_ascii_contents(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
773
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
774
775
    def test_from_unicode_deprecated(self):
776
        self.assertEqual('bargam',
777
            self.callDeprecated([osutils._file_id_warning],
778
                                osutils.safe_file_id, u'bargam'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
779
780
    def test_from_unicode_string_unicode_contents(self):
781
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
782
                         osutils.safe_file_id(u'bargam\xae', warn=False))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
783
784
    def test_from_utf8_string(self):
785
        self.assertEqual('foo\xc2\xae',
786
                         osutils.safe_file_id('foo\xc2\xae'))
787
788
    def test_none(self):
789
        """Currently, None is a valid revision_id"""
790
        self.assertEqual(None, osutils.safe_file_id(None))
791
792
4241.14.3 by Vincent Ladeuil
Cleanup imports.
793
class TestWin32Funcs(tests.TestCase):
794
    """Test that _win32 versions of os utilities return appropriate paths."""
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
795
796
    def test_abspath(self):
797
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
798
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
799
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
800
        self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
801
802
    def test_realpath(self):
803
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
804
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
805
806
    def test_pathjoin(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
807
        self.assertEqual('path/to/foo',
808
                         osutils._win32_pathjoin('path', 'to', 'foo'))
809
        self.assertEqual('C:/foo',
810
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
811
        self.assertEqual('C:/foo',
812
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
813
        self.assertEqual('path/to/foo',
814
                         osutils._win32_pathjoin('path/to/', 'foo'))
815
        self.assertEqual('/foo',
816
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
817
        self.assertEqual('/foo',
818
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
819
820
    def test_normpath(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
821
        self.assertEqual('path/to/foo',
822
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
823
        self.assertEqual('path/to/foo',
824
                         osutils._win32_normpath('path//from/../to/./foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
825
826
    def test_getcwd(self):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
827
        cwd = osutils._win32_getcwd()
828
        os_cwd = os.getcwdu()
829
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
830
        # win32 is inconsistent whether it returns lower or upper case
831
        # and even if it was consistent the user might type the other
832
        # so we force it to uppercase
833
        # running python.exe under cmd.exe return capital C:\\
834
        # running win32 python inside a cygwin shell returns lowercase
835
        self.assertEqual(os_cwd[0].upper(), cwd[0])
836
837
    def test_fixdrive(self):
838
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
839
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
840
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
841
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
842
    def test_win98_abspath(self):
843
        # absolute path
844
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
845
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
846
        # UNC path
847
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
848
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
849
        # relative path
850
        cwd = osutils.getcwd().rstrip('/')
851
        drive = osutils._nt_splitdrive(cwd)[0]
852
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
853
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
854
        # unicode path
855
        u = u'\u1234'
856
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
857
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
858
4241.14.3 by Vincent Ladeuil
Cleanup imports.
859
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
860
    """Test win32 functions that create files."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
861
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
862
    def test_getcwd(self):
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
863
        self.requireFeature(tests.UnicodeFilenameFeature)
864
        os.mkdir(u'mu-\xb5')
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
865
        os.chdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
866
        # TODO: jam 20060427 This will probably fail on Mac OSX because
867
        #       it will change the normalization of B\xe5gfors
868
        #       Consider using a different unicode character, or make
869
        #       osutils.getcwd() renormalize the path.
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
870
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
871
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
872
    def test_minimum_path_selection(self):
873
        self.assertEqual(set(),
874
            osutils.minimum_path_selection([]))
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
875
        self.assertEqual(set(['a']),
876
            osutils.minimum_path_selection(['a']))
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
877
        self.assertEqual(set(['a', 'b']),
878
            osutils.minimum_path_selection(['a', 'b']))
879
        self.assertEqual(set(['a/', 'b']),
880
            osutils.minimum_path_selection(['a/', 'b']))
881
        self.assertEqual(set(['a/', 'b']),
882
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
883
        self.assertEqual(set(['a-b', 'a', 'a0b']),
884
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
885
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
886
    def test_mkdtemp(self):
887
        tmpdir = osutils._win32_mkdtemp(dir='.')
888
        self.assertFalse('\\' in tmpdir)
889
890
    def test_rename(self):
891
        a = open('a', 'wb')
892
        a.write('foo\n')
893
        a.close()
894
        b = open('b', 'wb')
895
        b.write('baz\n')
896
        b.close()
897
898
        osutils._win32_rename('b', 'a')
899
        self.failUnlessExists('a')
900
        self.failIfExists('b')
901
        self.assertFileEqual('baz\n', 'a')
902
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
903
    def test_rename_missing_file(self):
904
        a = open('a', 'wb')
905
        a.write('foo\n')
906
        a.close()
907
908
        try:
909
            osutils._win32_rename('b', 'a')
910
        except (IOError, OSError), e:
911
            self.assertEqual(errno.ENOENT, e.errno)
912
        self.assertFileEqual('foo\n', 'a')
913
914
    def test_rename_missing_dir(self):
915
        os.mkdir('a')
916
        try:
917
            osutils._win32_rename('b', 'a')
918
        except (IOError, OSError), e:
919
            self.assertEqual(errno.ENOENT, e.errno)
920
921
    def test_rename_current_dir(self):
922
        os.mkdir('a')
923
        os.chdir('a')
924
        # You can't rename the working directory
925
        # doing rename non-existant . usually
926
        # just raises ENOENT, since non-existant
927
        # doesn't exist.
928
        try:
929
            osutils._win32_rename('b', '.')
930
        except (IOError, OSError), e:
931
            self.assertEqual(errno.ENOENT, e.errno)
932
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
933
    def test_splitpath(self):
934
        def check(expected, path):
935
            self.assertEqual(expected, osutils.splitpath(path))
936
937
        check(['a'], 'a')
938
        check(['a', 'b'], 'a/b')
939
        check(['a', 'b'], 'a/./b')
940
        check(['a', '.b'], 'a/.b')
941
        check(['a', '.b'], 'a\\.b')
942
943
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
944
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
945
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
946
class TestParentDirectories(tests.TestCaseInTempDir):
947
    """Test osutils.parent_directories()"""
948
949
    def test_parent_directories(self):
950
        self.assertEqual([], osutils.parent_directories('a'))
951
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
952
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
953
954
4241.14.3 by Vincent Ladeuil
Cleanup imports.
955
class TestMacFuncsDirs(tests.TestCaseInTempDir):
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
956
    """Test mac special functions that require directories."""
957
958
    def test_getcwd(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
959
        self.requireFeature(tests.UnicodeFilenameFeature)
960
        os.mkdir(u'B\xe5gfors')
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
961
        os.chdir(u'B\xe5gfors')
962
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
963
964
    def test_getcwd_nonnorm(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
965
        self.requireFeature(tests.UnicodeFilenameFeature)
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
966
        # Test that _mac_getcwd() will normalize this path
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
967
        os.mkdir(u'Ba\u030agfors')
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
968
        os.chdir(u'Ba\u030agfors')
969
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
970
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
971
4241.14.3 by Vincent Ladeuil
Cleanup imports.
972
class TestChunksToLines(tests.TestCase):
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
973
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
974
    def test_smoketest(self):
975
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
976
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
977
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
978
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
979
3734.2.21 by Vincent Ladeuil
Give test a better name.
980
    def test_osutils_binding(self):
3734.2.20 by Vincent Ladeuil
Fix failing test when CompiledChunksToLines is not available.
981
        from bzrlib.tests import test__chunks_to_lines
982
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
983
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
984
        else:
985
            from bzrlib._chunks_to_lines_py import chunks_to_lines
986
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
3890.2.5 by John Arbash Meinel
More tests for edge cases.
987
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
988
4241.14.3 by Vincent Ladeuil
Cleanup imports.
989
class TestSplitLines(tests.TestCase):
1666.1.6 by Robert Collins
Make knit the default format.
990
991
    def test_split_unicode(self):
992
        self.assertEqual([u'foo\n', u'bar\xae'],
993
                         osutils.split_lines(u'foo\nbar\xae'))
994
        self.assertEqual([u'foo\n', u'bar\xae\n'],
995
                         osutils.split_lines(u'foo\nbar\xae\n'))
996
997
    def test_split_with_carriage_returns(self):
998
        self.assertEqual(['foo\rbar\n'],
999
                         osutils.split_lines('foo\rbar\n'))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1000
1001
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1002
class TestWalkDirs(tests.TestCaseInTempDir):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1003
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1004
    def assertExpectedBlocks(self, expected, result):
1005
        self.assertEqual(expected,
1006
                         [(dirinfo, [line[0:3] for line in block])
1007
                          for dirinfo, block in result])
1008
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1009
    def test_walkdirs(self):
1010
        tree = [
1011
            '.bzr',
1012
            '0file',
1013
            '1dir/',
1014
            '1dir/0file',
1015
            '1dir/1dir/',
1016
            '2file'
1017
            ]
1018
        self.build_tree(tree)
1019
        expected_dirblocks = [
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1020
                (('', '.'),
1021
                 [('0file', '0file', 'file'),
1022
                  ('1dir', '1dir', 'directory'),
1023
                  ('2file', '2file', 'file'),
1024
                 ]
1025
                ),
1026
                (('1dir', './1dir'),
1027
                 [('1dir/0file', '0file', 'file'),
1028
                  ('1dir/1dir', '1dir', 'directory'),
1029
                 ]
1030
                ),
1031
                (('1dir/1dir', './1dir/1dir'),
1032
                 [
1033
                 ]
1034
                ),
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1035
            ]
1036
        result = []
1037
        found_bzrdir = False
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1038
        for dirdetail, dirblock in osutils.walkdirs('.'):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1039
            if len(dirblock) and dirblock[0][1] == '.bzr':
1040
                # this tests the filtering of selected paths
1041
                found_bzrdir = True
1042
                del dirblock[0]
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1043
            result.append((dirdetail, dirblock))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1044
1045
        self.assertTrue(found_bzrdir)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1046
        self.assertExpectedBlocks(expected_dirblocks, result)
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1047
        # you can search a subdir only, with a supplied prefix.
1048
        result = []
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1049
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1050
            result.append(dirblock)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1051
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1052
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1053
    def test_walkdirs_os_error(self):
1054
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1055
        # Pyrex readdir didn't raise useful messages if it had an error
1056
        # reading the directory
1057
        if sys.platform == 'win32':
1058
            raise tests.TestNotApplicable(
1059
                "readdir IOError not tested on win32")
1060
        os.mkdir("test-unreadable")
1061
        os.chmod("test-unreadable", 0000)
1062
        # must chmod it back so that it can be removed
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1063
        self.addCleanup(os.chmod, "test-unreadable", 0700)
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1064
        # The error is not raised until the generator is actually evaluated.
1065
        # (It would be ok if it happened earlier but at the moment it
1066
        # doesn't.)
4133.1.1 by Vincent Ladeuil
Fix bzrlib.tests.test_osutils.TestWalkDirs.test_walkdirs_os_error
1067
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1068
        self.assertEquals('./test-unreadable', e.filename)
1069
        self.assertEquals(errno.EACCES, e.errno)
4133.1.2 by Vincent Ladeuil
Fixed as per Martin's remark about the intent of the test :-}
1070
        # Ensure the message contains the file name
1071
        self.assertContainsRe(str(e), "\./test-unreadable")
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1072
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1073
    def test__walkdirs_utf8(self):
1074
        tree = [
1075
            '.bzr',
1076
            '0file',
1077
            '1dir/',
1078
            '1dir/0file',
1079
            '1dir/1dir/',
1080
            '2file'
1081
            ]
1082
        self.build_tree(tree)
1083
        expected_dirblocks = [
1084
                (('', '.'),
1085
                 [('0file', '0file', 'file'),
1086
                  ('1dir', '1dir', 'directory'),
1087
                  ('2file', '2file', 'file'),
1088
                 ]
1089
                ),
1090
                (('1dir', './1dir'),
1091
                 [('1dir/0file', '0file', 'file'),
1092
                  ('1dir/1dir', '1dir', 'directory'),
1093
                 ]
1094
                ),
1095
                (('1dir/1dir', './1dir/1dir'),
1096
                 [
1097
                 ]
1098
                ),
1099
            ]
1100
        result = []
1101
        found_bzrdir = False
1102
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1103
            if len(dirblock) and dirblock[0][1] == '.bzr':
1104
                # this tests the filtering of selected paths
1105
                found_bzrdir = True
1106
                del dirblock[0]
1107
            result.append((dirdetail, dirblock))
1108
1109
        self.assertTrue(found_bzrdir)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1110
        self.assertExpectedBlocks(expected_dirblocks, result)
1111
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1112
        # you can search a subdir only, with a supplied prefix.
1113
        result = []
1114
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1115
            result.append(dirblock)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1116
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1117
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1118
    def _filter_out_stat(self, result):
1119
        """Filter out the stat value from the walkdirs result"""
1120
        for dirdetail, dirblock in result:
1121
            new_dirblock = []
1122
            for info in dirblock:
1123
                # Ignore info[3] which is the stat
1124
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1125
            dirblock[:] = new_dirblock
1126
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1127
    def _save_platform_info(self):
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1128
        cur_winver = win32utils.winver
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1129
        cur_fs_enc = osutils._fs_enc
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1130
        cur_dir_reader = osutils._selected_dir_reader
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1131
        def restore():
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1132
            win32utils.winver = cur_winver
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1133
            osutils._fs_enc = cur_fs_enc
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1134
            osutils._selected_dir_reader = cur_dir_reader
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1135
        self.addCleanup(restore)
1136
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1137
    def assertDirReaderIs(self, expected):
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1138
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1139
        # Force it to redetect
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1140
        osutils._selected_dir_reader = None
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1141
        # Nothing to list, but should still trigger the selection logic
3557.2.5 by John Arbash Meinel
Test that the empty-directory logic for all _walkdirs implementations is correct.
1142
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1143
        self.assertIsInstance(osutils._selected_dir_reader, expected)
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1144
1145
    def test_force_walkdirs_utf8_fs_utf8(self):
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1146
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1147
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1148
        win32utils.winver = None # Avoid the win32 detection code
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1149
        osutils._fs_enc = 'UTF-8'
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1150
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1151
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1152
    def test_force_walkdirs_utf8_fs_ascii(self):
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1153
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1154
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1155
        win32utils.winver = None # Avoid the win32 detection code
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1156
        osutils._fs_enc = 'US-ASCII'
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1157
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1158
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1159
    def test_force_walkdirs_utf8_fs_ANSI(self):
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1160
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1161
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1162
        win32utils.winver = None # Avoid the win32 detection code
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1163
        osutils._fs_enc = 'ANSI_X3.4-1968'
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1164
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1165
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1166
    def test_force_walkdirs_utf8_fs_latin1(self):
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1167
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1168
        win32utils.winver = None # Avoid the win32 detection code
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1169
        osutils._fs_enc = 'latin1'
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1170
        self.assertDirReaderIs(osutils.UnicodeDirReader)
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1171
1172
    def test_force_walkdirs_utf8_nt(self):
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1173
        # Disabled because the thunk of the whole walkdirs api is disabled.
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1174
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1175
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1176
        win32utils.winver = 'Windows NT'
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1177
        from bzrlib._walkdirs_win32 import Win32ReadDir
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1178
        self.assertDirReaderIs(Win32ReadDir)
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1179
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1180
    def test_force_walkdirs_utf8_98(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1181
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1182
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1183
        win32utils.winver = 'Windows 98'
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
1184
        self.assertDirReaderIs(osutils.UnicodeDirReader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1185
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1186
    def test_unicode_walkdirs(self):
1187
        """Walkdirs should always return unicode paths."""
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1188
        self.requireFeature(tests.UnicodeFilenameFeature)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1189
        name0 = u'0file-\xb6'
1190
        name1 = u'1dir-\u062c\u0648'
1191
        name2 = u'2file-\u0633'
1192
        tree = [
1193
            name0,
1194
            name1 + '/',
1195
            name1 + '/' + name0,
1196
            name1 + '/' + name1 + '/',
1197
            name2,
1198
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1199
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1200
        expected_dirblocks = [
1201
                ((u'', u'.'),
1202
                 [(name0, name0, 'file', './' + name0),
1203
                  (name1, name1, 'directory', './' + name1),
1204
                  (name2, name2, 'file', './' + name2),
1205
                 ]
1206
                ),
1207
                ((name1, './' + name1),
1208
                 [(name1 + '/' + name0, name0, 'file', './' + name1
1209
                                                        + '/' + name0),
1210
                  (name1 + '/' + name1, name1, 'directory', './' + name1
1211
                                                            + '/' + name1),
1212
                 ]
1213
                ),
1214
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
1215
                 [
1216
                 ]
1217
                ),
1218
            ]
1219
        result = list(osutils.walkdirs('.'))
1220
        self._filter_out_stat(result)
1221
        self.assertEqual(expected_dirblocks, result)
1222
        result = list(osutils.walkdirs(u'./'+name1, name1))
1223
        self._filter_out_stat(result)
1224
        self.assertEqual(expected_dirblocks[1:], result)
1225
1226
    def test_unicode__walkdirs_utf8(self):
1227
        """Walkdirs_utf8 should always return utf8 paths.
1228
1229
        The abspath portion might be in unicode or utf-8
1230
        """
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1231
        self.requireFeature(tests.UnicodeFilenameFeature)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1232
        name0 = u'0file-\xb6'
1233
        name1 = u'1dir-\u062c\u0648'
1234
        name2 = u'2file-\u0633'
1235
        tree = [
1236
            name0,
1237
            name1 + '/',
1238
            name1 + '/' + name0,
1239
            name1 + '/' + name1 + '/',
1240
            name2,
1241
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1242
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1243
        name0 = name0.encode('utf8')
1244
        name1 = name1.encode('utf8')
1245
        name2 = name2.encode('utf8')
1246
1247
        expected_dirblocks = [
1248
                (('', '.'),
1249
                 [(name0, name0, 'file', './' + name0),
1250
                  (name1, name1, 'directory', './' + name1),
1251
                  (name2, name2, 'file', './' + name2),
1252
                 ]
1253
                ),
1254
                ((name1, './' + name1),
1255
                 [(name1 + '/' + name0, name0, 'file', './' + name1
1256
                                                        + '/' + name0),
1257
                  (name1 + '/' + name1, name1, 'directory', './' + name1
1258
                                                            + '/' + name1),
1259
                 ]
1260
                ),
1261
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
1262
                 [
1263
                 ]
1264
                ),
1265
            ]
1266
        result = []
1267
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1268
        # all abspaths are Unicode, and encode them back into utf8.
1269
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1270
            self.assertIsInstance(dirdetail[0], str)
1271
            if isinstance(dirdetail[1], unicode):
2324.2.4 by Dmitry Vasiliev
Fixed test_unicode__walkdirs_utf8 test
1272
                dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1273
                dirblock = [list(info) for info in dirblock]
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1274
                for info in dirblock:
1275
                    self.assertIsInstance(info[4], unicode)
1276
                    info[4] = info[4].encode('utf8')
1277
            new_dirblock = []
1278
            for info in dirblock:
1279
                self.assertIsInstance(info[0], str)
1280
                self.assertIsInstance(info[1], str)
1281
                self.assertIsInstance(info[4], str)
1282
                # Remove the stat information
1283
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1284
            result.append((dirdetail, new_dirblock))
1285
        self.assertEqual(expected_dirblocks, result)
1286
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1287
    def test__walkdirs_utf8_with_unicode_fs(self):
1288
        """UnicodeDirReader should be a safe fallback everywhere
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1289
1290
        The abspath portion should be in unicode
1291
        """
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1292
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1293
        # Use the unicode reader. TODO: split into driver-and-driven unit
1294
        # tests.
1295
        self._save_platform_info()
1296
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1297
        name0u = u'0file-\xb6'
1298
        name1u = u'1dir-\u062c\u0648'
1299
        name2u = u'2file-\u0633'
1300
        tree = [
1301
            name0u,
1302
            name1u + '/',
1303
            name1u + '/' + name0u,
1304
            name1u + '/' + name1u + '/',
1305
            name2u,
1306
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1307
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1308
        name0 = name0u.encode('utf8')
1309
        name1 = name1u.encode('utf8')
1310
        name2 = name2u.encode('utf8')
1311
1312
        # All of the abspaths should be in unicode, all of the relative paths
1313
        # should be in utf8
1314
        expected_dirblocks = [
1315
                (('', '.'),
1316
                 [(name0, name0, 'file', './' + name0u),
1317
                  (name1, name1, 'directory', './' + name1u),
1318
                  (name2, name2, 'file', './' + name2u),
1319
                 ]
1320
                ),
1321
                ((name1, './' + name1u),
1322
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1323
                                                        + '/' + name0u),
1324
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1325
                                                            + '/' + name1u),
1326
                 ]
1327
                ),
1328
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1329
                 [
1330
                 ]
1331
                ),
1332
            ]
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1333
        result = list(osutils._walkdirs_utf8('.'))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1334
        self._filter_out_stat(result)
1335
        self.assertEqual(expected_dirblocks, result)
1336
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1337
    def test__walkdirs_utf8_win32readdir(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1338
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1339
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1340
        from bzrlib._walkdirs_win32 import Win32ReadDir
1341
        self._save_platform_info()
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1342
        osutils._selected_dir_reader = Win32ReadDir()
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1343
        name0u = u'0file-\xb6'
1344
        name1u = u'1dir-\u062c\u0648'
1345
        name2u = u'2file-\u0633'
1346
        tree = [
1347
            name0u,
1348
            name1u + '/',
1349
            name1u + '/' + name0u,
1350
            name1u + '/' + name1u + '/',
1351
            name2u,
1352
            ]
1353
        self.build_tree(tree)
1354
        name0 = name0u.encode('utf8')
1355
        name1 = name1u.encode('utf8')
1356
        name2 = name2u.encode('utf8')
1357
1358
        # All of the abspaths should be in unicode, all of the relative paths
1359
        # should be in utf8
1360
        expected_dirblocks = [
1361
                (('', '.'),
1362
                 [(name0, name0, 'file', './' + name0u),
1363
                  (name1, name1, 'directory', './' + name1u),
1364
                  (name2, name2, 'file', './' + name2u),
1365
                 ]
1366
                ),
1367
                ((name1, './' + name1u),
1368
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1369
                                                        + '/' + name0u),
1370
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1371
                                                            + '/' + name1u),
1372
                 ]
1373
                ),
1374
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1375
                 [
1376
                 ]
1377
                ),
1378
            ]
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1379
        result = list(osutils._walkdirs_utf8(u'.'))
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1380
        self._filter_out_stat(result)
1381
        self.assertEqual(expected_dirblocks, result)
1382
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1383
    def assertStatIsCorrect(self, path, win32stat):
1384
        os_stat = os.stat(path)
1385
        self.assertEqual(os_stat.st_size, win32stat.st_size)
3504.4.6 by John Arbash Meinel
Start exposing the times on the stat, this now seems to be a complete walkdirs implementation.
1386
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
1387
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
1388
        self.assertAlmostEqual(os_stat.st_atime, win32stat.st_atime, places=4)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1389
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
1390
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
1391
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
1392
1393
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1394
        """make sure our Stat values are valid"""
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1395
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1396
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1397
        from bzrlib._walkdirs_win32 import Win32ReadDir
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1398
        name0u = u'0file-\xb6'
1399
        name0 = name0u.encode('utf8')
1400
        self.build_tree([name0u])
1401
        # I hate to sleep() here, but I'm trying to make the ctime different
1402
        # from the mtime
1403
        time.sleep(2)
1404
        f = open(name0u, 'ab')
1405
        try:
1406
            f.write('just a small update')
1407
        finally:
1408
            f.close()
1409
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1410
        result = Win32ReadDir().read_dir('', u'.')
1411
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1412
        self.assertEqual((name0, name0, 'file'), entry[:3])
1413
        self.assertEqual(u'./' + name0u, entry[4])
1414
        self.assertStatIsCorrect(entry[4], entry[3])
3504.4.6 by John Arbash Meinel
Start exposing the times on the stat, this now seems to be a complete walkdirs implementation.
1415
        self.assertNotEqual(entry[3].st_mtime, entry[3].st_ctime)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1416
1417
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1418
        """make sure our Stat values are valid"""
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1419
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1420
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1421
        from bzrlib._walkdirs_win32 import Win32ReadDir
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1422
        name0u = u'0dir-\u062c\u0648'
1423
        name0 = name0u.encode('utf8')
1424
        self.build_tree([name0u + '/'])
1425
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1426
        result = Win32ReadDir().read_dir('', u'.')
1427
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1428
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1429
        self.assertEqual(u'./' + name0u, entry[4])
1430
        self.assertStatIsCorrect(entry[4], entry[3])
1431
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1432
    def assertPathCompare(self, path_less, path_greater):
1433
        """check that path_less and path_greater compare correctly."""
1434
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1435
            path_less, path_less))
1436
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1437
            path_greater, path_greater))
1438
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
1439
            path_less, path_greater))
1440
        self.assertEqual(1, osutils.compare_paths_prefix_order(
1441
            path_greater, path_less))
1442
1443
    def test_compare_paths_prefix_order(self):
1444
        # root before all else
1445
        self.assertPathCompare("/", "/a")
1446
        # alpha within a dir
1447
        self.assertPathCompare("/a", "/b")
1448
        self.assertPathCompare("/b", "/z")
1449
        # high dirs before lower.
1450
        self.assertPathCompare("/z", "/a/a")
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
1451
        # except if the deeper dir should be output first
1452
        self.assertPathCompare("/a/b/c", "/d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1453
        # lexical betwen dirs of the same height
1454
        self.assertPathCompare("/a/z", "/z/z")
1455
        self.assertPathCompare("/a/c/z", "/a/d/e")
1456
1457
        # this should also be consistent for no leading / paths
1458
        # root before all else
1459
        self.assertPathCompare("", "a")
1460
        # alpha within a dir
1461
        self.assertPathCompare("a", "b")
1462
        self.assertPathCompare("b", "z")
1463
        # high dirs before lower.
1464
        self.assertPathCompare("z", "a/a")
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
1465
        # except if the deeper dir should be output first
1466
        self.assertPathCompare("a/b/c", "d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1467
        # lexical betwen dirs of the same height
1468
        self.assertPathCompare("a/z", "z/z")
1469
        self.assertPathCompare("a/c/z", "a/d/e")
1470
1773.3.3 by Robert Collins
Add new tests John Meinel asked for.
1471
    def test_path_prefix_sorting(self):
1472
        """Doing a sort on path prefix should match our sample data."""
1473
        original_paths = [
1474
            'a',
1475
            'a/b',
1476
            'a/b/c',
1477
            'b',
1478
            'b/c',
1479
            'd',
1480
            'd/e',
1481
            'd/e/f',
1482
            'd/f',
1483
            'd/g',
1484
            'g',
1485
            ]
1486
1487
        dir_sorted_paths = [
1488
            'a',
1489
            'b',
1490
            'd',
1491
            'g',
1492
            'a/b',
1493
            'a/b/c',
1494
            'b/c',
1495
            'd/e',
1496
            'd/f',
1497
            'd/g',
1498
            'd/e/f',
1499
            ]
1500
1501
        self.assertEqual(
1502
            dir_sorted_paths,
1503
            sorted(original_paths, key=osutils.path_prefix_key))
1504
        # using the comparison routine shoudl work too:
1505
        self.assertEqual(
1506
            dir_sorted_paths,
1507
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
1508
1509
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1510
class TestCopyTree(tests.TestCaseInTempDir):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1511
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1512
    def test_copy_basic_tree(self):
1513
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1514
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1515
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1516
        self.assertEqual(['c'], os.listdir('target/b'))
1517
1518
    def test_copy_tree_target_exists(self):
1519
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
1520
                         'target/'])
1521
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1522
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1523
        self.assertEqual(['c'], os.listdir('target/b'))
1524
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1525
    def test_copy_tree_symlinks(self):
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1526
        self.requireFeature(tests.SymlinkFeature)
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1527
        self.build_tree(['source/'])
1528
        os.symlink('a/generic/path', 'source/lnk')
1529
        osutils.copy_tree('source', 'target')
1530
        self.assertEqual(['lnk'], os.listdir('target'))
1531
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
1532
1533
    def test_copy_tree_handlers(self):
1534
        processed_files = []
1535
        processed_links = []
1536
        def file_handler(from_path, to_path):
1537
            processed_files.append(('f', from_path, to_path))
1538
        def dir_handler(from_path, to_path):
1539
            processed_files.append(('d', from_path, to_path))
1540
        def link_handler(from_path, to_path):
1541
            processed_links.append((from_path, to_path))
1542
        handlers = {'file':file_handler,
1543
                    'directory':dir_handler,
1544
                    'symlink':link_handler,
1545
                   }
1546
1547
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1548
        if osutils.has_symlinks():
1549
            os.symlink('a/generic/path', 'source/lnk')
1550
        osutils.copy_tree('source', 'target', handlers=handlers)
1551
1552
        self.assertEqual([('d', 'source', 'target'),
1553
                          ('f', 'source/a', 'target/a'),
1554
                          ('d', 'source/b', 'target/b'),
1555
                          ('f', 'source/b/c', 'target/b/c'),
1556
                         ], processed_files)
1557
        self.failIfExists('target')
1558
        if osutils.has_symlinks():
1559
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1560
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1561
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1562
class TestSetUnsetEnv(tests.TestCase):
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1563
    """Test updating the environment"""
1564
1565
    def setUp(self):
1566
        super(TestSetUnsetEnv, self).setUp()
1567
1568
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1569
                         'Environment was not cleaned up properly.'
1570
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
1571
        def cleanup():
1572
            if 'BZR_TEST_ENV_VAR' in os.environ:
1573
                del os.environ['BZR_TEST_ENV_VAR']
1574
1575
        self.addCleanup(cleanup)
1576
1577
    def test_set(self):
1578
        """Test that we can set an env variable"""
1579
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1580
        self.assertEqual(None, old)
1581
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1582
1583
    def test_double_set(self):
1584
        """Test that we get the old value out"""
1585
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1586
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
1587
        self.assertEqual('foo', old)
1588
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1589
1590
    def test_unicode(self):
1591
        """Environment can only contain plain strings
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1592
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1593
        So Unicode strings must be encoded.
1594
        """
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1595
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
1596
        if uni_val is None:
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1597
            raise tests.TestSkipped(
1598
                'Cannot find a unicode character that works in encoding %s'
1599
                % (osutils.get_user_encoding(),))
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1600
1601
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1602
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1603
1604
    def test_unset(self):
1605
        """Test that passing None will remove the env var"""
1606
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1607
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1608
        self.assertEqual('foo', old)
1609
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1610
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1611
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
1612
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1613
class TestSizeShaFile(tests.TestCaseInTempDir):
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1614
1615
    def test_sha_empty(self):
1616
        self.build_tree_contents([('foo', '')])
1617
        expected_sha = osutils.sha_string('')
1618
        f = open('foo')
1619
        self.addCleanup(f.close)
1620
        size, sha = osutils.size_sha_file(f)
1621
        self.assertEqual(0, size)
1622
        self.assertEqual(expected_sha, sha)
1623
1624
    def test_sha_mixed_endings(self):
1625
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1626
        self.build_tree_contents([('foo', text)])
1627
        expected_sha = osutils.sha_string(text)
4789.25.1 by John Arbash Meinel
When computing the sha1sum for a file, make sure it is opened in binary mode.
1628
        f = open('foo', 'rb')
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1629
        self.addCleanup(f.close)
1630
        size, sha = osutils.size_sha_file(f)
1631
        self.assertEqual(38, size)
1632
        self.assertEqual(expected_sha, sha)
1633
1634
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1635
class TestShaFileByName(tests.TestCaseInTempDir):
2922.1.2 by John Arbash Meinel
Add tests for sha_file_by_name.
1636
1637
    def test_sha_empty(self):
1638
        self.build_tree_contents([('foo', '')])
1639
        expected_sha = osutils.sha_string('')
1640
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1641
1642
    def test_sha_mixed_endings(self):
1643
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1644
        self.build_tree_contents([('foo', text)])
1645
        expected_sha = osutils.sha_string(text)
1646
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
3089.3.9 by Ian Clatworthy
add test for resource loading
1647
1648
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1649
class TestResourceLoading(tests.TestCaseInTempDir):
3089.3.9 by Ian Clatworthy
add test for resource loading
1650
1651
    def test_resource_string(self):
1652
        # test resource in bzrlib
1653
        text = osutils.resource_string('bzrlib', 'debug.py')
3959.1.4 by Martin Pool
test_resource_string shouldn't depend on the precise source file contents
1654
        self.assertContainsRe(text, "debug_flags = set()")
3089.3.9 by Ian Clatworthy
add test for resource loading
1655
        # test resource under bzrlib
1656
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1657
        self.assertContainsRe(text, "class TextUIFactory")
1658
        # test unsupported package
1659
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1660
            'yyy.xx')
1661
        # test unknown resource
1662
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
4183.6.4 by Martin Pool
Separate out re_compile_checked
1663
1664
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1665
class TestReCompile(tests.TestCase):
4183.6.4 by Martin Pool
Separate out re_compile_checked
1666
1667
    def test_re_compile_checked(self):
1668
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1669
        self.assertTrue(r.match('aaaa'))
1670
        self.assertTrue(r.match('aAaA'))
1671
1672
    def test_re_compile_checked_error(self):
1673
        # like https://bugs.launchpad.net/bzr/+bug/251352
1674
        err = self.assertRaises(
1675
            errors.BzrCommandError,
1676
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1677
        self.assertEqual(
1678
            "Invalid regular expression in test case: '*': "
1679
            "nothing to repeat",
1680
            str(err))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1681
1682
1683
class TestDirReader(tests.TestCaseInTempDir):
1684
1685
    # Set by load_tests
1686
    _dir_reader_class = None
1687
    _native_to_unicode = None
1688
1689
    def setUp(self):
1690
        tests.TestCaseInTempDir.setUp(self)
1691
1692
        # Save platform specific info and reset it
1693
        cur_dir_reader = osutils._selected_dir_reader
1694
1695
        def restore():
1696
            osutils._selected_dir_reader = cur_dir_reader
1697
        self.addCleanup(restore)
1698
1699
        osutils._selected_dir_reader = self._dir_reader_class()
1700
1701
    def _get_ascii_tree(self):
1702
        tree = [
1703
            '0file',
1704
            '1dir/',
1705
            '1dir/0file',
1706
            '1dir/1dir/',
1707
            '2file'
1708
            ]
1709
        expected_dirblocks = [
1710
                (('', '.'),
1711
                 [('0file', '0file', 'file'),
1712
                  ('1dir', '1dir', 'directory'),
1713
                  ('2file', '2file', 'file'),
1714
                 ]
1715
                ),
1716
                (('1dir', './1dir'),
1717
                 [('1dir/0file', '0file', 'file'),
1718
                  ('1dir/1dir', '1dir', 'directory'),
1719
                 ]
1720
                ),
1721
                (('1dir/1dir', './1dir/1dir'),
1722
                 [
1723
                 ]
1724
                ),
1725
            ]
1726
        return tree, expected_dirblocks
1727
1728
    def test_walk_cur_dir(self):
1729
        tree, expected_dirblocks = self._get_ascii_tree()
1730
        self.build_tree(tree)
1731
        result = list(osutils._walkdirs_utf8('.'))
1732
        # Filter out stat and abspath
1733
        self.assertEqual(expected_dirblocks,
1734
                         [(dirinfo, [line[0:3] for line in block])
1735
                          for dirinfo, block in result])
1736
1737
    def test_walk_sub_dir(self):
1738
        tree, expected_dirblocks = self._get_ascii_tree()
1739
        self.build_tree(tree)
1740
        # you can search a subdir only, with a supplied prefix.
1741
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1742
        # Filter out stat and abspath
1743
        self.assertEqual(expected_dirblocks[1:],
1744
                         [(dirinfo, [line[0:3] for line in block])
1745
                          for dirinfo, block in result])
1746
1747
    def _get_unicode_tree(self):
1748
        name0u = u'0file-\xb6'
1749
        name1u = u'1dir-\u062c\u0648'
1750
        name2u = u'2file-\u0633'
1751
        tree = [
1752
            name0u,
1753
            name1u + '/',
1754
            name1u + '/' + name0u,
1755
            name1u + '/' + name1u + '/',
1756
            name2u,
1757
            ]
1758
        name0 = name0u.encode('UTF-8')
1759
        name1 = name1u.encode('UTF-8')
1760
        name2 = name2u.encode('UTF-8')
1761
        expected_dirblocks = [
1762
                (('', '.'),
1763
                 [(name0, name0, 'file', './' + name0u),
1764
                  (name1, name1, 'directory', './' + name1u),
1765
                  (name2, name2, 'file', './' + name2u),
1766
                 ]
1767
                ),
1768
                ((name1, './' + name1u),
1769
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1770
                                                        + '/' + name0u),
1771
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1772
                                                            + '/' + name1u),
1773
                 ]
1774
                ),
1775
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1776
                 [
1777
                 ]
1778
                ),
1779
            ]
1780
        return tree, expected_dirblocks
1781
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1782
    def _filter_out(self, raw_dirblocks):
1783
        """Filter out a walkdirs_utf8 result.
1784
1785
        stat field is removed, all native paths are converted to unicode
1786
        """
1787
        filtered_dirblocks = []
1788
        for dirinfo, block in raw_dirblocks:
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1789
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1790
            details = []
1791
            for line in block:
4789.25.5 by John Arbash Meinel
Remove a pdb.set_trace() call.
1792
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1793
            filtered_dirblocks.append((dirinfo, details))
1794
        return filtered_dirblocks
1795
1796
    def test_walk_unicode_tree(self):
4241.14.25 by Vincent Ladeuil
Fix PQM failures.
1797
        self.requireFeature(tests.UnicodeFilenameFeature)
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1798
        tree, expected_dirblocks = self._get_unicode_tree()
1799
        self.build_tree(tree)
1800
        result = list(osutils._walkdirs_utf8('.'))
1801
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1802
1803
    def test_symlink(self):
1804
        self.requireFeature(tests.SymlinkFeature)
4241.14.25 by Vincent Ladeuil
Fix PQM failures.
1805
        self.requireFeature(tests.UnicodeFilenameFeature)
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1806
        target = u'target\N{Euro Sign}'
1807
        link_name = u'l\N{Euro Sign}nk'
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1808
        os.symlink(target, link_name)
1809
        target_utf8 = target.encode('UTF-8')
1810
        link_name_utf8 = link_name.encode('UTF-8')
1811
        expected_dirblocks = [
1812
                (('', '.'),
1813
                 [(link_name_utf8, link_name_utf8,
1814
                   'symlink', './' + link_name),],
1815
                 )]
1816
        result = list(osutils._walkdirs_utf8('.'))
1817
        self.assertEqual(expected_dirblocks, self._filter_out(result))
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1818
1819
1820
class TestReadLink(tests.TestCaseInTempDir):
1821
    """Exposes os.readlink() problems and the osutils solution.
1822
1823
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1824
    unicode string will be returned if a unicode string is passed.
1825
4241.14.25 by Vincent Ladeuil
Fix PQM failures.
1826
    But prior python versions failed to properly encode the passed unicode
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1827
    string.
1828
    """
4331.1.3 by Vincent Ladeuil
Revert previous patch, PQM now presents a unicode friendly file system encoding.
1829
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1830
1831
    def setUp(self):
1832
        super(tests.TestCaseInTempDir, self).setUp()
1833
        self.link = u'l\N{Euro Sign}ink'
1834
        self.target = u'targe\N{Euro Sign}t'
1835
        os.symlink(self.target, self.link)
1836
1837
    def test_os_readlink_link_encoding(self):
1838
        if sys.version_info < (2, 6):
1839
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
1840
        else:
1841
            self.assertEquals(self.target,  os.readlink(self.link))
1842
1843
    def test_os_readlink_link_decoding(self):
1844
        self.assertEquals(self.target.encode(osutils._fs_enc),
1845
                          os.readlink(self.link.encode(osutils._fs_enc)))
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1846
1847
1848
class TestConcurrency(tests.TestCase):
1849
1850
    def test_local_concurrency(self):
1851
        concurrency = osutils.local_concurrency()
1852
        self.assertIsInstance(concurrency, int)
4574.3.3 by Martin Pool
Add test for failure to load extensions
1853
1854
1855
class TestFailedToLoadExtension(tests.TestCase):
1856
1857
    def _try_loading(self):
1858
        try:
1859
            import bzrlib._fictional_extension_py
1860
        except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1861
            osutils.failed_to_load_extension(e)
4574.3.3 by Martin Pool
Add test for failure to load extensions
1862
            return True
1863
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1864
    def setUp(self):
1865
        super(TestFailedToLoadExtension, self).setUp()
1866
        self.saved_failures = osutils._extension_load_failures[:]
1867
        del osutils._extension_load_failures[:]
1868
        self.addCleanup(self.restore_failures)
1869
1870
    def restore_failures(self):
1871
        osutils._extension_load_failures = self.saved_failures
1872
4574.3.3 by Martin Pool
Add test for failure to load extensions
1873
    def test_failure_to_load(self):
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1874
        self._try_loading()
1875
        self.assertLength(1, osutils._extension_load_failures)
1876
        self.assertEquals(osutils._extension_load_failures[0],
1877
            "No module named _fictional_extension_py")
1878
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1879
    def test_report_extension_load_failures_no_warning(self):
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1880
        self.assertTrue(self._try_loading())
1881
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1882
        # it used to give a Python warning; it no longer does
1883
        self.assertLength(0, warnings)
1884
1885
    def test_report_extension_load_failures_message(self):
1886
        log = StringIO()
1887
        trace.push_log_file(log)
1888
        self.assertTrue(self._try_loading())
1889
        osutils.report_extension_load_failures()
1890
        self.assertContainsRe(
1891
            log.getvalue(),
1892
            r"bzr: warning: some compiled extensions could not be loaded; "
1893
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1894
            )