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