/brz/remove-bazaar

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