~bzr-pqm/bzr/bzr.dev

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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
22
import socket
23
import stat
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
24
import sys
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
25
import time
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
26
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
27
from bzrlib import (
28
    errors,
29
    osutils,
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
30
    tests,
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
31
    win32utils,
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
32
    )
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
33
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
34
from bzrlib.osutils import (
35
        is_inside_any,
36
        is_inside_or_parent_of_any,
37
        pathjoin,
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
38
        pumpfile,
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
39
        pump_string_file,
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
40
        canonical_relpath,
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
41
        )
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.
42
from bzrlib.tests import (
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
43
        Feature,
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
44
        probe_unicode_in_user_encoding,
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.
45
        StringIOWrapper,
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
46
        SymlinkFeature,
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
47
        CaseInsCasePresFilenameFeature,
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
48
        TestCase,
49
        TestCaseInTempDir,
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.
50
        TestSkipped,
51
        )
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
52
from bzrlib.tests.file_utils import (
53
    FakeReadFile,
54
    )
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
55
from bzrlib.tests.test__walkdirs_win32 import Win32ReadDirFeature
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
56
57
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)
58
class _UTF8DirReaderFeature(Feature):
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
59
60
    def _probe(self):
61
        try:
62
            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)
63
            self.reader = _readdir_pyx.UTF8DirReader
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
64
            return True
65
        except ImportError:
66
            return False
67
68
    def feature_name(self):
1739.2.13 by Robert Collins
Fix typo in ReadDirFeature.
69
        return 'bzrlib._readdir_pyx'
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
70
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)
71
UTF8DirReaderFeature = _UTF8DirReaderFeature()
1739.2.12 by Robert Collins
Add ReadDirFeature as per John's review.
72
73
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
74
class TestOSUtils(TestCaseInTempDir):
75
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
76
    def test_contains_whitespace(self):
77
        self.failUnless(osutils.contains_whitespace(u' '))
78
        self.failUnless(osutils.contains_whitespace(u'hello there'))
79
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
80
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
81
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
82
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
83
84
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
85
        # is whitespace, but we do not.
86
        self.failIf(osutils.contains_whitespace(u''))
87
        self.failIf(osutils.contains_whitespace(u'hellothere'))
88
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
89
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
90
    def test_fancy_rename(self):
91
        # This should work everywhere
92
        def rename(a, b):
93
            osutils.fancy_rename(a, b,
94
                    rename_func=os.rename,
95
                    unlink_func=os.unlink)
96
97
        open('a', 'wb').write('something in a\n')
98
        rename('a', 'b')
99
        self.failIfExists('a')
100
        self.failUnlessExists('b')
101
        self.check_file_contents('b', 'something in a\n')
102
103
        open('a', 'wb').write('new something in a\n')
104
        rename('b', 'a')
105
106
        self.check_file_contents('a', 'something in a\n')
107
108
    def test_rename(self):
109
        # Rename should be semi-atomic on all platforms
110
        open('a', 'wb').write('something in a\n')
111
        osutils.rename('a', 'b')
112
        self.failIfExists('a')
113
        self.failUnlessExists('b')
114
        self.check_file_contents('b', 'something in a\n')
115
116
        open('a', 'wb').write('new something in a\n')
117
        osutils.rename('b', 'a')
118
119
        self.check_file_contents('a', 'something in a\n')
120
121
    # TODO: test fancy_rename using a MemoryTransport
122
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
123
    def test_rename_change_case(self):
124
        # 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)
125
        self.build_tree(['a', 'b/'])
126
        osutils.rename('a', 'A')
127
        osutils.rename('b', 'B')
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
128
        # we can't use failUnlessExists on case-insensitive filesystem
129
        # so try to check shape of the tree
2978.8.1 by Alexander Belchenko
Rename on Windows is able to change filename case. (#77740)
130
        shape = sorted(os.listdir('.'))
131
        self.assertEquals(['A', 'B'], shape)
132
1553.5.5 by Martin Pool
New utility routine rand_chars
133
    def test_01_rand_chars_empty(self):
134
        result = osutils.rand_chars(0)
135
        self.assertEqual(result, '')
136
137
    def test_02_rand_chars_100(self):
138
        result = osutils.rand_chars(100)
139
        self.assertEqual(len(result), 100)
140
        self.assertEqual(type(result), str)
141
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
142
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
143
    def test_is_inside(self):
144
        is_inside = osutils.is_inside
145
        self.assertTrue(is_inside('src', 'src/foo.c'))
146
        self.assertFalse(is_inside('src', 'srccontrol'))
147
        self.assertTrue(is_inside('src', 'src/a/a/a/foo.c'))
148
        self.assertTrue(is_inside('foo.c', 'foo.c'))
149
        self.assertFalse(is_inside('foo.c', ''))
150
        self.assertTrue(is_inside('', 'foo.c'))
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
151
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
152
    def test_is_inside_any(self):
153
        SRC_FOO_C = pathjoin('src', 'foo.c')
154
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
155
                         (['src'], SRC_FOO_C),
156
                         (['src'], 'src'),
157
                         ]:
158
            self.assert_(is_inside_any(dirs, fn))
159
        for dirs, fn in [(['src'], 'srccontrol'),
160
                         (['src'], 'srccontrol/foo')]:
161
            self.assertFalse(is_inside_any(dirs, fn))
162
163
    def test_is_inside_or_parent_of_any(self):
164
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
165
                         (['src'], 'src/foo.c'),
166
                         (['src/bar.c'], 'src'),
167
                         (['src/bar.c', 'bla/foo.c'], 'src'),
168
                         (['src'], 'src'),
169
                         ]:
170
            self.assert_(is_inside_or_parent_of_any(dirs, fn))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
171
2729.2.4 by Martin Pool
move some osutils-related tests from test_inv to test_osutils
172
        for dirs, fn in [(['src'], 'srccontrol'),
173
                         (['srccontrol/foo.c'], 'src'),
174
                         (['src'], 'srccontrol/foo')]:
175
            self.assertFalse(is_inside_or_parent_of_any(dirs, fn))
176
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
177
    def test_rmtree(self):
178
        # Check to remove tree with read-only files/dirs
179
        os.mkdir('dir')
180
        f = file('dir/file', 'w')
181
        f.write('spam')
182
        f.close()
183
        # would like to also try making the directory readonly, but at the
184
        # moment python shutil.rmtree doesn't handle that properly - it would
185
        # need to chmod the directory before removing things inside it - deferred
186
        # for now -- mbp 20060505
187
        # osutils.make_readonly('dir')
188
        osutils.make_readonly('dir/file')
189
190
        osutils.rmtree('dir')
191
192
        self.failIfExists('dir/file')
193
        self.failIfExists('dir')
194
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
195
    def test_file_kind(self):
196
        self.build_tree(['file', 'dir/'])
197
        self.assertEquals('file', osutils.file_kind('file'))
