/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: John Arbash Meinel
  • Date: 2009-04-29 17:02:36 UTC
  • mto: This revision was merged to the branch mainline in revision 4322.
  • Revision ID: john@arbash-meinel.com-20090429170236-v1oe7b235mi73cqs
Add a per-implementation test that deleting lines conflicts with modifying lines.

At the moment, I don't see a simple way to implement this for LCA merge,
so I'm just marking it as 'expectedFailure'.
However, it works for both Weave merge and for Merge3.
Fixes bug #328171

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