/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Jelmer Vernooij
  • Date: 2009-05-26 07:48:03 UTC
  • mto: This revision was merged to the branch mainline in revision 4381.
  • Revision ID: jelmer@samba.org-20090526074803-fx1cdhcfcuxux8pf
Review feedback from Ian.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for the osutils wrapper."""
 
18
 
 
19
from cStringIO import StringIO
 
20
import errno
 
21
import os
 
22
import re
 
23
import socket
 
24
import stat
 
25
import sys
 
26
import time
 
27
 
 
28
from bzrlib import (
 
29
    errors,
 
30
    osutils,
 
31
    tests,
 
32
    win32utils,
 
33
    )
 
34
from bzrlib.tests import (
 
35
    file_utils,
 
36
    test__walkdirs_win32,
 
37
    )
 
38
 
 
39
 
 
40
class _UTF8DirReaderFeature(tests.Feature):
 
41
 
 
42
    def _probe(self):
 
43
        try:
 
44
            from bzrlib import _readdir_pyx
 
45
            self.reader = _readdir_pyx.UTF8DirReader
 
46
            return True
 
47
        except ImportError:
 
48
            return False
 
49
 
 
50
    def feature_name(self):
 
51
        return 'bzrlib._readdir_pyx'
 
52
 
 
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
 
54
 
 
55
 
 
56
def _already_unicode(s):
 
57
    return s
 
58
 
 
59
 
 
60
def _fs_enc_to_unicode(s):
 
61
    return s.decode(osutils._fs_enc)
 
62
 
 
63
 
 
64
def _utf8_to_unicode(s):
 
65
    return s.decode('UTF-8')
 
66
 
 
67
 
 
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.
 
75
    scenarios = [('unicode',
 
76
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
 
77
                       _native_to_unicode=_already_unicode))]
 
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
 
82
        scenarios.append(('utf8',
 
83
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
 
84
                               _native_to_unicode=_utf8_to_unicode)))
 
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
 
91
            scenarios.append(
 
92
                ('win32',
 
93
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
 
94
                      _native_to_unicode=_fs_enc_to_unicode)))
 
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
 
 
108
 
 
109
class TestContainsWhitespace(tests.TestCase):
 
110
 
 
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
 
 
125
 
 
126
class TestRename(tests.TestCaseInTempDir):
 
127
 
 
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
 
 
161
    def test_rename_change_case(self):
 
162
        # on Windows we should be able to change filename case by rename
 
163
        self.build_tree(['a', 'b/'])
 
164
        osutils.rename('a', 'A')
 
165
        osutils.rename('b', 'B')
 
166
        # we can't use failUnlessExists on case-insensitive filesystem
 
167
        # so try to check shape of the tree
 
168
        shape = sorted(os.listdir('.'))
 
169
        self.assertEquals(['A', 'B'], shape)
 
170
 
 
171
 
 
172
class TestRandChars(tests.TestCase):
 
173
 
 
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
 
 
184
 
 
185
class TestIsInside(tests.TestCase):
 
186
 
 
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'))
 
195
 
 
196
    def test_is_inside_any(self):
 
197
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
198
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
 
199
                         (['src'], SRC_FOO_C),
 
200
                         (['src'], 'src'),
 
201
                         ]:
 
202
            self.assert_(osutils.is_inside_any(dirs, fn))
 
203
        for dirs, fn in [(['src'], 'srccontrol'),
 
204
                         (['src'], 'srccontrol/foo')]:
 
205
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
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
                         ]:
 
214
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
 
215
 
 
216
        for dirs, fn in [(['src'], 'srccontrol'),
 
217
                         (['srccontrol/foo.c'], 'src'),
 
218
                         (['src'], 'srccontrol/foo')]:
 
219
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
 
220
 
 
221
 
 
222
class TestRmTree(tests.TestCaseInTempDir):
 
223
 
 
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
 
 
242
 
 
243
class TestKind(tests.TestCaseInTempDir):
 
244
 
 
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'))
 
252
 
 
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')
 
278
 
 
279
    def test_kind_marker(self):
 
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):
 
289
 
 
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()
 
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())
 
306
 
 
307
 
 
308
class TestDateTime(tests.TestCase):
 
309
 
 
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
 
 
315
    def test_format_delta(self):
 
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)
 
339
 
 
340
        # We handle when time steps the wrong direction because computers
 
341
        # don't have synchronized clocks.
 
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)
 
345
 
 
346
    def test_format_date(self):
 
347
        self.assertRaises(errors.UnsupportedTimezoneFormat,
 
348
            osutils.format_date, 0, timezone='foo')
 
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
 
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.
 
355
 
 
356
    def test_local_time_offset(self):
 
357
        """Test that local_time_offset() returns a sane value."""
 
358
        offset = osutils.local_time_offset()
 
359
        self.assertTrue(isinstance(offset, int))
 
360
        # Test that the offset is no more than a eighteen hours in
 
361
        # either direction.
 
362
        # Time zone handling is system specific, so it is difficult to
 
363
        # do more specific tests, but a value outside of this range is
 
364
        # probably wrong.
 
365
        eighteen_hours = 18 * 3600
 
366
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
367
 
 
368
    def test_local_time_offset_with_timestamp(self):
 
369
        """Test that local_time_offset() works with a timestamp."""
 
370
        offset = osutils.local_time_offset(1000000000.1234567)
 
371
        self.assertTrue(isinstance(offset, int))
 
372
        eighteen_hours = 18 * 3600
 
373
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
374
 
 
375
 
 
376
class TestLinks(tests.TestCaseInTempDir):
 
377
 
 
378
    def test_dereference_path(self):
 
379
        self.requireFeature(tests.SymlinkFeature)
 
380
        cwd = osutils.realpath('.')
 
381
        os.mkdir('bar')
 
382
        bar_path = osutils.pathjoin(cwd, 'bar')
 
383
        # Using './' to avoid bug #1213894 (first path component not
 
384
        # dereferenced) in Python 2.4.1 and earlier
 
385
        self.assertEqual(bar_path, osutils.realpath('./bar'))
 
386
        os.symlink('bar', 'foo')
 
387
        self.assertEqual(bar_path, osutils.realpath('./foo'))
 
388
 
 
389
        # Does not dereference terminal symlinks
 
390
        foo_path = osutils.pathjoin(cwd, 'foo')
 
391
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
 
392
 
 
393
        # Dereferences parent symlinks
 
394
        os.mkdir('bar/baz')
 
395
        baz_path = osutils.pathjoin(bar_path, 'baz')
 
396
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
 
397
 
 
398
        # Dereferences parent symlinks that are the first path element
 
399
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
 
400
 
 
401
        # Dereferences parent symlinks in absolute paths
 
402
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
 
403
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
 
404
 
 
405
    def test_changing_access(self):
 
406
        f = file('file', 'w')
 
407
        f.write('monkey')
 
408
        f.close()
 
409
 
 
410
        # Make a file readonly
 
411
        osutils.make_readonly('file')
 
412
        mode = os.lstat('file').st_mode
 
413
        self.assertEqual(mode, mode & 0777555)
 
414
 
 
415
        # Make a file writable
 
416
        osutils.make_writable('file')
 
417
        mode = os.lstat('file').st_mode
 
418
        self.assertEqual(mode, mode | 0200)
 
419
 
 
420
        if osutils.has_symlinks():
 
421
            # should not error when handed a symlink
 
422
            os.symlink('nonexistent', 'dangling')
 
423
            osutils.make_readonly('dangling')
 
424
            osutils.make_writable('dangling')
 
425
 
 
426
    def test_host_os_dereferences_symlinks(self):
 
427
        osutils.host_os_dereferences_symlinks()
 
428
 
 
429
 
 
430
class TestCanonicalRelPath(tests.TestCaseInTempDir):
 
431
 
 
432
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
 
433
 
 
434
    def test_canonical_relpath_simple(self):
 
435
        f = file('MixedCaseName', 'w')
 
436
        f.close()
 
437
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
438
        real_base_dir = osutils.realpath(self.test_base_dir)
 
439
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
 
440
        self.failUnlessEqual('work/MixedCaseName', actual)
 
441
 
 
442
    def test_canonical_relpath_missing_tail(self):
 
443
        os.mkdir('MixedCaseParent')
 
444
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
445
        real_base_dir = osutils.realpath(self.test_base_dir)
 
446
        actual = osutils.canonical_relpath(real_base_dir,
 
447
                                           'mixedcaseparent/nochild')
 
448
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
 
449
 
 
450
 
 
451
class TestPumpFile(tests.TestCase):
 
452
    """Test pumpfile method."""
 
453
 
 
454
    def setUp(self):
 
455
        tests.TestCase.setUp(self)
 
456
        # create a test datablock
 
457
        self.block_size = 512
 
458
        pattern = '0123456789ABCDEF'
 
459
        self.test_data = pattern * (3 * self.block_size / len(pattern))
 
460
        self.test_data_len = len(self.test_data)
 
461
 
 
462
    def test_bracket_block_size(self):
 
463
        """Read data in blocks with the requested read size bracketing the
 