198
        self.assertEquals('directory', osutils.file_kind('dir/'))
199
        if osutils.has_symlinks():
200
            os.symlink('symlink', 'symlink')
201
            self.assertEquals('symlink', osutils.file_kind('symlink'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
202
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
203
        # TODO: jam 20060529 Test a block device
204
        try:
205
            os.lstat('/dev/null')
206
        except OSError, e:
207
            if e.errno not in (errno.ENOENT,):
208
                raise
209
        else:
210
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
211
212
        mkfifo = getattr(os, 'mkfifo', None)
213
        if mkfifo:
214
            mkfifo('fifo')
215
            try:
216
                self.assertEquals('fifo', osutils.file_kind('fifo'))
217
            finally:
218
                os.remove('fifo')
219
220
        AF_UNIX = getattr(socket, 'AF_UNIX', None)
221
        if AF_UNIX:
222
            s = socket.socket(AF_UNIX)
223
            s.bind('socket')
224
            try:
225
                self.assertEquals('socket', osutils.file_kind('socket'))
226
            finally:
227
                os.remove('socket')
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
228
1551.10.27 by Aaron Bentley
Add a kind marker for subtrees
229
    def test_kind_marker(self):
230
        self.assertEqual(osutils.kind_marker('file'), '')
231
        self.assertEqual(osutils.kind_marker('directory'), '/')
232
        self.assertEqual(osutils.kind_marker('symlink'), '@')
1551.10.28 by Aaron Bentley
change kind marker to '+'
233
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
1551.10.27 by Aaron Bentley
Add a kind marker for subtrees
234
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
235
    def test_get_umask(self):
236
        if sys.platform == 'win32':
237
            # umask always returns '0', no way to set it
238
            self.assertEqual(0, osutils.get_umask())
239
            return
240
241
        orig_umask = osutils.get_umask()
242
        try:
243
            os.umask(0222)
244
            self.assertEqual(0222, osutils.get_umask())
245
            os.umask(0022)
246
            self.assertEqual(0022, osutils.get_umask())
247
            os.umask(0002)
248
            self.assertEqual(0002, osutils.get_umask())
249
            os.umask(0027)
250
            self.assertEqual(0027, osutils.get_umask())
251
        finally:
252
            os.umask(orig_umask)
253
1957.1.15 by John Arbash Meinel
Review feedback from Robert
254
    def assertFormatedDelta(self, expected, seconds):
255
        """Assert osutils.format_delta formats as expected"""
256
        actual = osutils.format_delta(seconds)
257
        self.assertEqual(expected, actual)
258
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
259
    def test_format_delta(self):
1957.1.15 by John Arbash Meinel
Review feedback from Robert
260
        self.assertFormatedDelta('0 seconds ago', 0)
261
        self.assertFormatedDelta('1 second ago', 1)
262
        self.assertFormatedDelta('10 seconds ago', 10)
263
        self.assertFormatedDelta('59 seconds ago', 59)
264
        self.assertFormatedDelta('89 seconds ago', 89)
265
        self.assertFormatedDelta('1 minute, 30 seconds ago', 90)
266
        self.assertFormatedDelta('3 minutes, 0 seconds ago', 180)
267
        self.assertFormatedDelta('3 minutes, 1 second ago', 181)
268
        self.assertFormatedDelta('10 minutes, 15 seconds ago', 615)
269
        self.assertFormatedDelta('30 minutes, 59 seconds ago', 1859)
270
        self.assertFormatedDelta('31 minutes, 0 seconds ago', 1860)
271
        self.assertFormatedDelta('60 minutes, 0 seconds ago', 3600)
272
        self.assertFormatedDelta('89 minutes, 59 seconds ago', 5399)
273
        self.assertFormatedDelta('1 hour, 30 minutes ago', 5400)
274
        self.assertFormatedDelta('2 hours, 30 minutes ago', 9017)
275
        self.assertFormatedDelta('10 hours, 0 minutes ago', 36000)
276
        self.assertFormatedDelta('24 hours, 0 minutes ago', 86400)
277
        self.assertFormatedDelta('35 hours, 59 minutes ago', 129599)
278
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129600)
279
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129601)
280
        self.assertFormatedDelta('36 hours, 1 minute ago', 129660)
281
        self.assertFormatedDelta('36 hours, 1 minute ago', 129661)
282
        self.assertFormatedDelta('84 hours, 10 minutes ago', 303002)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
283
284
        # We handle when time steps the wrong direction because computers
285
        # don't have synchronized clocks.
1957.1.15 by John Arbash Meinel
Review feedback from Robert
286
        self.assertFormatedDelta('84 hours, 10 minutes in the future', -303002)
287
        self.assertFormatedDelta('1 second in the future', -1)
288
        self.assertFormatedDelta('2 seconds in the future', -2)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
289
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
290
    def test_format_date(self):
