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