464
        block size."""
 
465
        # make sure test data is larger than max read size
 
466
        self.assertTrue(self.test_data_len > self.block_size)
 
467
 
 
468
        from_file = file_utils.FakeReadFile(self.test_data)
 
469
        to_file = StringIO()
 
470
 
 
471
        # read (max / 2) bytes and verify read size wasn't affected
 
472
        num_bytes_to_read = self.block_size / 2
 
473
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
474
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
 
475
        self.assertEqual(from_file.get_read_count(), 1)
 
476
 
 
477
        # read (max) bytes and verify read size wasn't affected
 
478
        num_bytes_to_read = self.block_size
 
479
        from_file.reset_read_count()
 
480
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
481
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
 
482
        self.assertEqual(from_file.get_read_count(), 1)
 
483
 
 
484
        # read (max + 1) bytes and verify read size was limited
 
485
        num_bytes_to_read = self.block_size + 1
 
486
        from_file.reset_read_count()
 
487
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
488
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
489
        self.assertEqual(from_file.get_read_count(), 2)
 
490
 
 
491
        # finish reading the rest of the data
 
492
        num_bytes_to_read = self.test_data_len - to_file.tell()
 
493
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
494
 
 
495
        # report error if the data wasn't equal (we only report the size due
 
496
        # to the length of the data)
 
497
        response_data = to_file.getvalue()
 
498
        if response_data != self.test_data:
 
499
            message = "Data not equal.  Expected %d bytes, received %d."
 
500
            self.fail(message % (len(response_data), self.test_data_len))
 
501
 
 
502
    def test_specified_size(self):
 
503
        """Request a transfer larger than the maximum block size and verify
 
504
        that the maximum read doesn't exceed the block_size."""
 
505
        # make sure test data is larger than max read size
 
506
        self.assertTrue(self.test_data_len > self.block_size)
 
507
 
 
508
        # retrieve data in blocks
 
509
        from_file = file_utils.FakeReadFile(self.test_data)
 
510
        to_file = StringIO()
 
511
        osutils.pumpfile(from_file, to_file, self.test_data_len,
 
512
                         self.block_size)
 
513
 
 
514
        # verify read size was equal to the maximum read size
 
515
        self.assertTrue(from_file.get_max_read_size() > 0)
 
516
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
517
        self.assertEqual(from_file.get_read_count(), 3)
 
518
 
 
519
        # report error if the data wasn't equal (we only report the size due
 
520
        # to the length of the data)
 
521
        response_data = to_file.getvalue()
 
522
        if response_data != self.test_data:
 
523
            message = "Data not equal.  Expected %d bytes, received %d."
 
524
            self.fail(message % (len(response_data), self.test_data_len))
 
525
 
 
526
    def test_to_eof(self):
 
527
        """Read to end-of-file and verify that the reads are not larger than
 
528
        the maximum read size."""
 
529
        # make sure test data is larger than max read size
 
530
        self.assertTrue(self.test_data_len > self.block_size)
 
531
 
 
532
        # retrieve data to EOF
 
533
        from_file = file_utils.FakeReadFile(self.test_data)
 
534
        to_file = StringIO()
 
535
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
 
536
 
 
537
        # verify read size was equal to the maximum read size
 
538
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
539
        self.assertEqual(from_file.get_read_count(), 4)
 
540
 
 
541
        # report error if the data wasn't equal (we only report the size due
 
542
        # to the length of the data)
 
543
        response_data = to_file.getvalue()
 
544
        if response_data != self.test_data:
 
545
            message = "Data not equal.  Expected %d bytes, received %d."
 
546
            self.fail(message % (len(response_data), self.test_data_len))
 
547
 
 
548
    def test_defaults(self):
 
549
        """Verifies that the default arguments will read to EOF -- this
 
550
        test verifies that any existing usages of pumpfile will not be broken
 
551
        with this new version."""
 
552
        # retrieve data using default (old) pumpfile method
 
553
        from_file = file_utils.FakeReadFile(self.test_data)
 
554
        to_file = StringIO()
 
555
        osutils.pumpfile(from_file, to_file)
 
556
 
 
557
        # report error if the data wasn't equal (we only report the size due
 
558
        # to the length of the data)
 
559
        response_data = to_file.getvalue()
 
560
        if response_data != self.test_data:
 
561
            message = "Data not equal.  Expected %d bytes, received %d."
 
562
            self.fail(message % (len(response_data), self.test_data_len))
 
563
 
 
564
    def test_report_activity(self):
 
565
        activity = []
 
566
        def log_activity(length, direction):
 
567
            activity.append((length, direction))
 
568
        from_file = StringIO(self.test_data)
 
569
        to_file = StringIO()
 
570
        osutils.pumpfile(from_file, to_file, buff_size=500,
 
571
                         report_activity=log_activity, direction='read')
 
572
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
 
573
                          (36, 'read')], activity)
 
574
 
 
575
        from_file = StringIO(self.test_data)
 
576
        to_file = StringIO()
 
577
        del activity[:]
 
578
        osutils.pumpfile(from_file, to_file, buff_size=500,
 
579
                         report_activity=log_activity, direction='write')
 
580
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
 
581
                          (36, 'write')], activity)
 
582
 
 
583
        # And with a limited amount of data
 
584
        from_file = StringIO(self.test_data)
 
585
        to_file = StringIO()
 
586
        del activity[:]
 
587
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
 
588
                         report_activity=log_activity, direction='read')
 
589
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
 
590
 
 
591
 
 
592
 
 
593
class TestPumpStringFile(tests.TestCase):
 
594
 
 
595
    def test_empty(self):
 
596
        output = StringIO()
 
597
        osutils.pump_string_file("", output)
 
598
        self.assertEqual("", output.getvalue())
 
599
 
 
600
    def test_more_than_segment_size(self):
 
601
        output = StringIO()
 
602
        osutils.pump_string_file("123456789", output, 2)
 
603
        self.assertEqual("123456789", output.getvalue())
 
604
 
 
605
    def test_segment_size(self):
 
606
        output = StringIO()
 
607
        osutils.pump_string_file("12", output, 2)
 
608
        self.assertEqual("12", output.getvalue())
 
609
 
 
610
    def test_segment_size_multiple(self):
 
611
        output = StringIO()
 
612
        osutils.pump_string_file("1234", output, 2)
 
613
        self.assertEqual("1234", output.getvalue())
 