291
        self.assertRaises(errors.UnsupportedTimezoneFormat,
292
            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.
293
        self.assertIsInstance(osutils.format_date(0), str)
294
        self.assertIsInstance(osutils.format_local_date(0), unicode)
295
        # Testing for the actual value of the local weekday without
3526.5.2 by Martin von Gagern
Check output type of format_date
296
        # duplicating the code from format_date is difficult.
297
        # Instead blackbox.test_locale should check for localized
298
        # dates once they do occur in output strings.
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
299
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
300
    def test_dereference_path(self):
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
301
        self.requireFeature(SymlinkFeature)
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
302
        cwd = osutils.realpath('.')
303
        os.mkdir('bar')
304
        bar_path = osutils.pathjoin(cwd, 'bar')
305
        # Using './' to avoid bug #1213894 (first path component not
306
        # dereferenced) in Python 2.4.1 and earlier
307
        self.assertEqual(bar_path, osutils.realpath('./bar'))
308
        os.symlink('bar', 'foo')
309
        self.assertEqual(bar_path, osutils.realpath('./foo'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
310
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
311
        # Does not dereference terminal symlinks
312
        foo_path = osutils.pathjoin(cwd, 'foo')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
313
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
314
315
        # Dereferences parent symlinks
316
        os.mkdir('bar/baz')
317
        baz_path = osutils.pathjoin(bar_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
318
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
319
320
        # Dereferences parent symlinks that are the first path element
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
321
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
322
323
        # Dereferences parent symlinks in absolute paths
324
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
325
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
326
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
327
    def test_changing_access(self):
328
        f = file('file', 'w')
329
        f.write('monkey')
330
        f.close()
331
332
        # Make a file readonly
333
        osutils.make_readonly('file')
2949.6.2 by Alexander Belchenko
more changes osutils.lstat -> os.lstat
334
        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
335
        self.assertEqual(mode, mode & 0777555)
336
337
        # Make a file writable
338
        osutils.make_writable('file')
2949.6.2 by Alexander Belchenko
more changes osutils.lstat -> os.lstat
339
        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
340
        self.assertEqual(mode, mode | 0200)
341
342
        if osutils.has_symlinks():
343
            # should not error when handed a symlink
344
            os.symlink('nonexistent', 'dangling')
345
            osutils.make_readonly('dangling')
346
            osutils.make_writable('dangling')
347
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
348
    def test_kind_marker(self):
349
        self.assertEqual("", osutils.kind_marker("file"))
350
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
351
        self.assertEqual("@", osutils.kind_marker("symlink"))
352
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
353
3287.18.26 by Matt McClure
Addresses concerns raised in
354
    def test_host_os_dereferences_symlinks(self):
355
        osutils.host_os_dereferences_symlinks()
356
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
357
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
358
class TestCanonicalRelPath(TestCaseInTempDir):
359
360
    _test_needs_features = [CaseInsCasePresFilenameFeature]
361
362
    def test_canonical_relpath_simple(self):
363
        f = file('MixedCaseName', 'w')
364
        f.close()
365
        self.failUnlessEqual(
366
            canonical_relpath(self.test_base_dir, 'mixedcasename'),
367
            'work/MixedCaseName')
368
369
    def test_canonical_relpath_missing_tail(self):
370
        os.mkdir('MixedCaseParent')
371
        self.failUnlessEqual(
372
            canonical_relpath(self.test_base_dir, 'mixedcaseparent/nochild'),
373
            'work/MixedCaseParent/nochild')
374
375
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
376
class TestPumpFile(TestCase):
377
    """Test pumpfile method."""
378
    def setUp(self):
4153.1.2 by Andrew Bennetts
Add missing TestCase.setUp upcalls.
379
        TestCase.setUp(self)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
380
        # create a test datablock
381
        self.block_size = 512
382
        pattern = '0123456789ABCDEF'
383
        self.test_data = pattern * (3 * self.block_size / len(pattern))
384
        self.test_data_len = len(self.test_data)
385
386
    def test_bracket_block_size(self):
387
        """Read data in blocks with the requested read size bracketing the
388
        block size."""
389
        # make sure test data is larger than max read size
390
        self.assertTrue(self.test_data_len > self.block_size)
391
392
        from_file = FakeReadFile(self.test_data)
393
        to_file = StringIO()
394
395
        # read (max / 2) bytes and verify read size wasn't affected
396
        num_bytes_to_read = self.block_size / 2
397
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
398
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
399
        self.assertEqual(from_file.get_read_count(), 1)
400
401
        # read (max) bytes and verify read size wasn't affected
402
        num_bytes_to_read = self.block_size
403
        from_file.reset_read_count()
404
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
405
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
406
        self.assertEqual(from_file.get_read_count(), 1)
407
408
        # read (max + 1) bytes and verify read size was limited
409
        num_bytes_to_read = self.block_size + 1
410
        from_file.reset_read_count()
411
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
412
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
413
        self.assertEqual(from_file.get_read_count(), 2)
414
415
        # finish reading the rest of the data
416
        num_bytes_to_read = self.test_data_len - to_file.tell()
417
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
418
419
        # report error if the data wasn't equal (we only report the size due
420
        # to the length of the data)
421
        response_data = to_file.getvalue()
422
        if response_data != self.test_data:
423
            message = "Data not equal.  Expected %d bytes, received %d."
424
            self.fail(message % (len(response_data), self.test_data_len))
425
426
    def test_specified_size(self):
427
        """Request a transfer larger than the maximum block size and verify
428
        that the maximum read doesn't exceed the block_size."""
429
        # make sure test data is larger than max read size
430
        self.assertTrue(self.test_data_len > self.block_size)
431
432
        # retrieve data in blocks
433
        from_file = FakeReadFile(self.test_data)
434
        to_file = StringIO()
435
        pumpfile(from_file, to_file, self.test_data_len, self.block_size)
436
437
        # verify read size was equal to the maximum read size
438
        self.assertTrue(from_file.get_max_read_size() > 0)
439
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
440
        self.assertEqual(from_file.get_read_count(), 3)
441
442
        # report error if the data wasn't equal (we only report the size due
443
        # to the length of the data)
444
        response_data = to_file.getvalue()
445
        if response_data != self.test_data:
446
            message = "Data not equal.  Expected %d bytes, received %d."
447
            self.fail(message % (len(response_data), self.test_data_len))
448
449
    def test_to_eof(self):
450
        """Read to end-of-file and verify that the reads are not larger than
451
        the maximum read size."""
452
        # make sure test data is larger than max read size
453
        self.assertTrue(self.test_data_len > self.block_size)
454
455
        # retrieve data to EOF
456
        from_file = FakeReadFile(self.test_data)
457
        to_file = StringIO()
458
        pumpfile(from_file, to_file, -1, self.block_size)
459
460
        # verify read size was equal to the maximum read size
461
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
462
        self.assertEqual(from_file.get_read_count(), 4)
463
464
        # report error if the data wasn't equal (we only report the size due
465
        # to the length of the data)
466
        response_data = to_file.getvalue()
467
        if response_data != self.test_data:
468
            message = "Data not equal.  Expected %d bytes, received %d."
469
            self.fail(message % (len(response_data), self.test_data_len))
470
471
    def test_defaults(self):
472
        """Verifies that the default arguments will read to EOF -- this
473
        test verifies that any existing usages of pumpfile will not be broken
474
        with this new version."""
475
        # retrieve data using default (old) pumpfile method
476
        from_file = FakeReadFile(self.test_data)
477
        to_file = StringIO()
478
        pumpfile(from_file, to_file)
479
480
        # report error if the data wasn't equal (we only report the size due
481
        # to the length of the data)
482
        response_data = to_file.getvalue()
483
        if response_data != self.test_data:
484
            message = "Data not equal.  Expected %d bytes, received %d."
485
            self.fail(message % (len(response_data), self.test_data_len))
486
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
487
    def test_report_activity(self):
488
        activity = []
489
        def log_activity(length, direction):
490
            activity.append((length, direction))
491
        from_file = StringIO(self.test_data)
492
        to_file = StringIO()
493
        pumpfile(from_file, to_file, buff_size=500,
494
                 report_activity=log_activity, direction='read')
495
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
496
                          (36, 'read')], activity)
497
498
        from_file = StringIO(self.test_data)
499
        to_file = StringIO()
500
        del activity[:]
501
        pumpfile(from_file, to_file, buff_size=500,
502
                 report_activity=log_activity, direction='write')
503
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
504
                          (36, 'write')], activity)
505
506
        # And with a limited amount of data
507
        from_file = StringIO(self.test_data)
508
        to_file = StringIO()
509
        del activity[:]
510
        pumpfile(from_file, to_file, buff_size=500, read_length=1028,
511
                 report_activity=log_activity, direction='read')
512
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
513
514
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
515
516
class TestPumpStringFile(TestCase):
517
518
    def test_empty(self):