614
 
 
615
 
 
616
class TestSafeUnicode(tests.TestCase):
 
617
 
 
618
    def test_from_ascii_string(self):
 
619
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
 
620
 
 
621
    def test_from_unicode_string_ascii_contents(self):
 
622
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
 
623
 
 
624
    def test_from_unicode_string_unicode_contents(self):
 
625
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
 
626
 
 
627
    def test_from_utf8_string(self):
 
628
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
 
629
 
 
630
    def test_bad_utf8_string(self):
 
631
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
632
                          osutils.safe_unicode,
 
633
                          '\xbb\xbb')
 
634
 
 
635
 
 
636
class TestSafeUtf8(tests.TestCase):
 
637
 
 
638
    def test_from_ascii_string(self):
 
639
        f = 'foobar'
 
640
        self.assertEqual('foobar', osutils.safe_utf8(f))
 
641
 
 
642
    def test_from_unicode_string_ascii_contents(self):
 
643
        self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
 
644
 
 
645
    def test_from_unicode_string_unicode_contents(self):
 
646
        self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
 
647
 
 
648
    def test_from_utf8_string(self):
 
649
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
 
650
 
 
651
    def test_bad_utf8_string(self):
 
652
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
653
                          osutils.safe_utf8, '\xbb\xbb')
 
654
 
 
655
 
 
656
class TestSafeRevisionId(tests.TestCase):
 
657
 
 
658
    def test_from_ascii_string(self):
 
659
        # this shouldn't give a warning because it's getting an ascii string
 
660
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
 
661
 
 
662
    def test_from_unicode_string_ascii_contents(self):
 
663
        self.assertEqual('bargam',
 
664
                         osutils.safe_revision_id(u'bargam', warn=False))
 
665
 
 
666
    def test_from_unicode_deprecated(self):
 
667
        self.assertEqual('bargam',
 
668
            self.callDeprecated([osutils._revision_id_warning],
 
669
                                osutils.safe_revision_id, u'bargam'))
 
670
 
 
671
    def test_from_unicode_string_unicode_contents(self):
 
672
        self.assertEqual('bargam\xc2\xae',
 
673
                         osutils.safe_revision_id(u'bargam\xae', warn=False))
 
674
 
 
675
    def test_from_utf8_string(self):
 
676
        self.assertEqual('foo\xc2\xae',
 
677
                         osutils.safe_revision_id('foo\xc2\xae'))
 
678
 
 
679
    def test_none(self):
 
680
        """Currently, None is a valid revision_id"""
 
681
        self.assertEqual(None, osutils.safe_revision_id(None))
 
682
 
 
683
 
 
684
class TestSafeFileId(tests.TestCase):
 
685
 
 
686
    def test_from_ascii_string(self):
 
687
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
 
688
 
 
689
    def test_from_unicode_string_ascii_contents(self):
 
690
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
 
691
 
 
692
    def test_from_unicode_deprecated(self):
 
693
        self.assertEqual('bargam',
 
694
            self.callDeprecated([osutils._file_id_warning],
 
695
                                osutils.safe_file_id, u'bargam'))
 
696
 
 
697
    def test_from_unicode_string_unicode_contents(self):
 
698
        self.assertEqual('bargam\xc2\xae',
 
699
                         osutils.safe_file_id(u'bargam\xae', warn=False))
 
700
 
 
701
    def test_from_utf8_string(self):
 
702
        self.assertEqual('foo\xc2\xae',
 
703
                         osutils.safe_file_id('foo\xc2\xae'))
 
704
 
 
705
    def test_none(self):
 
706
        """Currently, None is a valid revision_id"""
 
707
        self.assertEqual(None, osutils.safe_file_id(None))
 
708
 
 
709
 
 
710
class TestWin32Funcs(tests.TestCase):
 
711
    """Test that _win32 versions of os utilities return appropriate paths."""
 
712
 
 
713
    def test_abspath(self):
 
714
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
 
715
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
 
716
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
 
717
        self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
 
718
 
 
719
    def test_realpath(self):
 
720
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
 
721
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
 
722
 
 
723
    def test_pathjoin(self):
 
724
        self.assertEqual('path/to/foo',
 
725
                         osutils._win32_pathjoin('path', 'to', 'foo'))
 