519
        output = StringIO()
520
        pump_string_file("", output)
521
        self.assertEqual("", output.getvalue())
522
523
    def test_more_than_segment_size(self):
524
        output = StringIO()
525
        pump_string_file("123456789", output, 2)
526
        self.assertEqual("123456789", output.getvalue())
527
528
    def test_segment_size(self):
529
        output = StringIO()
530
        pump_string_file("12", output, 2)
531
        self.assertEqual("12", output.getvalue())
532
533
    def test_segment_size_multiple(self):
534
        output = StringIO()
535
        pump_string_file("1234", output, 2)
536
        self.assertEqual("1234", output.getvalue())
537
538
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
539
class TestSafeUnicode(TestCase):
540
541
    def test_from_ascii_string(self):
542
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
543
1534.3.2 by Robert Collins
An extra test for John.
544
    def test_from_unicode_string_ascii_contents(self):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
545
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
546
1534.3.2 by Robert Collins
An extra test for John.
547
    def test_from_unicode_string_unicode_contents(self):
548
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
549
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
550
    def test_from_utf8_string(self):
551
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
552
553
    def test_bad_utf8_string(self):
1185.65.29 by Robert Collins
Implement final review suggestions.
554
        self.assertRaises(BzrBadParameterNotUnicode,
555
                          osutils.safe_unicode,
556
                          '\xbb\xbb')
1666.1.6 by Robert Collins
Make knit the default format.
557
558
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
559
class TestSafeUtf8(TestCase):
560
561
    def test_from_ascii_string(self):
562
        f = 'foobar'
563
        self.assertEqual('foobar', osutils.safe_utf8(f))
564
565
    def test_from_unicode_string_ascii_contents(self):
566
        self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
567
568
    def test_from_unicode_string_unicode_contents(self):
569
        self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
570
571
    def test_from_utf8_string(self):
572
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
573
574
    def test_bad_utf8_string(self):
575
        self.assertRaises(BzrBadParameterNotUnicode,
576
                          osutils.safe_utf8, '\xbb\xbb')
577
578
579
class TestSafeRevisionId(TestCase):
580
581
    def test_from_ascii_string(self):
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
582
        # 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.
583
        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.
584
585
    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.
586
        self.assertEqual('bargam',
587
                         osutils.safe_revision_id(u'bargam', warn=False))
588
589
    def test_from_unicode_deprecated(self):
590
        self.assertEqual('bargam',
591
            self.callDeprecated([osutils._revision_id_warning],
592
                                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.
593
594
    def test_from_unicode_string_unicode_contents(self):
595
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
596
                         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.
597
598
    def test_from_utf8_string(self):
599
        self.assertEqual('foo\xc2\xae',
600
                         osutils.safe_revision_id('foo\xc2\xae'))
601
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
602
    def test_none(self):
603
        """Currently, None is a valid revision_id"""
604
        self.assertEqual(None, osutils.safe_revision_id(None))
605
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
606
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
607
class TestSafeFileId(TestCase):
608
609
    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.
610
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
611
612
    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.
613
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
614
615
    def test_from_unicode_deprecated(self):
616
        self.assertEqual('bargam',
617
            self.callDeprecated([osutils._file_id_warning],
618
                                osutils.safe_file_id, u'bargam'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
619
620
    def test_from_unicode_string_unicode_contents(self):
621
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
622
                         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.
623
624
    def test_from_utf8_string(self):
625
        self.assertEqual('foo\xc2\xae',
626
                         osutils.safe_file_id('foo\xc2\xae'))
627
628
    def test_none(self):
629
        """Currently, None is a valid revision_id"""
630
        self.assertEqual(None, osutils.safe_file_id(None))
631
632
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
633
class TestWin32Funcs(TestCase):
634
    """Test that the _win32 versions of os utilities return appropriate paths."""
635
636
    def test_abspath(self):
637
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
638
        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
639
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
640
        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.
641
642
    def test_realpath(self):
643
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
644
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
645
646
    def test_pathjoin(self):
647
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
648
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
649
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
650
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
651
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
652
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
653
654
    def test_normpath(self):
655
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
656
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
657
658
    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
659
        cwd = osutils._win32_getcwd()
660
        os_cwd = os.getcwdu()
661
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
662
        # win32 is inconsistent whether it returns lower or upper case
663
        # and even if it was consistent the user might type the other
664
        # so we force it to uppercase
665
        # running python.exe under cmd.exe return capital C:\\
666
        # running win32 python inside a cygwin shell returns lowercase
667
        self.assertEqual(os_cwd[0].upper(), cwd[0])
668
669
    def test_fixdrive(self):
670
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
671
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
672
        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.
673
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
674
    def test_win98_abspath(self):
675
        # absolute path
676
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
677
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
678
        # UNC path
679
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
680
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
681
        # relative path
682
        cwd = osutils.getcwd().rstrip('/')
683
        drive = osutils._nt_splitdrive(cwd)[0]
684
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
685
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
686
        # unicode path
687
        u = u'\u1234'
688
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
689
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
690
691
class TestWin32FuncsDirs(TestCaseInTempDir):
692
    """Test win32 functions that create files."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
693
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
694
    def test_getcwd(self):
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
695
        if win32utils.winver == 'Windows 98':
696
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
697
        # Make sure getcwd can handle unicode filenames
698
        try:
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
699
            os.mkdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
700
        except UnicodeError:
701
            raise TestSkipped("Unable to create Unicode filename")
702
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
703
        os.chdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
704
        # TODO: jam 20060427 This will probably fail on Mac OSX because
705
        #       it will change the normalization of B\xe5gfors
706
        #       Consider using a different unicode character, or make
707
        #       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.
708
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
709
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
710
    def test_minimum_path_selection(self):
711
        self.assertEqual(set(),
712
            osutils.minimum_path_selection([]))
713
        self.assertEqual(set(['a', 'b']),
714
            osutils.minimum_path_selection(['a', 'b']))
715
        self.assertEqual(set(['a/', 'b']),
716
            osutils.minimum_path_selection(['a/', 'b']))
717
        self.assertEqual(set(['a/', 'b']),
718
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
719
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
720
    def test_mkdtemp(self):
721
        tmpdir = osutils._win32_mkdtemp(dir='.')
722
        self.assertFalse('\\' in tmpdir)
723
724
    def test_rename(self):
725
        a = open('a', 'wb')
726
        a.write('foo\n')
727
        a.close()
728
        b = open('b', 'wb')
729
        b.write('baz\n')
730
        b.close()
731
732
        osutils._win32_rename('b', 'a')
733
        self.failUnlessExists('a')
734
        self.failIfExists('b')
735
        self.assertFileEqual('baz\n', 'a')
736
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
737
    def test_rename_missing_file(self):
738
        a = open('a', 'wb')
739
        a.write('foo\n')
740
        a.close()
741
742
        try:
743
            osutils._win32_rename('b', 'a')
744
        except (IOError, OSError), e:
745
            self.assertEqual(errno.ENOENT, e.errno)
746
        self.assertFileEqual('foo\n', 'a')
747
748
    def test_rename_missing_dir(self):
749
        os.mkdir('a')
750
        try:
751
            osutils._win32_rename('b', 'a')
752
        except (IOError, OSError), e:
753
            self.assertEqual(errno.ENOENT, e.errno)
754
755
    def test_rename_current_dir(self):
756
        os.mkdir('a')
757
        os.chdir('a')
758
        # You can't rename the working directory
759
        # doing rename non-existant . usually
760
        # just raises ENOENT, since non-existant
761
        # doesn't exist.
762
        try:
763
            osutils._win32_rename('b', '.')
764
        except (IOError, OSError), e:
765
            self.assertEqual(errno.ENOENT, e.errno)
766
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
767
    def test_splitpath(self):
768
        def check(expected, path):
769
            self.assertEqual(expected, osutils.splitpath(path))
770
771
        check(['a'], 'a')
772
        check(['a', 'b'], 'a/b')
773
        check(['a', 'b'], 'a/./b')
774
        check(['a', '.b'], 'a/.b')
775
        check(['a', '.b'], 'a\\.b')
776
777
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
778
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
779
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
780
class TestMacFuncsDirs(TestCaseInTempDir):
781
    """Test mac special functions that require directories."""
782
783
    def test_getcwd(self):
784
        # On Mac, this will actually create Ba\u030agfors
785
        # but chdir will still work, because it accepts both paths
786
        try:
787
            os.mkdir(u'B\xe5gfors')
788
        except UnicodeError:
789
            raise TestSkipped("Unable to create Unicode filename")
790
791
        os.chdir(u'B\xe5gfors')
792
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
793
794
    def test_getcwd_nonnorm(self):
795
        # Test that _mac_getcwd() will normalize this path
796
        try:
797
            os.mkdir(u'Ba\u030agfors')
798
        except UnicodeError:
799
            raise TestSkipped("Unable to create Unicode filename")
800
801
        os.chdir(u'Ba\u030agfors')
802
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
803
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
804
3890.2.6 by John Arbash Meinel
Change name to 'chunks_to_lines', and find an optimized form.
805
class TestChunksToLines(TestCase):
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
806
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
807
    def test_smoketest(self):
808
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
809
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
810
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
811
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
812
3734.2.21 by Vincent Ladeuil
Give test a better name.
813
    def test_osutils_binding(self):
3734.2.20 by Vincent Ladeuil
Fix failing test when CompiledChunksToLines is not available.
814
        from bzrlib.tests import test__chunks_to_lines
815
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
816
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
817
        else:
818
            from bzrlib._chunks_to_lines_py import chunks_to_lines
819
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
3890.2.5 by John Arbash Meinel
More tests for edge cases.
820
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
821
1666.1.6 by Robert Collins
Make knit the default format.
822
class TestSplitLines(TestCase):
823
824
    def test_split_unicode(self):
825
        self.assertEqual([u'foo\n', u'bar\xae'],
826
                         osutils.split_lines(u'foo\nbar\xae'))
827
        self.assertEqual([u'foo\n', u'bar\xae\n'],
828
                         osutils.split_lines(u'foo\nbar\xae\n'))
829
830
    def test_split_with_carriage_returns(self):
831
        self.assertEqual(['foo\rbar\n'],
832
                         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.
833
834
835
class TestWalkDirs(TestCaseInTempDir):
836
837
    def test_walkdirs(self):
838
        tree = [
839
            '.bzr',
840
            '0file',
841
            '1dir/',
842
            '1dir/0file',
843
            '1dir/1dir/',
844
            '2file'
845
            ]
846
        self.build_tree(tree)
847
        expected_dirblocks = [
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
848
                (('', '.'),
849
                 [('0file', '0file', 'file'),
850
                  ('1dir', '1dir', 'directory'),
851
                  ('2file', '2file', 'file'),
852
                 ]
853
                ),
854
                (('1dir', './1dir'),
855
                 [('1dir/0file', '0file', 'file'),
856
                  ('1dir/1dir', '1dir', 'directory'),
857
                 ]
858
                ),
859
                (('1dir/1dir', './1dir/1dir'),
860
                 [
861
                 ]
862
                ),
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
863
            ]
864
        result = []
865
        found_bzrdir = False
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
866
        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.
867
            if len(dirblock) and dirblock[0][1] == '.bzr':
868
                # this tests the filtering of selected paths
869
                found_bzrdir = True
870
                del dirblock[0]
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
871
            result.append((dirdetail, dirblock))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
872
873
        self.assertTrue(found_bzrdir)
874
        self.assertEqual(expected_dirblocks,
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
875
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
876
        # you can search a subdir only, with a supplied prefix.
877
        result = []
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
878
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
879
            result.append(dirblock)
880
        self.assertEqual(expected_dirblocks[1:],
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
881
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
882
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
883
    def test_walkdirs_os_error(self):
884
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
885
        # Pyrex readdir didn't raise useful messages if it had an error
886
        # reading the directory
887
        if sys.platform == 'win32':
888
            raise tests.TestNotApplicable(
889
                "readdir IOError not tested on win32")
890
        os.mkdir("test-unreadable")
891
        os.chmod("test-unreadable", 0000)
892
        # must chmod it back so that it can be removed
893
        self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
894
        # The error is not raised until the generator is actually evaluated.
895
        # (It would be ok if it happened earlier but at the moment it
896
        # doesn't.)
4133.1.1 by Vincent Ladeuil
Fix bzrlib.tests.test_osutils.TestWalkDirs.test_walkdirs_os_error
897
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
898
        self.assertEquals('./test-unreadable', e.filename)
899
        self.assertEquals(errno.EACCES, e.errno)
4133.1.2 by Vincent Ladeuil
Fixed as per Martin's remark about the intent of the test :-}
900
        # Ensure the message contains the file name
901
        self.assertContainsRe(str(e), "\./test-unreadable")
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
902
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
903
    def test__walkdirs_utf8(self):
904
        tree = [
905
            '.bzr',
906
            '0file',
907
            '1dir/',
908
            '1dir/0file',
909
            '1dir/1dir/',
910
            '2file'
911
            ]
912
        self.build_tree(tree)
913
        expected_dirblocks = [
914
                (('', '.'),
915
                 [('0file', '0file', 'file'),
916
                  ('1dir', '1dir', 'directory'),
917
                  ('2file', '2file', 'file'),
918
                 ]
919
                ),
920
                (('1dir', './1dir'),
921
                 [('1dir/0file', '0file', 'file'),
922
                  ('1dir/1dir', '1dir', 'directory'),
923
                 ]
924
                ),
925
                (('1dir/1dir', './1dir/1dir'),
926
                 [
927
                 ]
928
                ),
929
            ]
930
        result = []
931
        found_bzrdir = False
932
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
933
            if len(dirblock) and dirblock[0][1] == '.bzr':
934
                # this tests the filtering of selected paths
935
                found_bzrdir = True
936
                del dirblock[0]
937
            result.append((dirdetail, dirblock))
938
939
        self.assertTrue(found_bzrdir)
940
        self.assertEqual(expected_dirblocks,
941
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
942
        # you can search a subdir only, with a supplied prefix.
943
        result = []
944
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
945
            result.append(dirblock)
946
        self.assertEqual(expected_dirblocks[1:],
947
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
948
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
949
    def _filter_out_stat(self, result):
950
        """Filter out the stat value from the walkdirs result"""
951
        for dirdetail, dirblock in result:
952
            new_dirblock = []
953
            for info in dirblock:
954
                # Ignore info[3] which is the stat
955
                new_dirblock.append((info[0], info[1], info[2], info[4]))
956
            dirblock[:] = new_dirblock
957
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
958
    def _save_platform_info(self):
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
959
        cur_winver = win32utils.winver
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
960
        cur_fs_enc = osutils._fs_enc
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
961
        cur_dir_reader = osutils._selected_dir_reader
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
962
        def restore():
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
963
            win32utils.winver = cur_winver
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
964
            osutils._fs_enc = cur_fs_enc
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
965
            osutils._selected_dir_reader = cur_dir_reader
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
966
        self.addCleanup(restore)
967
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
968
    def assertReadFSDirIs(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'
969
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
970
        # Force it to redetect
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
971
        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'
972
        # 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.
973
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
974
        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'
975
976
    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)
977
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
978
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
979
        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,
980
        osutils._fs_enc = 'UTF-8'
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)
981
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
982
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'
983
    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)
984
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
985
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
986
        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,
987
        osutils._fs_enc = 'US-ASCII'
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)
988
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
989
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'
990
    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)
991
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
992
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
993
        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,
994
        osutils._fs_enc = 'ANSI_X3.4-1968'
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)
995
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
996
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'
997
    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,
998
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
999
        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,
1000
        osutils._fs_enc = 'latin1'
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1001
        self.assertReadFSDirIs(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'
1002
1003
    def test_force_walkdirs_utf8_nt(self):
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1004
        # Disabled because the thunk of the whole walkdirs api is disabled.
1005
        self.requireFeature(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'
1006
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1007
        win32utils.winver = 'Windows NT'
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1008
        from bzrlib._walkdirs_win32 import Win32ReadDir
1009
        self.assertReadFSDirIs(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'
1010
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1011
    def test_force_walkdirs_utf8_98(self):
1012
        self.requireFeature(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'
1013
        self._save_platform_info()
3557.2.6 by John Arbash Meinel
Switch from os.name to bzrlib.win32utils.winver.
1014
        win32utils.winver = 'Windows 98'
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1015
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1016
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1017
    def test_unicode_walkdirs(self):
1018
        """Walkdirs should always return unicode paths."""
1019
        name0 = u'0file-\xb6'
1020
        name1 = u'1dir-\u062c\u0648'
1021
        name2 = u'2file-\u0633'
1022
        tree = [
1023
            name0,
1024
            name1 + '/',
1025
            name1 + '/' + name0,
1026
            name1 + '/' + name1 + '/',
1027
            name2,
1028
            ]
1029
        try:
1030
            self.build_tree(tree)
1031
        except UnicodeError:
1032
            raise TestSkipped('Could not represent Unicode chars'
1033
                              ' in current encoding.')
1034
        expected_dirblocks = [
1035
                ((u'', u'.'),
1036
                 [(name0, name0, 'file', './' + name0),
1037
                  (name1, name1, 'directory', './' + name1),
1038
                  (name2, name2, 'file', './' + name2),
1039
                 ]
1040
                ),
1041
                ((name1, './' + name1),
1042
                 [(name1 + '/' + name0, name0, 'file', './' + name1
1043
                                                        + '/' + name0),
1044
                  (name1 + '/' + name1, name1, 'directory', './' + name1
1045
                                                            + '/' + name1),
1046
                 ]
1047
                ),
1048
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
1049
                 [
1050
                 ]
1051
                ),
1052
            ]
1053
        result = list(osutils.walkdirs('.'))
1054
        self._filter_out_stat(result)
1055
        self.assertEqual(expected_dirblocks, result)
1056
        result = list(osutils.walkdirs(u'./'+name1, name1))
1057
        self._filter_out_stat(result)
1058
        self.assertEqual(expected_dirblocks[1:], result)
1059
1060
    def test_unicode__walkdirs_utf8(self):
1061
        """Walkdirs_utf8 should always return utf8 paths.
1062
1063
        The abspath portion might be in unicode or utf-8
1064
        """
1065
        name0 = u'0file-\xb6'
1066
        name1 = u'1dir-\u062c\u0648'
1067
        name2 = u'2file-\u0633'
1068
        tree = [
1069
            name0,
1070
            name1 + '/',
1071
            name1 + '/' + name0,
1072
            name1 + '/' + name1 + '/',
1073
            name2,
1074
            ]
1075
        try:
1076
            self.build_tree(tree)
1077
        except UnicodeError:
1078
            raise TestSkipped('Could not represent Unicode chars'
1079
                              ' in current encoding.')
1080
        name0 = name0.encode('utf8')
1081
        name1 = name1.encode('utf8')
1082
        name2 = name2.encode('utf8')
1083
1084
        expected_dirblocks = [
1085
                (('', '.'),
1086
                 [(name0, name0, 'file', './' + name0),
1087
                  (name1, name1, 'directory', './' + name1),
1088
                  (name2, name2, 'file', './' + name2),
1089
                 ]
1090
                ),
1091
                ((name1, './' + name1),
1092
                 [(name1 + '/' + name0, name0, 'file', './' + name1
1093
                                                        + '/' + name0),
1094
                  (name1 + '/' + name1, name1, 'directory', './' + name1
1095
                                                            + '/' + name1),
1096
                 ]
1097
                ),
1098
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
1099
                 [
1100
                 ]
1101
                ),
1102
            ]
1103
        result = []
1104
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1105
        # all abspaths are Unicode, and encode them back into utf8.
1106
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1107
            self.assertIsInstance(dirdetail[0], str)
1108
            if isinstance(dirdetail[1], unicode):
2324.2.4 by Dmitry Vasiliev
Fixed test_unicode__walkdirs_utf8 test
1109
                dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1110
                dirblock = [list(info) for info in dirblock]
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1111
                for info in dirblock:
1112
                    self.assertIsInstance(info[4], unicode)
1113
                    info[4] = info[4].encode('utf8')
1114
            new_dirblock = []
1115
            for info in dirblock:
1116
                self.assertIsInstance(info[0], str)
1117
                self.assertIsInstance(info[1], str)
1118
                self.assertIsInstance(info[4], str)
1119
                # Remove the stat information
1120
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1121
            result.append((dirdetail, new_dirblock))
1122
        self.assertEqual(expected_dirblocks, result)
1123
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1124
    def test__walkdirs_utf8_with_unicode_fs(self):
1125
        """UnicodeDirReader should be a safe fallback everywhere
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1126
1127
        The abspath portion should be in unicode
1128
        """
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1129
        # Use the unicode reader. TODO: split into driver-and-driven unit
1130
        # tests.
1131
        self._save_platform_info()
1132
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1133
        name0u = u'0file-\xb6'
1134
        name1u = u'1dir-\u062c\u0648'
1135
        name2u = u'2file-\u0633'
1136
        tree = [
1137
            name0u,
1138
            name1u + '/',
1139
            name1u + '/' + name0u,
1140
            name1u + '/' + name1u + '/',
1141
            name2u,
1142
            ]
1143
        try:
1144
            self.build_tree(tree)
1145
        except UnicodeError:
1146
            raise TestSkipped('Could not represent Unicode chars'
1147
                              ' in current encoding.')
1148
        name0 = name0u.encode('utf8')
1149
        name1 = name1u.encode('utf8')
1150
        name2 = name2u.encode('utf8')
1151
1152
        # All of the abspaths should be in unicode, all of the relative paths
1153
        # should be in utf8
1154
        expected_dirblocks = [
1155
                (('', '.'),
1156
                 [(name0, name0, 'file', './' + name0u),
1157
                  (name1, name1, 'directory', './' + name1u),
1158
                  (name2, name2, 'file', './' + name2u),
1159
                 ]
1160
                ),
1161
                ((name1, './' + name1u),
1162
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1163
                                                        + '/' + name0u),
1164
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1165
                                                            + '/' + name1u),
1166
                 ]
1167
                ),
1168
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1169
                 [
1170
                 ]
1171
                ),
1172
            ]
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1173
        result = list(osutils._walkdirs_utf8('.'))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1174
        self._filter_out_stat(result)
1175
        self.assertEqual(expected_dirblocks, result)
1176
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1177
    def test__walkdirs_utf8_win32readdir(self):
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1178
        self.requireFeature(Win32ReadDirFeature)
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1179
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1180
        from bzrlib._walkdirs_win32 import Win32ReadDir
1181
        self._save_platform_info()
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1182
        osutils._selected_dir_reader = Win32ReadDir()
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1183
        name0u = u'0file-\xb6'
1184
        name1u = u'1dir-\u062c\u0648'
1185
        name2u = u'2file-\u0633'
1186
        tree = [
1187
            name0u,
1188
            name1u + '/',
1189
            name1u + '/' + name0u,
1190
            name1u + '/' + name1u + '/',
1191
            name2u,
1192
            ]
1193
        self.build_tree(tree)
1194
        name0 = name0u.encode('utf8')
1195
        name1 = name1u.encode('utf8')
1196
        name2 = name2u.encode('utf8')
1197
1198
        # All of the abspaths should be in unicode, all of the relative paths
1199
        # should be in utf8
1200
        expected_dirblocks = [
1201
                (('', '.'),
1202
                 [(name0, name0, 'file', './' + name0u),
1203
                  (name1, name1, 'directory', './' + name1u),
1204
                  (name2, name2, 'file', './' + name2u),
1205
                 ]
1206
                ),
1207
                ((name1, './' + name1u),
1208
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1209
                                                        + '/' + name0u),
1210
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1211
                                                            + '/' + name1u),
1212
                 ]
1213
                ),
1214
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1215
                 [
1216
                 ]
1217
                ),
1218
            ]
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1219
        result = list(osutils._walkdirs_utf8(u'.'))
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1220
        self._filter_out_stat(result)
1221
        self.assertEqual(expected_dirblocks, result)
1222
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1223
    def assertStatIsCorrect(self, path, win32stat):
1224
        os_stat = os.stat(path)
1225
        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.
1226
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
1227
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
1228
        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.
1229
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
1230
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
1231
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
1232
1233
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1234
        """make sure our Stat values are valid"""
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1235
        self.requireFeature(Win32ReadDirFeature)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1236
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1237
        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.
1238
        name0u = u'0file-\xb6'
1239
        name0 = name0u.encode('utf8')
1240
        self.build_tree([name0u])
1241
        # I hate to sleep() here, but I'm trying to make the ctime different
1242
        # from the mtime
1243
        time.sleep(2)
1244
        f = open(name0u, 'ab')
1245
        try:
1246
            f.write('just a small update')
1247
        finally:
1248
            f.close()
1249
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1250
        result = Win32ReadDir().read_dir('', u'.')
1251
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1252
        self.assertEqual((name0, name0, 'file'), entry[:3])
1253
        self.assertEqual(u'./' + name0u, entry[4])
1254
        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.
1255
        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.
1256
1257
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1258
        """make sure our Stat values are valid"""
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1259
        self.requireFeature(Win32ReadDirFeature)
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1260
        self.requireFeature(tests.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1261
        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.
1262
        name0u = u'0dir-\u062c\u0648'
1263
        name0 = name0u.encode('utf8')
1264
        self.build_tree([name0u + '/'])
1265
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1266
        result = Win32ReadDir().read_dir('', u'.')
1267
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1268
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1269
        self.assertEqual(u'./' + name0u, entry[4])
1270
        self.assertStatIsCorrect(entry[4], entry[3])
1271
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1272
    def assertPathCompare(self, path_less, path_greater):
1273
        """check that path_less and path_greater compare correctly."""
1274
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1275
            path_less, path_less))
1276
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1277
            path_greater, path_greater))
1278
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
1279
            path_less, path_greater))
1280
        self.assertEqual(1, osutils.compare_paths_prefix_order(
1281
            path_greater, path_less))
1282
1283
    def test_compare_paths_prefix_order(self):
1284
        # root before all else
1285
        self.assertPathCompare("/", "/a")
1286
        # alpha within a dir
1287
        self.assertPathCompare("/a", "/b")
1288
        self.assertPathCompare("/b", "/z")
1289
        # high dirs before lower.
1290
        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.
1291
        # except if the deeper dir should be output first
1292
        self.assertPathCompare("/a/b/c", "/d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1293
        # lexical betwen dirs of the same height
1294
        self.assertPathCompare("/a/z", "/z/z")
1295
        self.assertPathCompare("/a/c/z", "/a/d/e")
1296
1297
        # this should also be consistent for no leading / paths
1298
        # root before all else
1299
        self.assertPathCompare("", "a")
1300
        # alpha within a dir
1301
        self.assertPathCompare("a", "b")
1302
        self.assertPathCompare("b", "z")
1303
        # high dirs before lower.
1304
        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.
1305
        # except if the deeper dir should be output first
1306
        self.assertPathCompare("a/b/c", "d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1307
        # lexical betwen dirs of the same height
1308
        self.assertPathCompare("a/z", "z/z")
1309
        self.assertPathCompare("a/c/z", "a/d/e")
1310
1773.3.3 by Robert Collins
Add new tests John Meinel asked for.
1311
    def test_path_prefix_sorting(self):
1312
        """Doing a sort on path prefix should match our sample data."""
1313
        original_paths = [
1314
            'a',
1315
            'a/b',
1316
            'a/b/c',
1317
            'b',
1318
            'b/c',
1319
            'd',
1320
            'd/e',
1321
            'd/e/f',
1322
            'd/f',
1323
            'd/g',
1324
            'g',
1325
            ]
1326
1327
        dir_sorted_paths = [
1328
            'a',
1329
            'b',
1330
            'd',
1331
            'g',
1332
            'a/b',
1333
            'a/b/c',
1334
            'b/c',
1335
            'd/e',
1336
            'd/f',
1337
            'd/g',
1338
            'd/e/f',
1339
            ]
1340
1341
        self.assertEqual(
1342
            dir_sorted_paths,
1343
            sorted(original_paths, key=osutils.path_prefix_key))
1344
        # using the comparison routine shoudl work too:
1345
        self.assertEqual(
1346
            dir_sorted_paths,
1347
            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.
1348
1349
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1350
class TestCopyTree(TestCaseInTempDir):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1351
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1352
    def test_copy_basic_tree(self):
1353
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1354
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1355
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1356
        self.assertEqual(['c'], os.listdir('target/b'))
1357
1358
    def test_copy_tree_target_exists(self):
1359
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
1360
                         'target/'])
1361
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1362
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1363
        self.assertEqual(['c'], os.listdir('target/b'))
1364
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1365
    def test_copy_tree_symlinks(self):
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1366
        self.requireFeature(SymlinkFeature)
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1367
        self.build_tree(['source/'])
1368
        os.symlink('a/generic/path', 'source/lnk')
1369
        osutils.copy_tree('source', 'target')
1370
        self.assertEqual(['lnk'], os.listdir('target'))
1371
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
1372
1373
    def test_copy_tree_handlers(self):
1374
        processed_files = []
1375
        processed_links = []
1376
        def file_handler(from_path, to_path):
1377
            processed_files.append(('f', from_path, to_path))
1378
        def dir_handler(from_path, to_path):
1379
            processed_files.append(('d', from_path, to_path))
1380
        def link_handler(from_path, to_path):
1381
            processed_links.append((from_path, to_path))
1382
        handlers = {'file':file_handler,
1383
                    'directory':dir_handler,
1384
                    'symlink':link_handler,
1385
                   }
1386
1387
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1388
        if osutils.has_symlinks():
1389
            os.symlink('a/generic/path', 'source/lnk')
1390
        osutils.copy_tree('source', 'target', handlers=handlers)
1391
1392
        self.assertEqual([('d', 'source', 'target'),
1393
                          ('f', 'source/a', 'target/a'),
1394
                          ('d', 'source/b', 'target/b'),
1395
                          ('f', 'source/b/c', 'target/b/c'),
1396
                         ], processed_files)
1397
        self.failIfExists('target')
1398
        if osutils.has_symlinks():
1399
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1400
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1401
2192.1.2 by Alexander Belchenko
Tests for osutils.get_terminal_encoding()
1402
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
1403
# [bialix] 2006/12/26
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.
1404
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1405
1406
class TestSetUnsetEnv(TestCase):
1407
    """Test updating the environment"""
1408
1409
    def setUp(self):
1410
        super(TestSetUnsetEnv, self).setUp()
1411
1412
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1413
                         'Environment was not cleaned up properly.'
1414
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
1415
        def cleanup():
1416
            if 'BZR_TEST_ENV_VAR' in os.environ:
1417
                del os.environ['BZR_TEST_ENV_VAR']
1418
1419
        self.addCleanup(cleanup)
1420
1421
    def test_set(self):
1422
        """Test that we can set an env variable"""
1423
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1424
        self.assertEqual(None, old)
1425
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1426
1427
    def test_double_set(self):
1428
        """Test that we get the old value out"""
1429
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1430
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
1431
        self.assertEqual('foo', old)
1432
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1433
1434
    def test_unicode(self):
1435
        """Environment can only contain plain strings
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1436
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1437
        So Unicode strings must be encoded.
1438
        """
2785.1.5 by Alexander Belchenko
support for non-ascii BZR_HOME in show_version()
1439
        uni_val, env_val = probe_unicode_in_user_encoding()
1440
        if uni_val is None:
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1441
            raise TestSkipped('Cannot find a unicode character that works in'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1442
                              ' encoding %s' % (osutils.get_user_encoding(),))
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1443
1444
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1445
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1446
1447
    def test_unset(self):
1448
        """Test that passing None will remove the env var"""
1449
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1450
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1451
        self.assertEqual('foo', old)
1452
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1453
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1454
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
1455
1456
class TestLocalTimeOffset(TestCase):
1457
1458
    def test_local_time_offset(self):
1459
        """Test that local_time_offset() returns a sane value."""
1460
        offset = osutils.local_time_offset()
1461
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
1462
        # Test that the offset is no more than a eighteen hours in
1463
        # either direction.
1464
        # Time zone handling is system specific, so it is difficult to
1465
        # do more specific tests, but a value outside of this range is
1466
        # probably wrong.
1467
        eighteen_hours = 18 * 3600
1468
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
1469
1470
    def test_local_time_offset_with_timestamp(self):
1471
        """Test that local_time_offset() works with a timestamp."""
1472
        offset = osutils.local_time_offset(1000000000.1234567)
1473
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
1474
        eighteen_hours = 18 * 3600
1475
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
2922.1.2 by John Arbash Meinel
Add tests for sha_file_by_name.
1476
1477
1478
class TestShaFileByName(TestCaseInTempDir):
1479
1480
    def test_sha_empty(self):
1481
        self.build_tree_contents([('foo', '')])
1482
        expected_sha = osutils.sha_string('')
1483
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1484
1485
    def test_sha_mixed_endings(self):
1486
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1487
        self.build_tree_contents([('foo', text)])
1488
        expected_sha = osutils.sha_string(text)
1489
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
3089.3.9 by Ian Clatworthy
add test for resource loading
1490
1491
1492
class TestResourceLoading(TestCaseInTempDir):
1493
1494
    def test_resource_string(self):
1495
        # test resource in bzrlib
1496
        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
1497
        self.assertContainsRe(text, "debug_flags = set()")
3089.3.9 by Ian Clatworthy
add test for resource loading
1498
        # test resource under bzrlib
1499
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1500
        self.assertContainsRe(text, "class TextUIFactory")
1501
        # test unsupported package
1502
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1503
            'yyy.xx')
1504
        # test unknown resource
1505
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')