726
        self.assertEqual('C:/foo',
 
727
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
728
        self.assertEqual('C:/foo',
 
729
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
 
730
        self.assertEqual('path/to/foo',
 
731
                         osutils._win32_pathjoin('path/to/', 'foo'))
 
732
        self.assertEqual('/foo',
 
733
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
734
        self.assertEqual('/foo',
 
735
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
736
 
 
737
    def test_normpath(self):
 
738
        self.assertEqual('path/to/foo',
 
739
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
740
        self.assertEqual('path/to/foo',
 
741
                         osutils._win32_normpath('path//from/../to/./foo'))
 
742
 
 
743
    def test_getcwd(self):
 
744
        cwd = osutils._win32_getcwd()
 
745
        os_cwd = os.getcwdu()
 
746
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
 
747
        # win32 is inconsistent whether it returns lower or upper case
 
748
        # and even if it was consistent the user might type the other
 
749
        # so we force it to uppercase
 
750
        # running python.exe under cmd.exe return capital C:\\
 
751
        # running win32 python inside a cygwin shell returns lowercase
 
752
        self.assertEqual(os_cwd[0].upper(), cwd[0])
 
753
 
 
754
    def test_fixdrive(self):
 
755
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
 
756
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
 
757
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
 
758
 
 
759
    def test_win98_abspath(self):
 
760
        # absolute path
 
761
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
 
762
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
 
763
        # UNC path
 
764
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
 
765
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
 
766
        # relative path
 
767
        cwd = osutils.getcwd().rstrip('/')
 
768
        drive = osutils._nt_splitdrive(cwd)[0]
 
769
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
 
770
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
 
771
        # unicode path
 
772
        u = u'\u1234'
 
773
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
 
774
 
 
775
 
 
776
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
 
777
    """Test win32 functions that create files."""
 
778
 
 
779
    def test_getcwd(self):
 
780
        self.requireFeature(tests.UnicodeFilenameFeature)
 
781
        os.mkdir(u'mu-\xb5')
 
782
        os.chdir(u'mu-\xb5')
 
783
        # TODO: jam 20060427 This will probably fail on Mac OSX because
 
784
        #       it will change the normalization of B\xe5gfors
 
785
        #       Consider using a different unicode character, or make
 
786
        #       osutils.getcwd() renormalize the path.
 
787
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
 
788
 
 
789
    def test_minimum_path_selection(self):
 
790
        self.assertEqual(set(),
 
791
            osutils.minimum_path_selection([]))
 
792
        self.assertEqual(set(['a']),
 
793
            osutils.minimum_path_selection(['a']))
 
794
        self.assertEqual(set(['a', 'b']),
 
795
            osutils.minimum_path_selection(['a', 'b']))
 
796
        self.assertEqual(set(['a/', 'b']),
 
797
            osutils.minimum_path_selection(['a/', 'b']))
 
798
        self.assertEqual(set(['a/', 'b']),
 
799
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
 
800
        self.assertEqual(set(['a-b', 'a', 'a0b']),
 
801
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
 
802
 
 
803
    def test_mkdtemp(self):
 
804
        tmpdir = osutils._win32_mkdtemp(dir='.')
 
805
        self.assertFalse('\\' in tmpdir)
 
806
 
 
807
    def test_rename(self):
 
808
        a = open('a', 'wb')
 
809
        a.write('foo\n')
 
810
        a.close()
 
811
        b = open('b', 'wb')
 
812
        b.write('baz\n')
 
813
        b.close()
 
814
 
 
815
        osutils._win32_rename('b', 'a')
 
816
        self.failUnlessExists('a')
 
817
        self.failIfExists('b')
 
818
        self.assertFileEqual('baz\n', 'a')
 
819
 
 
820
    def test_rename_missing_file(self):
 
821
        a = open('a', 'wb')
 
822
        a.write('foo\n')
 
823
        a.close()
 
824
 
 
825
        try:
 
826
            osutils._win32_rename('b', 'a')
 
827
        except (IOError, OSError), e:
 
828
            self.assertEqual(errno.ENOENT, e.errno)
 
829
        self.assertFileEqual('foo\n', 'a')
 
830
 
 
831
    def test_rename_missing_dir(self):
 
832
        os.mkdir('a')
 
833
        try:
 
834
            osutils._win32_rename('b', 'a')
 
835
        except (IOError, OSError), e:
 
836
            self.assertEqual(errno.ENOENT, e.errno)
 
837
 
 
838
    def test_rename_current_dir(self):
 
839
        os.mkdir('a')
 
840
        os.chdir('a')
 
841
        # You can't rename the working directory
 
842
        # doing rename non-existant . usually
 
843
        # just raises ENOENT, since non-existant
 
844
        # doesn't exist.
 
845
        try:
 
846
            osutils._win32_rename('b', '.')
 
847
        except (IOError, OSError), e:
 
848
            self.assertEqual(errno.ENOENT, e.errno)
 
849
 
 
850
    def test_splitpath(self):
 
851
        def check(expected, path):
 
852
            self.assertEqual(expected, osutils.splitpath(path))
 
853
 
 
854
        check(['a'], 'a')
 
855
        check(['a', 'b'], 'a/b')
 
856
        check(['a', 'b'], 'a/./b')
 
857
        check(['a', '.b'], 'a/.b')
 
858
        check(['a', '.b'], 'a\\.b')
 
859
 
 
860
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
 
861
 
 
862
 
 
863
class TestMacFuncsDirs(tests.TestCaseInTempDir):
 
864
    """Test mac special functions that require directories."""
 
865
 
 
866
    def test_getcwd(self):
 
867
        self.requireFeature(tests.UnicodeFilenameFeature)
 
868
        os.mkdir(u'B\xe5gfors')
 
869
        os.chdir(u'B\xe5gfors')
 
870
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
871
 
 
872
    def test_getcwd_nonnorm(self):
 
873
        self.requireFeature(tests.UnicodeFilenameFeature)
 
874
        # Test that _mac_getcwd() will normalize this path
 
875
        os.mkdir(u'Ba\u030agfors')
 
876
        os.chdir(u'Ba\u030agfors')
 
877
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
878
 
 
879
 
 
880
class TestChunksToLines(tests.TestCase):
 
881
 
 
882
    def test_smoketest(self):
 
883
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
 
884
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
 
885
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
 
886
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
 
887
 
 
888
    def test_osutils_binding(self):
 
889
        from bzrlib.tests import test__chunks_to_lines
 
890
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
 
891
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
892
        else:
 
893
            from bzrlib._chunks_to_lines_py import chunks_to_lines
 
894
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
 
895
 
 
896
 
 
897
class TestSplitLines(tests.TestCase):
 
898
 
 
899
    def test_split_unicode(self):
 
900
        self.assertEqual([u'foo\n', u'bar\xae'],
 
901
                         osutils.split_lines(u'foo\nbar\xae'))
 
902
        self.assertEqual([u'foo\n', u'bar\xae\n'],
 
903
                         osutils.split_lines(u'foo\nbar\xae\n'))
 
904
 
 
905
    def test_split_with_carriage_returns(self):
 
906
        self.assertEqual(['foo\rbar\n'],
 
907
                         osutils.split_lines('foo\rbar\n'))
 
908
 
 
909
 
 
910
class TestWalkDirs(tests.TestCaseInTempDir):
 
911
 
 
912
    def assertExpectedBlocks(self, expected, result):
 
913
        self.assertEqual(expected,
 
914
                         [(dirinfo, [line[0:3] for line in block])
 
915
                          for dirinfo, block in result])
 
916
 
 
917
    def test_walkdirs(self):
 
918
        tree = [
 
919
            '.bzr',
 
920
            '0file',
 
921
            '1dir/',
 
922
            '1dir/0file',
 
923
            '1dir/1dir/',
 
924
            '2file'
 
925
            ]
 
926
        self.build_tree(tree)
 
927
        expected_dirblocks = [
 
928
                (('', '.'),
 
929
                 [('0file', '0file', 'file'),
 
930
                  ('1dir', '1dir', 'directory'),
 
931
                  ('2file', '2file', 'file'),
 
932
                 ]
 
933
                ),
 
934
                (('1dir', './1dir'),
 
935
                 [('1dir/0file', '0file', 'file'),
 
936
                  ('1dir/1dir', '1dir', 'directory'),
 
937
                 ]
 
938
                ),
 
939
                (('1dir/1dir', './1dir/1dir'),
 
940
                 [
 
941
                 ]
 
942
                ),
 
943
            ]
 
944
        result = []
 
945
        found_bzrdir = False
 
946
        for dirdetail, dirblock in osutils.walkdirs('.'):
 
947
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
948
                # this tests the filtering of selected paths
 
949
                found_bzrdir = True
 
950
                del dirblock[0]
 
951
            result.append((dirdetail, dirblock))
 
952
 
 
953
        self.assertTrue(found_bzrdir)
 
954
        self.assertExpectedBlocks(expected_dirblocks, result)
 
955
        # you can search a subdir only, with a supplied prefix.
 
956
        result = []
 
957
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
958
            result.append(dirblock)
 
959
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
960
 
 
961
    def test_walkdirs_os_error(self):
 
962
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
 
963
        # Pyrex readdir didn't raise useful messages if it had an error
 
964
        # reading the directory
 
965
        if sys.platform == 'win32':
 
966
            raise tests.TestNotApplicable(
 
967
                "readdir IOError not tested on win32")
 
968
        os.mkdir("test-unreadable")
 
969
        os.chmod("test-unreadable", 0000)
 
970
        # must chmod it back so that it can be removed
 
971
        self.addCleanup(os.chmod, "test-unreadable", 0700)
 
972
        # The error is not raised until the generator is actually evaluated.
 
973
        # (It would be ok if it happened earlier but at the moment it
 
974
        # doesn't.)
 
975
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
 
976
        self.assertEquals('./test-unreadable', e.filename)
 
977
        self.assertEquals(errno.EACCES, e.errno)
 
978
        # Ensure the message contains the file name
 
979
        self.assertContainsRe(str(e), "\./test-unreadable")
 
980
 
 
981
    def test__walkdirs_utf8(self):
 
982
        tree = [
 
983
            '.bzr',
 
984
            '0file',
 
985
            '1dir/',
 
986
            '1dir/0file',
 
987
            '1dir/1dir/',
 
988
            '2file'
 
989
            ]
 
990
        self.build_tree(tree)
 
991
        expected_dirblocks = [
 
992
                (('', '.'),
 
993
                 [('0file', '0file', 'file'),
 
994
                  ('1dir', '1dir', 'directory'),
 
995
                  ('2file', '2file', 'file'),
 
996
                 ]
 
997
                ),
 
998
                (('1dir', './1dir'),
 
999
                 [('1dir/0file', '0file', 'file'),
 
1000
                  ('1dir/1dir', '1dir', 'directory'),
 
1001
                 ]
 
1002
                ),
 
1003
                (('1dir/1dir', './1dir/1dir'),
 
1004
                 [
 
1005
                 ]
 
1006
                ),
 
1007
            ]
 
1008
        result = []
 
1009
        found_bzrdir = False
 
1010
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
 
1011
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
1012
                # this tests the filtering of selected paths
 
1013
                found_bzrdir = True
 
1014
                del dirblock[0]
 
1015
            result.append((dirdetail, dirblock))
 
1016
 
 
1017
        self.assertTrue(found_bzrdir)
 
1018
        self.assertExpectedBlocks(expected_dirblocks, result)
 
1019
 
 
1020
        # you can search a subdir only, with a supplied prefix.
 
1021
        result = []
 
1022
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
1023
            result.append(dirblock)
 
1024
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
1025
 
 
1026
    def _filter_out_stat(self, result):
 
1027
        """Filter out the stat value from the walkdirs result"""
 
1028
        for dirdetail, dirblock in result:
 
1029
            new_dirblock = []
 
1030
            for info in dirblock:
 
1031
                # Ignore info[3] which is the stat
 
1032
                new_dirblock.append((info[0], info[1], info[2], info[4]))
 
1033
            dirblock[:] = new_dirblock
 
1034
 
 
1035
    def _save_platform_info(self):
 
1036
        cur_winver = win32utils.winver
 
1037
        cur_fs_enc = osutils._fs_enc
 
1038
        cur_dir_reader = osutils._selected_dir_reader
 
1039
        def restore():
 
1040
            win32utils.winver = cur_winver
 
1041
            osutils._fs_enc = cur_fs_enc
 
1042
            osutils._selected_dir_reader = cur_dir_reader
 
1043
        self.addCleanup(restore)
 
1044
 
 
1045
    def assertDirReaderIs(self, expected):
 
1046
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
 
1047
        # Force it to redetect
 
1048
        osutils._selected_dir_reader = None
 
1049
        # Nothing to list, but should still trigger the selection logic
 
1050
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
 
1051
        self.assertIsInstance(osutils._selected_dir_reader, expected)
 
1052
 
 
1053
    def test_force_walkdirs_utf8_fs_utf8(self):
 
1054
        self.requireFeature(UTF8DirReaderFeature)
 
1055
        self._save_platform_info()
 
1056
        win32utils.winver = None # Avoid the win32 detection code
 
1057
        osutils._fs_enc = 'UTF-8'
 
1058
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1059
 
 
1060
    def test_force_walkdirs_utf8_fs_ascii(self):
 
1061
        self.requireFeature(UTF8DirReaderFeature)
 
1062
        self._save_platform_info()
 
1063
        win32utils.winver = None # Avoid the win32 detection code
 
1064
        osutils._fs_enc = 'US-ASCII'
 
1065
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1066
 
 
1067
    def test_force_walkdirs_utf8_fs_ANSI(self):
 
1068
        self.requireFeature(UTF8DirReaderFeature)
 
1069
        self._save_platform_info()
 
1070
        win32utils.winver = None # Avoid the win32 detection code
 
1071
        osutils._fs_enc = 'ANSI_X3.4-1968'
 
1072
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
1073
 
 
1074
    def test_force_walkdirs_utf8_fs_latin1(self):
 
1075
        self._save_platform_info()
 
1076
        win32utils.winver = None # Avoid the win32 detection code
 
1077
        osutils._fs_enc = 'latin1'
 
1078
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
1079
 
 
1080
    def test_force_walkdirs_utf8_nt(self):
 
1081
        # Disabled because the thunk of the whole walkdirs api is disabled.
 
1082
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1083
        self._save_platform_info()
 
1084
        win32utils.winver = 'Windows NT'
 
1085
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1086
        self.assertDirReaderIs(Win32ReadDir)
 
1087
 
 
1088
    def test_force_walkdirs_utf8_98(self):
 
1089
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1090
        self._save_platform_info()
 
1091
        win32utils.winver = 'Windows 98'
 
1092
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
1093
 
 
1094
    def test_unicode_walkdirs(self):
 
1095
        """Walkdirs should always return unicode paths."""
 
1096
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1097
        name0 = u'0file-\xb6'
 
1098
        name1 = u'1dir-\u062c\u0648'
 
1099
        name2 = u'2file-\u0633'
 
1100
        tree = [
 
1101
            name0,
 
1102
            name1 + '/',
 
1103
            name1 + '/' + name0,
 
1104
            name1 + '/' + name1 + '/',
 
1105
            name2,
 
1106
            ]
 
1107
        self.build_tree(tree)
 
1108
        expected_dirblocks = [
 
1109
                ((u'', u'.'),
 
1110
                 [(name0, name0, 'file', './' + name0),
 
1111
                  (name1, name1, 'directory', './' + name1),
 
1112
                  (name2, name2, 'file', './' + name2),
 
1113
                 ]
 
1114
                ),
 
1115
                ((name1, './' + name1),
 
1116
                 [(name1 + '/' + name0, name0, 'file', './' + name1
 
1117
                                                        + '/' + name0),
 
1118
                  (name1 + '/' + name1, name1, 'directory', './' + name1
 
1119
                                                            + '/' + name1),
 
1120
                 ]
 
1121
                ),
 
1122
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
 
1123
                 [
 
1124
                 ]
 
1125
                ),
 
1126
            ]
 
1127
        result = list(osutils.walkdirs('.'))
 
1128
        self._filter_out_stat(result)
 
1129
        self.assertEqual(expected_dirblocks, result)
 
1130
        result = list(osutils.walkdirs(u'./'+name1, name1))
 
1131
        self._filter_out_stat(result)
 
1132
        self.assertEqual(expected_dirblocks[1:], result)
 
1133
 
 
1134
    def test_unicode__walkdirs_utf8(self):
 
1135
        """Walkdirs_utf8 should always return utf8 paths.
 
1136
 
 
1137
        The abspath portion might be in unicode or utf-8
 
1138
        """
 
1139
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1140
        name0 = u'0file-\xb6'
 
1141
        name1 = u'1dir-\u062c\u0648'
 
1142
        name2 = u'2file-\u0633'
 
1143
        tree = [
 
1144
            name0,
 
1145
            name1 + '/',
 
1146
            name1 + '/' + name0,
 
1147
            name1 + '/' + name1 + '/',
 
1148
            name2,
 
1149
            ]
 
1150
        self.build_tree(tree)
 
1151
        name0 = name0.encode('utf8')
 
1152
        name1 = name1.encode('utf8')
 
1153
        name2 = name2.encode('utf8')
 
1154
 
 
1155
        expected_dirblocks = [
 
1156
                (('', '.'),
 
1157
                 [(name0, name0, 'file', './' + name0),
 
1158
                  (name1, name1, 'directory', './' + name1),
 
1159
                  (name2, name2, 'file', './' + name2),
 
1160
                 ]
 
1161
                ),
 
1162
                ((name1, './' + name1),
 
1163
                 [(name1 + '/' + name0, name0, 'file', './' + name1
 
1164
                                                        + '/' + name0),
 
1165
                  (name1 + '/' + name1, name1, 'directory', './' + name1
 
1166
                                                            + '/' + name1),
 
1167
                 ]
 
1168
                ),
 
1169
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
 
1170
                 [
 
1171
                 ]
 
1172
                ),
 
1173
            ]
 
1174
        result = []
 
1175
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
 
1176
        # all abspaths are Unicode, and encode them back into utf8.
 
1177
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
 
1178
            self.assertIsInstance(dirdetail[0], str)
 
1179
            if isinstance(dirdetail[1], unicode):
 
1180
                dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
 
1181
                dirblock = [list(info) for info in dirblock]
 
1182
                for info in dirblock:
 
1183
                    self.assertIsInstance(info[4], unicode)
 
1184
                    info[4] = info[4].encode('utf8')
 
1185
            new_dirblock = []
 
1186
            for info in dirblock:
 
1187
                self.assertIsInstance(info[0], str)
 
1188
                self.assertIsInstance(info[1], str)
 
1189
                self.assertIsInstance(info[4], str)
 
1190
                # Remove the stat information
 
1191
                new_dirblock.append((info[0], info[1], info[2], info[4]))
 
1192
            result.append((dirdetail, new_dirblock))
 
1193
        self.assertEqual(expected_dirblocks, result)
 
1194
 
 
1195
    def test__walkdirs_utf8_with_unicode_fs(self):
 
1196
        """UnicodeDirReader should be a safe fallback everywhere
 
1197
 
 
1198
        The abspath portion should be in unicode
 
1199
        """
 
1200
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1201
        # Use the unicode reader. TODO: split into driver-and-driven unit
 
1202
        # tests.
 
1203
        self._save_platform_info()
 
1204
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
 
1205
        name0u = u'0file-\xb6'
 
1206
        name1u = u'1dir-\u062c\u0648'
 
1207
        name2u = u'2file-\u0633'
 
1208
        tree = [
 
1209
            name0u,
 
1210
            name1u + '/',
 
1211
            name1u + '/' + name0u,
 
1212
            name1u + '/' + name1u + '/',
 
1213
            name2u,
 
1214
            ]
 
1215
        self.build_tree(tree)
 
1216
        name0 = name0u.encode('utf8')
 
1217
        name1 = name1u.encode('utf8')
 
1218
        name2 = name2u.encode('utf8')
 
1219
 
 
1220
        # All of the abspaths should be in unicode, all of the relative paths
 
1221
        # should be in utf8
 
1222
        expected_dirblocks = [
 
1223
                (('', '.'),
 
1224
                 [(name0, name0, 'file', './' + name0u),
 
1225
                  (name1, name1, 'directory', './' + name1u),
 
1226
                  (name2, name2, 'file', './' + name2u),
 
1227
                 ]
 
1228
                ),
 
1229
                ((name1, './' + name1u),
 
1230
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
1231
                                                        + '/' + name0u),
 
1232
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
1233
                                                            + '/' + name1u),
 
1234
                 ]
 
1235
                ),
 
1236
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
1237
                 [
 
1238
                 ]
 
1239
                ),
 
1240
            ]
 
1241
        result = list(osutils._walkdirs_utf8('.'))
 
1242
        self._filter_out_stat(result)
 
1243
        self.assertEqual(expected_dirblocks, result)
 
1244
 
 
1245
    def test__walkdirs_utf8_win32readdir(self):
 
1246
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1247
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1248
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1249
        self._save_platform_info()
 
1250
        osutils._selected_dir_reader = Win32ReadDir()
 
1251
        name0u = u'0file-\xb6'
 
1252
        name1u = u'1dir-\u062c\u0648'
 
1253
        name2u = u'2file-\u0633'
 
1254
        tree = [
 
1255
            name0u,
 
1256
            name1u + '/',
 
1257
            name1u + '/' + name0u,
 
1258
            name1u + '/' + name1u + '/',
 
1259
            name2u,
 
1260
            ]
 
1261
        self.build_tree(tree)
 
1262
        name0 = name0u.encode('utf8')
 
1263
        name1 = name1u.encode('utf8')
 
1264
        name2 = name2u.encode('utf8')
 
1265
 
 
1266
        # All of the abspaths should be in unicode, all of the relative paths
 
1267
        # should be in utf8
 
1268
        expected_dirblocks = [
 
1269
                (('', '.'),
 
1270
                 [(name0, name0, 'file', './' + name0u),
 
1271
                  (name1, name1, 'directory', './' + name1u),
 
1272
                  (name2, name2, 'file', './' + name2u),
 
1273
                 ]
 
1274
                ),
 
1275
                ((name1, './' + name1u),
 
1276
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
1277
                                                        + '/' + name0u),
 
1278
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
1279
                                                            + '/' + name1u),
 
1280
                 ]
 
1281
                ),
 
1282
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
1283
                 [
 
1284
                 ]
 
1285
                ),
 
1286
            ]
 
1287
        result = list(osutils._walkdirs_utf8(u'.'))
 
1288
        self._filter_out_stat(result)
 
1289
        self.assertEqual(expected_dirblocks, result)
 
1290
 
 
1291
    def assertStatIsCorrect(self, path, win32stat):
 
1292
        os_stat = os.stat(path)
 
1293
        self.assertEqual(os_stat.st_size, win32stat.st_size)
 
1294
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
 
1295
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
 
1296
        self.assertAlmostEqual(os_stat.st_atime, win32stat.st_atime, places=4)
 
1297
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
 
1298
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
 
1299
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
 
1300
 
 
1301
    def test__walkdirs_utf_win32_find_file_stat_file(self):
 
1302
        """make sure our Stat values are valid"""
 
1303
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1304
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1305
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1306
        name0u = u'0file-\xb6'
 
1307
        name0 = name0u.encode('utf8')
 
1308
        self.build_tree([name0u])
 
1309
        # I hate to sleep() here, but I'm trying to make the ctime different
 
1310
        # from the mtime
 
1311
        time.sleep(2)
 
1312
        f = open(name0u, 'ab')
 
1313
        try:
 
1314
            f.write('just a small update')
 
1315
        finally:
 
1316
            f.close()
 
1317
 
 
1318
        result = Win32ReadDir().read_dir('', u'.')
 
1319
        entry = result[0]
 
1320
        self.assertEqual((name0, name0, 'file'), entry[:3])
 
1321
        self.assertEqual(u'./' + name0u, entry[4])
 
1322
        self.assertStatIsCorrect(entry[4], entry[3])
 
1323
        self.assertNotEqual(entry[3].st_mtime, entry[3].st_ctime)
 
1324
 
 
1325
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
 
1326
        """make sure our Stat values are valid"""
 
1327
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1328
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1329
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1330
        name0u = u'0dir-\u062c\u0648'
 
1331
        name0 = name0u.encode('utf8')
 
1332
        self.build_tree([name0u + '/'])
 
1333
 
 
1334
        result = Win32ReadDir().read_dir('', u'.')
 
1335
        entry = result[0]
 
1336
        self.assertEqual((name0, name0, 'directory'), entry[:3])
 
1337
        self.assertEqual(u'./' + name0u, entry[4])
 
1338
        self.assertStatIsCorrect(entry[4], entry[3])
 
1339
 
 
1340
    def assertPathCompare(self, path_less, path_greater):
 
1341
        """check that path_less and path_greater compare correctly."""
 
1342
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
1343
            path_less, path_less))
 
1344
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
1345
            path_greater, path_greater))
 
1346
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
 
1347
            path_less, path_greater))
 
1348
        self.assertEqual(1, osutils.compare_paths_prefix_order(
 
1349
            path_greater, path_less))
 
1350
 
 
1351
    def test_compare_paths_prefix_order(self):
 
1352
        # root before all else
 
1353
        self.assertPathCompare("/", "/a")
 
1354
        # alpha within a dir
 
1355
        self.assertPathCompare("/a", "/b")
 
1356
        self.assertPathCompare("/b", "/z")
 
1357
        # high dirs before lower.
 
1358
        self.assertPathCompare("/z", "/a/a")
 
1359
        # except if the deeper dir should be output first
 
1360
        self.assertPathCompare("/a/b/c", "/d/g")
 
1361
        # lexical betwen dirs of the same height
 
1362
        self.assertPathCompare("/a/z", "/z/z")
 
1363
        self.assertPathCompare("/a/c/z", "/a/d/e")
 
1364
 
 
1365
        # this should also be consistent for no leading / paths
 
1366
        # root before all else
 
1367
        self.assertPathCompare("", "a")
 
1368
        # alpha within a dir
 
1369
        self.assertPathCompare("a", "b")
 
1370
        self.assertPathCompare("b", "z")
 
1371
        # high dirs before lower.
 
1372
        self.assertPathCompare("z", "a/a")
 
1373
        # except if the deeper dir should be output first
 
1374
        self.assertPathCompare("a/b/c", "d/g")
 
1375
        # lexical betwen dirs of the same height
 
1376
        self.assertPathCompare("a/z", "z/z")
 
1377
        self.assertPathCompare("a/c/z", "a/d/e")
 
1378
 
 
1379
    def test_path_prefix_sorting(self):
 
1380
        """Doing a sort on path prefix should match our sample data."""
 
1381
        original_paths = [
 
1382
            'a',
 
1383
            'a/b',
 
1384
            'a/b/c',
 
1385
            'b',
 
1386
            'b/c',
 
1387
            'd',
 
1388
            'd/e',
 
1389
            'd/e/f',
 
1390
            'd/f',
 
1391
            'd/g',
 
1392
            'g',
 
1393
            ]
 
1394
 
 
1395
        dir_sorted_paths = [
 
1396
            'a',
 
1397
            'b',
 
1398
            'd',
 
1399
            'g',
 
1400
            'a/b',
 
1401
            'a/b/c',
 
1402
            'b/c',
 
1403
            'd/e',
 
1404
            'd/f',
 
1405
            'd/g',
 
1406
            'd/e/f',
 
1407
            ]
 
1408
 
 
1409
        self.assertEqual(
 
1410
            dir_sorted_paths,
 
1411
            sorted(original_paths, key=osutils.path_prefix_key))
 
1412
        # using the comparison routine shoudl work too:
 
1413
        self.assertEqual(
 
1414
            dir_sorted_paths,
 
1415
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
 
1416
 
 
1417
 
 
1418
class TestCopyTree(tests.TestCaseInTempDir):
 
1419
 
 
1420
    def test_copy_basic_tree(self):
 
1421
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
1422
        osutils.copy_tree('source', 'target')
 
1423
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
1424
        self.assertEqual(['c'], os.listdir('target/b'))
 
1425
 
 
1426
    def test_copy_tree_target_exists(self):
 
1427
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
 
1428
                         'target/'])
 
1429
        osutils.copy_tree('source', 'target')
 
1430
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
1431
        self.assertEqual(['c'], os.listdir('target/b'))
 
1432
 
 
1433
    def test_copy_tree_symlinks(self):
 
1434
        self.requireFeature(tests.SymlinkFeature)
 
1435
        self.build_tree(['source/'])
 
1436
        os.symlink('a/generic/path', 'source/lnk')
 
1437
        osutils.copy_tree('source', 'target')
 
1438
        self.assertEqual(['lnk'], os.listdir('target'))
 
1439
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
 
1440
 
 
1441
    def test_copy_tree_handlers(self):
 
1442
        processed_files = []
 
1443
        processed_links = []
 
1444
        def file_handler(from_path, to_path):
 
1445
            processed_files.append(('f', from_path, to_path))
 
1446
        def dir_handler(from_path, to_path):
 
1447
            processed_files.append(('d', from_path, to_path))
 
1448
        def link_handler(from_path, to_path):
 
1449
            processed_links.append((from_path, to_path))
 
1450
        handlers = {'file':file_handler,
 
1451
                    'directory':dir_handler,
 
1452
                    'symlink':link_handler,
 
1453
                   }
 
1454
 
 
1455
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
1456
        if osutils.has_symlinks():
 
1457
            os.symlink('a/generic/path', 'source/lnk')
 
1458
        osutils.copy_tree('source', 'target', handlers=handlers)
 
1459
 
 
1460
        self.assertEqual([('d', 'source', 'target'),
 
1461
                          ('f', 'source/a', 'target/a'),
 
1462
                          ('d', 'source/b', 'target/b'),
 
1463
                          ('f', 'source/b/c', 'target/b/c'),
 
1464
                         ], processed_files)
 
1465
        self.failIfExists('target')
 
1466
        if osutils.has_symlinks():
 
1467
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
 
1468
 
 
1469
 
 
1470
class TestSetUnsetEnv(tests.TestCase):
 
1471
    """Test updating the environment"""
 
1472
 
 
1473
    def setUp(self):
 
1474
        super(TestSetUnsetEnv, self).setUp()
 
1475
 
 
1476
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
 
1477
                         'Environment was not cleaned up properly.'
 
1478
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
 
1479
        def cleanup():
 
1480
            if 'BZR_TEST_ENV_VAR' in os.environ:
 
1481
                del os.environ['BZR_TEST_ENV_VAR']
 
1482
 
 
1483
        self.addCleanup(cleanup)
 
1484
 
 
1485
    def test_set(self):
 
1486
        """Test that we can set an env variable"""
 
1487
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1488
        self.assertEqual(None, old)
 
1489
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
 
1490
 
 
1491
    def test_double_set(self):
 
1492
        """Test that we get the old value out"""
 
1493
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1494
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
 
1495
        self.assertEqual('foo', old)
 
1496
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
 
1497
 
 
1498
    def test_unicode(self):
 
1499
        """Environment can only contain plain strings
 
1500
 
 
1501
        So Unicode strings must be encoded.
 
1502
        """
 
1503
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
1504
        if uni_val is None:
 
1505
            raise tests.TestSkipped(
 
1506
                'Cannot find a unicode character that works in encoding %s'
 
1507
                % (osutils.get_user_encoding(),))
 
1508
 
 
1509
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
 
1510
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
 
1511
 
 
1512
    def test_unset(self):
 
1513
        """Test that passing None will remove the env var"""
 
1514
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
1515
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
 
1516
        self.assertEqual('foo', old)
 
1517
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
 
1518
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1519
 
 
1520
 
 
1521
class TestSizeShaFile(tests.TestCaseInTempDir):
 
1522
 
 
1523
    def test_sha_empty(self):
 
1524
        self.build_tree_contents([('foo', '')])
 
1525
        expected_sha = osutils.sha_string('')
 
1526
        f = open('foo')
 
1527
        self.addCleanup(f.close)
 
1528
        size, sha = osutils.size_sha_file(f)
 
1529
        self.assertEqual(0, size)
 
1530
        self.assertEqual(expected_sha, sha)
 
1531
 
 
1532
    def test_sha_mixed_endings(self):
 
1533
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1534
        self.build_tree_contents([('foo', text)])
 
1535
        expected_sha = osutils.sha_string(text)
 
1536
        f = open('foo')
 
1537
        self.addCleanup(f.close)
 
1538
        size, sha = osutils.size_sha_file(f)
 
1539
        self.assertEqual(38, size)
 
1540
        self.assertEqual(expected_sha, sha)
 
1541
 
 
1542
 
 
1543
class TestShaFileByName(tests.TestCaseInTempDir):
 
1544
 
 
1545
    def test_sha_empty(self):
 
1546
        self.build_tree_contents([('foo', '')])
 
1547
        expected_sha = osutils.sha_string('')
 
1548
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1549
 
 
1550
    def test_sha_mixed_endings(self):
 
1551
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1552
        self.build_tree_contents([('foo', text)])
 
1553
        expected_sha = osutils.sha_string(text)
 
1554
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1555
 
 
1556
 
 
1557
class TestResourceLoading(tests.TestCaseInTempDir):
 
1558
 
 
1559
    def test_resource_string(self):
 
1560
        # test resource in bzrlib
 
1561
        text = osutils.resource_string('bzrlib', 'debug.py')
 
1562
        self.assertContainsRe(text, "debug_flags = set()")
 
1563
        # test resource under bzrlib
 
1564
        text = osutils.resource_string('bzrlib.ui', 'text.py')
 
1565
        self.assertContainsRe(text, "class TextUIFactory")
 
1566
        # test unsupported package
 
1567
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
 
1568
            'yyy.xx')
 
1569
        # test unknown resource
 
1570
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
 
1571
 
 
1572
 
 
1573
class TestReCompile(tests.TestCase):
 
1574
 
 
1575
    def test_re_compile_checked(self):
 
1576
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
 
1577
        self.assertTrue(r.match('aaaa'))
 
1578
        self.assertTrue(r.match('aAaA'))
 
1579
 
 
1580
    def test_re_compile_checked_error(self):
 
1581
        # like https://bugs.launchpad.net/bzr/+bug/251352
 
1582
        err = self.assertRaises(
 
1583
            errors.BzrCommandError,
 
1584
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1585
        self.assertEqual(
 
1586
            "Invalid regular expression in test case: '*': "
 
1587
            "nothing to repeat",
 
1588
            str(err))
 
1589
 
 
1590
 
 
1591
class TestDirReader(tests.TestCaseInTempDir):
 
1592
 
 
1593
    # Set by load_tests
 
1594
    _dir_reader_class = None
 
1595
    _native_to_unicode = None
 
1596
 
 
1597
    def setUp(self):
 
1598
        tests.TestCaseInTempDir.setUp(self)
 
1599
 
 
1600
        # Save platform specific info and reset it
 
1601
        cur_dir_reader = osutils._selected_dir_reader
 
1602
 
 
1603
        def restore():
 
1604
            osutils._selected_dir_reader = cur_dir_reader
 
1605
        self.addCleanup(restore)
 
1606
 
 
1607
        osutils._selected_dir_reader = self._dir_reader_class()
 
1608
 
 
1609
    def _get_ascii_tree(self):
 
1610
        tree = [
 
1611
            '0file',
 
1612
            '1dir/',
 
1613
            '1dir/0file',
 
1614
            '1dir/1dir/',
 
1615
            '2file'
 
1616
            ]
 
1617
        expected_dirblocks = [
 
1618
                (('', '.'),
 
1619
                 [('0file', '0file', 'file'),
 
1620
                  ('1dir', '1dir', 'directory'),
 
1621
                  ('2file', '2file', 'file'),
 
1622
                 ]
 
1623
                ),
 
1624
                (('1dir', './1dir'),
 
1625
                 [('1dir/0file', '0file', 'file'),
 
1626
                  ('1dir/1dir', '1dir', 'directory'),
 
1627
                 ]
 
1628
                ),
 
1629
                (('1dir/1dir', './1dir/1dir'),
 
1630
                 [
 
1631
                 ]
 
1632
                ),
 
1633
            ]
 
1634
        return tree, expected_dirblocks
 
1635
 
 
1636
    def test_walk_cur_dir(self):
 
1637
        tree, expected_dirblocks = self._get_ascii_tree()
 
1638
        self.build_tree(tree)
 
1639
        result = list(osutils._walkdirs_utf8('.'))
 
1640
        # Filter out stat and abspath
 
1641
        self.assertEqual(expected_dirblocks,
 
1642
                         [(dirinfo, [line[0:3] for line in block])
 
1643
                          for dirinfo, block in result])
 
1644
 
 
1645
    def test_walk_sub_dir(self):
 
1646
        tree, expected_dirblocks = self._get_ascii_tree()
 
1647
        self.build_tree(tree)
 
1648
        # you can search a subdir only, with a supplied prefix.
 
1649
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
 
1650
        # Filter out stat and abspath
 
1651
        self.assertEqual(expected_dirblocks[1:],
 
1652
                         [(dirinfo, [line[0:3] for line in block])
 
1653
                          for dirinfo, block in result])
 
1654
 
 
1655
    def _get_unicode_tree(self):
 
1656
        name0u = u'0file-\xb6'
 
1657
        name1u = u'1dir-\u062c\u0648'
 
1658
        name2u = u'2file-\u0633'
 
1659
        tree = [
 
1660
            name0u,
 
1661
            name1u + '/',
 
1662
            name1u + '/' + name0u,
 
1663
            name1u + '/' + name1u + '/',
 
1664
            name2u,
 
1665
            ]
 
1666
        name0 = name0u.encode('UTF-8')
 
1667
        name1 = name1u.encode('UTF-8')
 
1668
        name2 = name2u.encode('UTF-8')
 
1669
        expected_dirblocks = [
 
1670
                (('', '.'),
 
1671
                 [(name0, name0, 'file', './' + name0u),
 
1672
                  (name1, name1, 'directory', './' + name1u),
 
1673
                  (name2, name2, 'file', './' + name2u),
 
1674
                 ]
 
1675
                ),
 
1676
                ((name1, './' + name1u),
 
1677
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
1678
                                                        + '/' + name0u),
 
1679
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
1680
                                                            + '/' + name1u),
 
1681
                 ]
 
1682
                ),
 
1683
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
1684
                 [
 
1685
                 ]
 
1686
                ),
 
1687
            ]
 
1688
        return tree, expected_dirblocks
 
1689
 
 
1690
    def _filter_out(self, raw_dirblocks):
 
1691
        """Filter out a walkdirs_utf8 result.
 
1692
 
 
1693
        stat field is removed, all native paths are converted to unicode
 
1694
        """
 
1695
        filtered_dirblocks = []
 
1696
        for dirinfo, block in raw_dirblocks:
 
1697
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
 
1698
            details = []
 
1699
            for line in block:
 
1700
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
 
1701
            filtered_dirblocks.append((dirinfo, details))
 
1702
        return filtered_dirblocks
 
1703
 
 
1704
    def test_walk_unicode_tree(self):
 
1705
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1706
        tree, expected_dirblocks = self._get_unicode_tree()
 
1707
        self.build_tree(tree)
 
1708
        result = list(osutils._walkdirs_utf8('.'))
 
1709
        self.assertEqual(expected_dirblocks, self._filter_out(result))
 
1710
 
 
1711
    def test_symlink(self):
 
1712
        self.requireFeature(tests.SymlinkFeature)
 
1713
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1714
        target = u'target\N{Euro Sign}'
 
1715
        link_name = u'l\N{Euro Sign}nk'
 
1716
        os.symlink(target, link_name)
 
1717
        target_utf8 = target.encode('UTF-8')
 
1718
        link_name_utf8 = link_name.encode('UTF-8')
 
1719
        expected_dirblocks = [
 
1720
                (('', '.'),
 
1721
                 [(link_name_utf8, link_name_utf8,
 
1722
                   'symlink', './' + link_name),],
 
1723
                 )]
 
1724
        result = list(osutils._walkdirs_utf8('.'))
 
1725
        self.assertEqual(expected_dirblocks, self._filter_out(result))
 
1726
 
 
1727
 
 
1728
class TestReadLink(tests.TestCaseInTempDir):
 
1729
    """Exposes os.readlink() problems and the osutils solution.
 
1730
 
 
1731
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
 
1732
    unicode string will be returned if a unicode string is passed.
 
1733
 
 
1734
    But prior python versions failed to properly encode the passed unicode
 
1735
    string.
 
1736
    """
 
1737
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
 
1738
 
 
1739
    def setUp(self):
 
1740
        super(tests.TestCaseInTempDir, self).setUp()
 
1741
        self.link = u'l\N{Euro Sign}ink'
 
1742
        self.target = u'targe\N{Euro Sign}t'
 
1743
        os.symlink(self.target, self.link)
 
1744
 
 
1745
    def test_os_readlink_link_encoding(self):
 
1746
        if sys.version_info < (2, 6):
 
1747
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
 
1748
        else:
 
1749
            self.assertEquals(self.target,  os.readlink(self.link))
 
1750
 
 
1751
    def test_os_readlink_link_decoding(self):
 
1752
        self.assertEquals(self.target.encode(osutils._fs_enc),
 
1753
                          os.readlink(self.link.encode(osutils._fs_enc)))