~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

Initial commit for russian version of documents.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
19
19
from cStringIO import StringIO
20
20
import errno
21
21
import os
22
 
import re
23
22
import socket
24
23
import stat
25
24
import sys
26
25
import time
27
26
 
 
27
import bzrlib
28
28
from bzrlib import (
29
29
    errors,
30
30
    osutils,
31
31
    tests,
32
32
    win32utils,
33
33
    )
 
34
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
35
from bzrlib.osutils import (
 
36
        is_inside_any,
 
37
        is_inside_or_parent_of_any,
 
38
        pathjoin,
 
39
        pumpfile,
 
40
        )
34
41
from bzrlib.tests import (
35
 
    file_utils,
36
 
    test__walkdirs_win32,
 
42
        probe_unicode_in_user_encoding,
 
43
        StringIOWrapper,
 
44
        SymlinkFeature,
 
45
        TestCase,
 
46
        TestCaseInTempDir,
 
47
        TestSkipped,
 
48
        )
 
49
from bzrlib.tests.file_utils import (
 
50
    FakeReadFile,
37
51
    )
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):
 
52
from bzrlib.tests.test__walkdirs_win32 import WalkdirsWin32Feature
 
53
 
 
54
 
 
55
class TestOSUtils(TestCaseInTempDir):
110
56
 
111
57
    def test_contains_whitespace(self):
112
58
        self.failUnless(osutils.contains_whitespace(u' '))
122
68
        self.failIf(osutils.contains_whitespace(u'hellothere'))
123
69
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
124
70
 
125
 
 
126
 
class TestRename(tests.TestCaseInTempDir):
127
 
 
128
71
    def test_fancy_rename(self):
129
72
        # This should work everywhere
130
73
        def rename(a, b):
168
111
        shape = sorted(os.listdir('.'))
169
112
        self.assertEquals(['A', 'B'], shape)
170
113
 
171
 
 
172
 
class TestRandChars(tests.TestCase):
173
 
 
174
114
    def test_01_rand_chars_empty(self):
175
115
        result = osutils.rand_chars(0)
176
116
        self.assertEqual(result, '')
181
121
        self.assertEqual(type(result), str)
182
122
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
183
123
 
184
 
 
185
 
class TestIsInside(tests.TestCase):
186
 
 
187
124
    def test_is_inside(self):
188
125
        is_inside = osutils.is_inside
189
126
        self.assertTrue(is_inside('src', 'src/foo.c'))
194
131
        self.assertTrue(is_inside('', 'foo.c'))
195
132
 
196
133
    def test_is_inside_any(self):
197
 
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
134
        SRC_FOO_C = pathjoin('src', 'foo.c')
198
135
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
199
136
                         (['src'], SRC_FOO_C),
200
137
                         (['src'], 'src'),
201
138
                         ]:
202
 
            self.assert_(osutils.is_inside_any(dirs, fn))
 
139
            self.assert_(is_inside_any(dirs, fn))
203
140
        for dirs, fn in [(['src'], 'srccontrol'),
204
141
                         (['src'], 'srccontrol/foo')]:
205
 
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
142
            self.assertFalse(is_inside_any(dirs, fn))
206
143
 
207
144
    def test_is_inside_or_parent_of_any(self):
208
145
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
211
148
                         (['src/bar.c', 'bla/foo.c'], 'src'),
212
149
                         (['src'], 'src'),
213
150
                         ]:
214
 
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
215
 
 
 
151
            self.assert_(is_inside_or_parent_of_any(dirs, fn))
 
152
            
216
153
        for dirs, fn in [(['src'], 'srccontrol'),
217
154
                         (['srccontrol/foo.c'], 'src'),
218
155
                         (['src'], 'srccontrol/foo')]:
219
 
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
220
 
 
221
 
 
222
 
class TestRmTree(tests.TestCaseInTempDir):
 
156
            self.assertFalse(is_inside_or_parent_of_any(dirs, fn))
223
157
 
224
158
    def test_rmtree(self):
225
159
        # Check to remove tree with read-only files/dirs
239
173
        self.failIfExists('dir/file')
240
174
        self.failIfExists('dir')
241
175
 
242
 
 
243
 
class TestDeleteAny(tests.TestCaseInTempDir):
244
 
 
245
 
    def test_delete_any_readonly(self):
246
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
247
 
        self.build_tree(['d/', 'f'])
248
 
        osutils.make_readonly('d')
249
 
        osutils.make_readonly('f')
250
 
 
251
 
        osutils.delete_any('f')
252
 
        osutils.delete_any('d')
253
 
 
254
 
 
255
 
class TestKind(tests.TestCaseInTempDir):
256
 
 
257
176
    def test_file_kind(self):
258
177
        self.build_tree(['file', 'dir/'])
259
178
        self.assertEquals('file', osutils.file_kind('file'))
261
180
        if osutils.has_symlinks():
262
181
            os.symlink('symlink', 'symlink')
263
182
            self.assertEquals('symlink', osutils.file_kind('symlink'))
264
 
 
 
183
        
265
184
        # TODO: jam 20060529 Test a block device
266
185
        try:
267
186
            os.lstat('/dev/null')
289
208
                os.remove('socket')
290
209
 
291
210
    def test_kind_marker(self):
292
 
        self.assertEqual("", osutils.kind_marker("file"))
293
 
        self.assertEqual("/", osutils.kind_marker('directory'))
294
 
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
295
 
        self.assertEqual("@", osutils.kind_marker("symlink"))
296
 
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
297
 
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
298
 
 
299
 
 
300
 
class TestUmask(tests.TestCaseInTempDir):
 
211
        self.assertEqual(osutils.kind_marker('file'), '')
 
212
        self.assertEqual(osutils.kind_marker('directory'), '/')
 
213
        self.assertEqual(osutils.kind_marker('symlink'), '@')
 
214
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
301
215
 
302
216
    def test_get_umask(self):
303
217
        if sys.platform == 'win32':
306
220
            return
307
221
 
308
222
        orig_umask = osutils.get_umask()
309
 
        self.addCleanup(os.umask, orig_umask)
310
 
        os.umask(0222)
311
 
        self.assertEqual(0222, osutils.get_umask())
312
 
        os.umask(0022)
313
 
        self.assertEqual(0022, osutils.get_umask())
314
 
        os.umask(0002)
315
 
        self.assertEqual(0002, osutils.get_umask())
316
 
        os.umask(0027)
317
 
        self.assertEqual(0027, osutils.get_umask())
318
 
 
319
 
 
320
 
class TestDateTime(tests.TestCase):
 
223
        try:
 
224
            os.umask(0222)
 
225
            self.assertEqual(0222, osutils.get_umask())
 
226
            os.umask(0022)
 
227
            self.assertEqual(0022, osutils.get_umask())
 
228
            os.umask(0002)
 
229
            self.assertEqual(0002, osutils.get_umask())
 
230
            os.umask(0027)
 
231
            self.assertEqual(0027, osutils.get_umask())
 
232
        finally:
 
233
            os.umask(orig_umask)
321
234
 
322
235
    def assertFormatedDelta(self, expected, seconds):
323
236
        """Assert osutils.format_delta formats as expected"""
358
271
    def test_format_date(self):
359
272
        self.assertRaises(errors.UnsupportedTimezoneFormat,
360
273
            osutils.format_date, 0, timezone='foo')
361
 
        self.assertIsInstance(osutils.format_date(0), str)
362
 
        self.assertIsInstance(osutils.format_local_date(0), unicode)
363
 
        # Testing for the actual value of the local weekday without
364
 
        # duplicating the code from format_date is difficult.
365
 
        # Instead blackbox.test_locale should check for localized
366
 
        # dates once they do occur in output strings.
367
 
 
368
 
    def test_local_time_offset(self):
369
 
        """Test that local_time_offset() returns a sane value."""
370
 
        offset = osutils.local_time_offset()
371
 
        self.assertTrue(isinstance(offset, int))
372
 
        # Test that the offset is no more than a eighteen hours in
373
 
        # either direction.
374
 
        # Time zone handling is system specific, so it is difficult to
375
 
        # do more specific tests, but a value outside of this range is
376
 
        # probably wrong.
377
 
        eighteen_hours = 18 * 3600
378
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
379
 
 
380
 
    def test_local_time_offset_with_timestamp(self):
381
 
        """Test that local_time_offset() works with a timestamp."""
382
 
        offset = osutils.local_time_offset(1000000000.1234567)
383
 
        self.assertTrue(isinstance(offset, int))
384
 
        eighteen_hours = 18 * 3600
385
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
386
 
 
387
 
 
388
 
class TestLinks(tests.TestCaseInTempDir):
389
274
 
390
275
    def test_dereference_path(self):
391
 
        self.requireFeature(tests.SymlinkFeature)
 
276
        self.requireFeature(SymlinkFeature)
392
277
        cwd = osutils.realpath('.')
393
278
        os.mkdir('bar')
394
279
        bar_path = osutils.pathjoin(cwd, 'bar')
397
282
        self.assertEqual(bar_path, osutils.realpath('./bar'))
398
283
        os.symlink('bar', 'foo')
399
284
        self.assertEqual(bar_path, osutils.realpath('./foo'))
400
 
 
 
285
        
401
286
        # Does not dereference terminal symlinks
402
287
        foo_path = osutils.pathjoin(cwd, 'foo')
403
288
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
435
320
            osutils.make_readonly('dangling')
436
321
            osutils.make_writable('dangling')
437
322
 
 
323
    def test_kind_marker(self):
 
324
        self.assertEqual("", osutils.kind_marker("file"))
 
325
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
 
326
        self.assertEqual("@", osutils.kind_marker("symlink"))
 
327
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
328
 
438
329
    def test_host_os_dereferences_symlinks(self):
439
330
        osutils.host_os_dereferences_symlinks()
440
331
 
441
332
 
442
 
class TestCanonicalRelPath(tests.TestCaseInTempDir):
443
 
 
444
 
    _test_needs_features = [tests.CaseInsCasePresFilenameFeature]
445
 
 
446
 
    def test_canonical_relpath_simple(self):
447
 
        f = file('MixedCaseName', 'w')
448
 
        f.close()
449
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
450
 
        real_base_dir = osutils.realpath(self.test_base_dir)
451
 
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
452
 
        self.failUnlessEqual('work/MixedCaseName', actual)
453
 
 
454
 
    def test_canonical_relpath_missing_tail(self):
455
 
        os.mkdir('MixedCaseParent')
456
 
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
457
 
        real_base_dir = osutils.realpath(self.test_base_dir)
458
 
        actual = osutils.canonical_relpath(real_base_dir,
459
 
                                           'mixedcaseparent/nochild')
460
 
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
461
 
 
462
 
 
463
 
class TestPumpFile(tests.TestCase):
 
333
class TestPumpFile(TestCase):
464
334
    """Test pumpfile method."""
465
 
 
466
335
    def setUp(self):
467
 
        tests.TestCase.setUp(self)
468
336
        # create a test datablock
469
337
        self.block_size = 512
470
338
        pattern = '0123456789ABCDEF'
477
345
        # make sure test data is larger than max read size
478
346
        self.assertTrue(self.test_data_len > self.block_size)
479
347
 
480
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
348
        from_file = FakeReadFile(self.test_data)
481
349
        to_file = StringIO()
482
350
 
483
351
        # read (max / 2) bytes and verify read size wasn't affected
484
352
        num_bytes_to_read = self.block_size / 2
485
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
353
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
486
354
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
487
355
        self.assertEqual(from_file.get_read_count(), 1)
488
356
 
489
357
        # read (max) bytes and verify read size wasn't affected
490
358
        num_bytes_to_read = self.block_size
491
359
        from_file.reset_read_count()
492
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
360
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
493
361
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
494
362
        self.assertEqual(from_file.get_read_count(), 1)
495
363
 
496
364
        # read (max + 1) bytes and verify read size was limited
497
365
        num_bytes_to_read = self.block_size + 1
498
366
        from_file.reset_read_count()
499
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
367
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
500
368
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
501
369
        self.assertEqual(from_file.get_read_count(), 2)
502
370
 
503
371
        # finish reading the rest of the data
504
372
        num_bytes_to_read = self.test_data_len - to_file.tell()
505
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
373
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
506
374
 
507
375
        # report error if the data wasn't equal (we only report the size due
508
376
        # to the length of the data)
518
386
        self.assertTrue(self.test_data_len > self.block_size)
519
387
 
520
388
        # retrieve data in blocks
521
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
389
        from_file = FakeReadFile(self.test_data)
522
390
        to_file = StringIO()
523
 
        osutils.pumpfile(from_file, to_file, self.test_data_len,
524
 
                         self.block_size)
 
391
        pumpfile(from_file, to_file, self.test_data_len, self.block_size)
525
392
 
526
393
        # verify read size was equal to the maximum read size
527
394
        self.assertTrue(from_file.get_max_read_size() > 0)
542
409
        self.assertTrue(self.test_data_len > self.block_size)
543
410
 
544
411
        # retrieve data to EOF
545
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
412
        from_file = FakeReadFile(self.test_data)
546
413
        to_file = StringIO()
547
 
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
 
414
        pumpfile(from_file, to_file, -1, self.block_size)
548
415
 
549
416
        # verify read size was equal to the maximum read size
550
417
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
562
429
        test verifies that any existing usages of pumpfile will not be broken
563
430
        with this new version."""
564
431
        # retrieve data using default (old) pumpfile method
565
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
432
        from_file = FakeReadFile(self.test_data)
566
433
        to_file = StringIO()
567
 
        osutils.pumpfile(from_file, to_file)
 
434
        pumpfile(from_file, to_file)
568
435
 
569
436
        # report error if the data wasn't equal (we only report the size due
570
437
        # to the length of the data)
573
440
            message = "Data not equal.  Expected %d bytes, received %d."
574
441
            self.fail(message % (len(response_data), self.test_data_len))
575
442
 
576
 
    def test_report_activity(self):
577
 
        activity = []
578
 
        def log_activity(length, direction):
579
 
            activity.append((length, direction))
580
 
        from_file = StringIO(self.test_data)
581
 
        to_file = StringIO()
582
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
583
 
                         report_activity=log_activity, direction='read')
584
 
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
585
 
                          (36, 'read')], activity)
586
 
 
587
 
        from_file = StringIO(self.test_data)
588
 
        to_file = StringIO()
589
 
        del activity[:]
590
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
591
 
                         report_activity=log_activity, direction='write')
592
 
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
593
 
                          (36, 'write')], activity)
594
 
 
595
 
        # And with a limited amount of data
596
 
        from_file = StringIO(self.test_data)
597
 
        to_file = StringIO()
598
 
        del activity[:]
599
 
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
600
 
                         report_activity=log_activity, direction='read')
601
 
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
602
 
 
603
 
 
604
 
 
605
 
class TestPumpStringFile(tests.TestCase):
606
 
 
607
 
    def test_empty(self):
608
 
        output = StringIO()
609
 
        osutils.pump_string_file("", output)
610
 
        self.assertEqual("", output.getvalue())
611
 
 
612
 
    def test_more_than_segment_size(self):
613
 
        output = StringIO()
614
 
        osutils.pump_string_file("123456789", output, 2)
615
 
        self.assertEqual("123456789", output.getvalue())
616
 
 
617
 
    def test_segment_size(self):
618
 
        output = StringIO()
619
 
        osutils.pump_string_file("12", output, 2)
620
 
        self.assertEqual("12", output.getvalue())
621
 
 
622
 
    def test_segment_size_multiple(self):
623
 
        output = StringIO()
624
 
        osutils.pump_string_file("1234", output, 2)
625
 
        self.assertEqual("1234", output.getvalue())
626
 
 
627
 
 
628
 
class TestRelpath(tests.TestCase):
629
 
 
630
 
    def test_simple_relpath(self):
631
 
        cwd = osutils.getcwd()
632
 
        subdir = cwd + '/subdir'
633
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
634
 
 
635
 
    def test_deep_relpath(self):
636
 
        cwd = osutils.getcwd()
637
 
        subdir = cwd + '/sub/subsubdir'
638
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
639
 
 
640
 
    def test_not_relative(self):
641
 
        self.assertRaises(errors.PathNotChild,
642
 
                          osutils.relpath, 'C:/path', 'H:/path')
643
 
        self.assertRaises(errors.PathNotChild,
644
 
                          osutils.relpath, 'C:/', 'H:/path')
645
 
 
646
 
 
647
 
class TestSafeUnicode(tests.TestCase):
 
443
class TestSafeUnicode(TestCase):
648
444
 
649
445
    def test_from_ascii_string(self):
650
446
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
659
455
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
660
456
 
661
457
    def test_bad_utf8_string(self):
662
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
458
        self.assertRaises(BzrBadParameterNotUnicode,
663
459
                          osutils.safe_unicode,
664
460
                          '\xbb\xbb')
665
461
 
666
462
 
667
 
class TestSafeUtf8(tests.TestCase):
 
463
class TestSafeUtf8(TestCase):
668
464
 
669
465
    def test_from_ascii_string(self):
670
466
        f = 'foobar'
680
476
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
681
477
 
682
478
    def test_bad_utf8_string(self):
683
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
479
        self.assertRaises(BzrBadParameterNotUnicode,
684
480
                          osutils.safe_utf8, '\xbb\xbb')
685
481
 
686
482
 
687
 
class TestSafeRevisionId(tests.TestCase):
 
483
class TestSafeRevisionId(TestCase):
688
484
 
689
485
    def test_from_ascii_string(self):
690
486
        # this shouldn't give a warning because it's getting an ascii string
712
508
        self.assertEqual(None, osutils.safe_revision_id(None))
713
509
 
714
510
 
715
 
class TestSafeFileId(tests.TestCase):
 
511
class TestSafeFileId(TestCase):
716
512
 
717
513
    def test_from_ascii_string(self):
718
514
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
738
534
        self.assertEqual(None, osutils.safe_file_id(None))
739
535
 
740
536
 
741
 
class TestWin32Funcs(tests.TestCase):
742
 
    """Test that _win32 versions of os utilities return appropriate paths."""
 
537
class TestWin32Funcs(TestCase):
 
538
    """Test that the _win32 versions of os utilities return appropriate paths."""
743
539
 
744
540
    def test_abspath(self):
745
541
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
752
548
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
753
549
 
754
550
    def test_pathjoin(self):
755
 
        self.assertEqual('path/to/foo',
756
 
                         osutils._win32_pathjoin('path', 'to', 'foo'))
757
 
        self.assertEqual('C:/foo',
758
 
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
759
 
        self.assertEqual('C:/foo',
760
 
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
761
 
        self.assertEqual('path/to/foo',
762
 
                         osutils._win32_pathjoin('path/to/', 'foo'))
763
 
        self.assertEqual('/foo',
764
 
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
765
 
        self.assertEqual('/foo',
766
 
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
551
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
552
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
553
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
554
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
555
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
556
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
767
557
 
768
558
    def test_normpath(self):
769
 
        self.assertEqual('path/to/foo',
770
 
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
771
 
        self.assertEqual('path/to/foo',
772
 
                         osutils._win32_normpath('path//from/../to/./foo'))
 
559
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
560
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
773
561
 
774
562
    def test_getcwd(self):
775
563
        cwd = osutils._win32_getcwd()
804
592
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
805
593
 
806
594
 
807
 
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
 
595
class TestWin32FuncsDirs(TestCaseInTempDir):
808
596
    """Test win32 functions that create files."""
 
597
    
 
598
    def test_getcwd(self):
 
599
        if win32utils.winver == 'Windows 98':
 
600
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
601
        # Make sure getcwd can handle unicode filenames
 
602
        try:
 
603
            os.mkdir(u'mu-\xb5')
 
604
        except UnicodeError:
 
605
            raise TestSkipped("Unable to create Unicode filename")
809
606
 
810
 
    def test_getcwd(self):
811
 
        self.requireFeature(tests.UnicodeFilenameFeature)
812
 
        os.mkdir(u'mu-\xb5')
813
607
        os.chdir(u'mu-\xb5')
814
608
        # TODO: jam 20060427 This will probably fail on Mac OSX because
815
609
        #       it will change the normalization of B\xe5gfors
820
614
    def test_minimum_path_selection(self):
821
615
        self.assertEqual(set(),
822
616
            osutils.minimum_path_selection([]))
823
 
        self.assertEqual(set(['a']),
824
 
            osutils.minimum_path_selection(['a']))
825
617
        self.assertEqual(set(['a', 'b']),
826
618
            osutils.minimum_path_selection(['a', 'b']))
827
619
        self.assertEqual(set(['a/', 'b']),
828
620
            osutils.minimum_path_selection(['a/', 'b']))
829
621
        self.assertEqual(set(['a/', 'b']),
830
622
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
831
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
832
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
833
623
 
834
624
    def test_mkdtemp(self):
835
625
        tmpdir = osutils._win32_mkdtemp(dir='.')
891
681
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
892
682
 
893
683
 
894
 
class TestParentDirectories(tests.TestCaseInTempDir):
895
 
    """Test osutils.parent_directories()"""
896
 
 
897
 
    def test_parent_directories(self):
898
 
        self.assertEqual([], osutils.parent_directories('a'))
899
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
900
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
901
 
 
902
 
 
903
 
class TestMacFuncsDirs(tests.TestCaseInTempDir):
 
684
class TestMacFuncsDirs(TestCaseInTempDir):
904
685
    """Test mac special functions that require directories."""
905
686
 
906
687
    def test_getcwd(self):
907
 
        self.requireFeature(tests.UnicodeFilenameFeature)
908
 
        os.mkdir(u'B\xe5gfors')
 
688
        # On Mac, this will actually create Ba\u030agfors
 
689
        # but chdir will still work, because it accepts both paths
 
690
        try:
 
691
            os.mkdir(u'B\xe5gfors')
 
692
        except UnicodeError:
 
693
            raise TestSkipped("Unable to create Unicode filename")
 
694
 
909
695
        os.chdir(u'B\xe5gfors')
910
696
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
911
697
 
912
698
    def test_getcwd_nonnorm(self):
913
 
        self.requireFeature(tests.UnicodeFilenameFeature)
914
699
        # Test that _mac_getcwd() will normalize this path
915
 
        os.mkdir(u'Ba\u030agfors')
 
700
        try:
 
701
            os.mkdir(u'Ba\u030agfors')
 
702
        except UnicodeError:
 
703
            raise TestSkipped("Unable to create Unicode filename")
 
704
 
916
705
        os.chdir(u'Ba\u030agfors')
917
706
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
918
707
 
919
708
 
920
 
class TestChunksToLines(tests.TestCase):
921
 
 
922
 
    def test_smoketest(self):
923
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
924
 
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
925
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
926
 
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
927
 
 
928
 
    def test_osutils_binding(self):
929
 
        from bzrlib.tests import test__chunks_to_lines
930
 
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
931
 
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
932
 
        else:
933
 
            from bzrlib._chunks_to_lines_py import chunks_to_lines
934
 
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
935
 
 
936
 
 
937
 
class TestSplitLines(tests.TestCase):
 
709
class TestSplitLines(TestCase):
938
710
 
939
711
    def test_split_unicode(self):
940
712
        self.assertEqual([u'foo\n', u'bar\xae'],
947
719
                         osutils.split_lines('foo\rbar\n'))
948
720
 
949
721
 
950
 
class TestWalkDirs(tests.TestCaseInTempDir):
951
 
 
952
 
    def assertExpectedBlocks(self, expected, result):
953
 
        self.assertEqual(expected,
954
 
                         [(dirinfo, [line[0:3] for line in block])
955
 
                          for dirinfo, block in result])
 
722
class TestWalkDirs(TestCaseInTempDir):
956
723
 
957
724
    def test_walkdirs(self):
958
725
        tree = [
991
758
            result.append((dirdetail, dirblock))
992
759
 
993
760
        self.assertTrue(found_bzrdir)
994
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
761
        self.assertEqual(expected_dirblocks,
 
762
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
995
763
        # you can search a subdir only, with a supplied prefix.
996
764
        result = []
997
765
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
998
766
            result.append(dirblock)
999
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1000
 
 
1001
 
    def test_walkdirs_os_error(self):
1002
 
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1003
 
        # Pyrex readdir didn't raise useful messages if it had an error
1004
 
        # reading the directory
1005
 
        if sys.platform == 'win32':
1006
 
            raise tests.TestNotApplicable(
1007
 
                "readdir IOError not tested on win32")
1008
 
        os.mkdir("test-unreadable")
1009
 
        os.chmod("test-unreadable", 0000)
1010
 
        # must chmod it back so that it can be removed
1011
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
1012
 
        # The error is not raised until the generator is actually evaluated.
1013
 
        # (It would be ok if it happened earlier but at the moment it
1014
 
        # doesn't.)
1015
 
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1016
 
        self.assertEquals('./test-unreadable', e.filename)
1017
 
        self.assertEquals(errno.EACCES, e.errno)
1018
 
        # Ensure the message contains the file name
1019
 
        self.assertContainsRe(str(e), "\./test-unreadable")
 
767
        self.assertEqual(expected_dirblocks[1:],
 
768
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1020
769
 
1021
770
    def test__walkdirs_utf8(self):
1022
771
        tree = [
1055
804
            result.append((dirdetail, dirblock))
1056
805
 
1057
806
        self.assertTrue(found_bzrdir)
1058
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1059
 
 
 
807
        self.assertEqual(expected_dirblocks,
 
808
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1060
809
        # you can search a subdir only, with a supplied prefix.
1061
810
        result = []
1062
811
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1063
812
            result.append(dirblock)
1064
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
813
        self.assertEqual(expected_dirblocks[1:],
 
814
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1065
815
 
1066
816
    def _filter_out_stat(self, result):
1067
817
        """Filter out the stat value from the walkdirs result"""
1072
822
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1073
823
            dirblock[:] = new_dirblock
1074
824
 
 
825
    def test__walkdirs_utf8_selection(self):
 
826
        # Just trigger the function once, to make sure it has selected a real
 
827
        # implementation.
 
828
        list(osutils._walkdirs_utf8('.'))
 
829
        if WalkdirsWin32Feature.available():
 
830
            # If the compiled form is available, make sure it is used
 
831
            from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
832
            self.assertIs(_walkdirs_utf8_win32_find_file,
 
833
                          osutils._real_walkdirs_utf8)
 
834
        elif sys.platform == 'win32':
 
835
            self.assertIs(osutils._walkdirs_unicode_to_utf8,
 
836
                          osutils._real_walkdirs_utf8)
 
837
        elif osutils._fs_enc.upper() in ('UTF-8', 'ASCII', 'ANSI_X3.4-1968'): # ascii
 
838
            self.assertIs(osutils._walkdirs_fs_utf8,
 
839
                          osutils._real_walkdirs_utf8)
 
840
        else:
 
841
            self.assertIs(osutils._walkdirs_unicode_to_utf8,
 
842
                          osutils._real_walkdirs_utf8)
 
843
 
1075
844
    def _save_platform_info(self):
1076
845
        cur_winver = win32utils.winver
1077
846
        cur_fs_enc = osutils._fs_enc
1078
 
        cur_dir_reader = osutils._selected_dir_reader
 
847
        cur_real_walkdirs_utf8 = osutils._real_walkdirs_utf8
1079
848
        def restore():
1080
849
            win32utils.winver = cur_winver
1081
850
            osutils._fs_enc = cur_fs_enc
1082
 
            osutils._selected_dir_reader = cur_dir_reader
 
851
            osutils._real_walkdirs_utf8 = cur_real_walkdirs_utf8
1083
852
        self.addCleanup(restore)
1084
853
 
1085
 
    def assertDirReaderIs(self, expected):
 
854
    def assertWalkdirsUtf8Is(self, expected):
1086
855
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1087
856
        # Force it to redetect
1088
 
        osutils._selected_dir_reader = None
 
857
        osutils._real_walkdirs_utf8 = None
1089
858
        # Nothing to list, but should still trigger the selection logic
1090
859
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1091
 
        self.assertIsInstance(osutils._selected_dir_reader, expected)
 
860
        self.assertIs(expected, osutils._real_walkdirs_utf8)
1092
861
 
1093
862
    def test_force_walkdirs_utf8_fs_utf8(self):
1094
 
        self.requireFeature(UTF8DirReaderFeature)
1095
863
        self._save_platform_info()
1096
864
        win32utils.winver = None # Avoid the win32 detection code
1097
865
        osutils._fs_enc = 'UTF-8'
1098
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
866
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1099
867
 
1100
868
    def test_force_walkdirs_utf8_fs_ascii(self):
1101
 
        self.requireFeature(UTF8DirReaderFeature)
1102
869
        self._save_platform_info()
1103
870
        win32utils.winver = None # Avoid the win32 detection code
1104
871
        osutils._fs_enc = 'US-ASCII'
1105
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
872
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1106
873
 
1107
874
    def test_force_walkdirs_utf8_fs_ANSI(self):
1108
 
        self.requireFeature(UTF8DirReaderFeature)
1109
875
        self._save_platform_info()
1110
876
        win32utils.winver = None # Avoid the win32 detection code
1111
877
        osutils._fs_enc = 'ANSI_X3.4-1968'
1112
 
        self.assertDirReaderIs(UTF8DirReaderFeature.reader)
 
878
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1113
879
 
1114
880
    def test_force_walkdirs_utf8_fs_latin1(self):
1115
881
        self._save_platform_info()
1116
882
        win32utils.winver = None # Avoid the win32 detection code
1117
883
        osutils._fs_enc = 'latin1'
1118
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
884
        self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1119
885
 
1120
886
    def test_force_walkdirs_utf8_nt(self):
1121
 
        # Disabled because the thunk of the whole walkdirs api is disabled.
1122
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
887
        self.requireFeature(WalkdirsWin32Feature)
1123
888
        self._save_platform_info()
1124
889
        win32utils.winver = 'Windows NT'
1125
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1126
 
        self.assertDirReaderIs(Win32ReadDir)
 
890
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
891
        self.assertWalkdirsUtf8Is(_walkdirs_utf8_win32_find_file)
1127
892
 
1128
 
    def test_force_walkdirs_utf8_98(self):
1129
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
893
    def test_force_walkdirs_utf8_nt(self):
 
894
        self.requireFeature(WalkdirsWin32Feature)
1130
895
        self._save_platform_info()
1131
896
        win32utils.winver = 'Windows 98'
1132
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
897
        self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1133
898
 
1134
899
    def test_unicode_walkdirs(self):
1135
900
        """Walkdirs should always return unicode paths."""
1136
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1137
901
        name0 = u'0file-\xb6'
1138
902
        name1 = u'1dir-\u062c\u0648'
1139
903
        name2 = u'2file-\u0633'
1144
908
            name1 + '/' + name1 + '/',
1145
909
            name2,
1146
910
            ]
1147
 
        self.build_tree(tree)
 
911
        try:
 
912
            self.build_tree(tree)
 
913
        except UnicodeError:
 
914
            raise TestSkipped('Could not represent Unicode chars'
 
915
                              ' in current encoding.')
1148
916
        expected_dirblocks = [
1149
917
                ((u'', u'.'),
1150
918
                 [(name0, name0, 'file', './' + name0),
1176
944
 
1177
945
        The abspath portion might be in unicode or utf-8
1178
946
        """
1179
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1180
947
        name0 = u'0file-\xb6'
1181
948
        name1 = u'1dir-\u062c\u0648'
1182
949
        name2 = u'2file-\u0633'
1187
954
            name1 + '/' + name1 + '/',
1188
955
            name2,
1189
956
            ]
1190
 
        self.build_tree(tree)
 
957
        try:
 
958
            self.build_tree(tree)
 
959
        except UnicodeError:
 
960
            raise TestSkipped('Could not represent Unicode chars'
 
961
                              ' in current encoding.')
1191
962
        name0 = name0.encode('utf8')
1192
963
        name1 = name1.encode('utf8')
1193
964
        name2 = name2.encode('utf8')
1232
1003
            result.append((dirdetail, new_dirblock))
1233
1004
        self.assertEqual(expected_dirblocks, result)
1234
1005
 
1235
 
    def test__walkdirs_utf8_with_unicode_fs(self):
1236
 
        """UnicodeDirReader should be a safe fallback everywhere
 
1006
    def test_unicode__walkdirs_unicode_to_utf8(self):
 
1007
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
1237
1008
 
1238
1009
        The abspath portion should be in unicode
1239
1010
        """
1240
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1241
 
        # Use the unicode reader. TODO: split into driver-and-driven unit
1242
 
        # tests.
1243
 
        self._save_platform_info()
1244
 
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
1245
1011
        name0u = u'0file-\xb6'
1246
1012
        name1u = u'1dir-\u062c\u0648'
1247
1013
        name2u = u'2file-\u0633'
1252
1018
            name1u + '/' + name1u + '/',
1253
1019
            name2u,
1254
1020
            ]
1255
 
        self.build_tree(tree)
 
1021
        try:
 
1022
            self.build_tree(tree)
 
1023
        except UnicodeError:
 
1024
            raise TestSkipped('Could not represent Unicode chars'
 
1025
                              ' in current encoding.')
1256
1026
        name0 = name0u.encode('utf8')
1257
1027
        name1 = name1u.encode('utf8')
1258
1028
        name2 = name2u.encode('utf8')
1278
1048
                 ]
1279
1049
                ),
1280
1050
            ]
1281
 
        result = list(osutils._walkdirs_utf8('.'))
 
1051
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
1282
1052
        self._filter_out_stat(result)
1283
1053
        self.assertEqual(expected_dirblocks, result)
1284
1054
 
1285
 
    def test__walkdirs_utf8_win32readdir(self):
1286
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1055
    def test__walkdirs_utf_win32_find_file(self):
 
1056
        self.requireFeature(WalkdirsWin32Feature)
1287
1057
        self.requireFeature(tests.UnicodeFilenameFeature)
1288
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1289
 
        self._save_platform_info()
1290
 
        osutils._selected_dir_reader = Win32ReadDir()
 
1058
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1291
1059
        name0u = u'0file-\xb6'
1292
1060
        name1u = u'1dir-\u062c\u0648'
1293
1061
        name2u = u'2file-\u0633'
1324
1092
                 ]
1325
1093
                ),
1326
1094
            ]
1327
 
        result = list(osutils._walkdirs_utf8(u'.'))
 
1095
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
1328
1096
        self._filter_out_stat(result)
1329
1097
        self.assertEqual(expected_dirblocks, result)
1330
1098
 
1340
1108
 
1341
1109
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1342
1110
        """make sure our Stat values are valid"""
1343
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1111
        self.requireFeature(WalkdirsWin32Feature)
1344
1112
        self.requireFeature(tests.UnicodeFilenameFeature)
1345
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1113
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1346
1114
        name0u = u'0file-\xb6'
1347
1115
        name0 = name0u.encode('utf8')
1348
1116
        self.build_tree([name0u])
1355
1123
        finally:
1356
1124
            f.close()
1357
1125
 
1358
 
        result = Win32ReadDir().read_dir('', u'.')
1359
 
        entry = result[0]
 
1126
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
 
1127
        entry = result[0][1][0]
1360
1128
        self.assertEqual((name0, name0, 'file'), entry[:3])
1361
1129
        self.assertEqual(u'./' + name0u, entry[4])
1362
1130
        self.assertStatIsCorrect(entry[4], entry[3])
1364
1132
 
1365
1133
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1366
1134
        """make sure our Stat values are valid"""
1367
 
        self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
 
1135
        self.requireFeature(WalkdirsWin32Feature)
1368
1136
        self.requireFeature(tests.UnicodeFilenameFeature)
1369
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1137
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1370
1138
        name0u = u'0dir-\u062c\u0648'
1371
1139
        name0 = name0u.encode('utf8')
1372
1140
        self.build_tree([name0u + '/'])
1373
1141
 
1374
 
        result = Win32ReadDir().read_dir('', u'.')
1375
 
        entry = result[0]
 
1142
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
 
1143
        entry = result[0][1][0]
1376
1144
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1377
1145
        self.assertEqual(u'./' + name0u, entry[4])
1378
1146
        self.assertStatIsCorrect(entry[4], entry[3])
1455
1223
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1456
1224
 
1457
1225
 
1458
 
class TestCopyTree(tests.TestCaseInTempDir):
1459
 
 
 
1226
class TestCopyTree(TestCaseInTempDir):
 
1227
    
1460
1228
    def test_copy_basic_tree(self):
1461
1229
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1462
1230
        osutils.copy_tree('source', 'target')
1471
1239
        self.assertEqual(['c'], os.listdir('target/b'))
1472
1240
 
1473
1241
    def test_copy_tree_symlinks(self):
1474
 
        self.requireFeature(tests.SymlinkFeature)
 
1242
        self.requireFeature(SymlinkFeature)
1475
1243
        self.build_tree(['source/'])
1476
1244
        os.symlink('a/generic/path', 'source/lnk')
1477
1245
        osutils.copy_tree('source', 'target')
1507
1275
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1508
1276
 
1509
1277
 
1510
 
class TestSetUnsetEnv(tests.TestCase):
 
1278
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
1279
# [bialix] 2006/12/26
 
1280
 
 
1281
 
 
1282
class TestSetUnsetEnv(TestCase):
1511
1283
    """Test updating the environment"""
1512
1284
 
1513
1285
    def setUp(self):
1537
1309
 
1538
1310
    def test_unicode(self):
1539
1311
        """Environment can only contain plain strings
1540
 
 
 
1312
        
1541
1313
        So Unicode strings must be encoded.
1542
1314
        """
1543
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
1315
        uni_val, env_val = probe_unicode_in_user_encoding()
1544
1316
        if uni_val is None:
1545
 
            raise tests.TestSkipped(
1546
 
                'Cannot find a unicode character that works in encoding %s'
1547
 
                % (osutils.get_user_encoding(),))
 
1317
            raise TestSkipped('Cannot find a unicode character that works in'
 
1318
                              ' encoding %s' % (bzrlib.user_encoding,))
1548
1319
 
1549
1320
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1550
1321
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1558
1329
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1559
1330
 
1560
1331
 
1561
 
class TestSizeShaFile(tests.TestCaseInTempDir):
1562
 
 
1563
 
    def test_sha_empty(self):
1564
 
        self.build_tree_contents([('foo', '')])
1565
 
        expected_sha = osutils.sha_string('')
1566
 
        f = open('foo')
1567
 
        self.addCleanup(f.close)
1568
 
        size, sha = osutils.size_sha_file(f)
1569
 
        self.assertEqual(0, size)
1570
 
        self.assertEqual(expected_sha, sha)
1571
 
 
1572
 
    def test_sha_mixed_endings(self):
1573
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1574
 
        self.build_tree_contents([('foo', text)])
1575
 
        expected_sha = osutils.sha_string(text)
1576
 
        f = open('foo')
1577
 
        self.addCleanup(f.close)
1578
 
        size, sha = osutils.size_sha_file(f)
1579
 
        self.assertEqual(38, size)
1580
 
        self.assertEqual(expected_sha, sha)
1581
 
 
1582
 
 
1583
 
class TestShaFileByName(tests.TestCaseInTempDir):
1584
 
 
1585
 
    def test_sha_empty(self):
1586
 
        self.build_tree_contents([('foo', '')])
1587
 
        expected_sha = osutils.sha_string('')
1588
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1589
 
 
1590
 
    def test_sha_mixed_endings(self):
1591
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1592
 
        self.build_tree_contents([('foo', text)])
1593
 
        expected_sha = osutils.sha_string(text)
1594
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1595
 
 
1596
 
 
1597
 
class TestResourceLoading(tests.TestCaseInTempDir):
 
1332
class TestLocalTimeOffset(TestCase):
 
1333
 
 
1334
    def test_local_time_offset(self):
 
1335
        """Test that local_time_offset() returns a sane value."""
 
1336
        offset = osutils.local_time_offset()
 
1337
        self.assertTrue(isinstance(offset, int))
 
1338
        # Test that the offset is no more than a eighteen hours in
 
1339
        # either direction.
 
1340
        # Time zone handling is system specific, so it is difficult to
 
1341
        # do more specific tests, but a value outside of this range is
 
1342
        # probably wrong.
 
1343
        eighteen_hours = 18 * 3600
 
1344
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1345
 
 
1346
    def test_local_time_offset_with_timestamp(self):
 
1347
        """Test that local_time_offset() works with a timestamp."""
 
1348
        offset = osutils.local_time_offset(1000000000.1234567)
 
1349
        self.assertTrue(isinstance(offset, int))
 
1350
        eighteen_hours = 18 * 3600
 
1351
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1352
 
 
1353
 
 
1354
class TestShaFileByName(TestCaseInTempDir):
 
1355
 
 
1356
    def test_sha_empty(self):
 
1357
        self.build_tree_contents([('foo', '')])
 
1358
        expected_sha = osutils.sha_string('')
 
1359
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1360
 
 
1361
    def test_sha_mixed_endings(self):
 
1362
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1363
        self.build_tree_contents([('foo', text)])
 
1364
        expected_sha = osutils.sha_string(text)
 
1365
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1366
 
 
1367
 
 
1368
_debug_text = \
 
1369
r'''# Copyright (C) 2005, 2006 Canonical Ltd
 
1370
#
 
1371
# This program is free software; you can redistribute it and/or modify
 
1372
# it under the terms of the GNU General Public License as published by
 
1373
# the Free Software Foundation; either version 2 of the License, or
 
1374
# (at your option) any later version.
 
1375
#
 
1376
# This program is distributed in the hope that it will be useful,
 
1377
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
1378
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
1379
# GNU General Public License for more details.
 
1380
#
 
1381
# You should have received a copy of the GNU General Public License
 
1382
# along with this program; if not, write to the Free Software
 
1383
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
1384
 
 
1385
 
 
1386
# NOTE: If update these, please also update the help for global-options in
 
1387
#       bzrlib/help_topics/__init__.py
 
1388
 
 
1389
debug_flags = set()
 
1390
"""Set of flags that enable different debug behaviour.
 
1391
 
 
1392
These are set with eg ``-Dlock`` on the bzr command line.
 
1393
 
 
1394
Options include:
 
1395
 
 
1396
 * auth - show authentication sections used
 
1397
 * error - show stack traces for all top level exceptions
 
1398
 * evil - capture call sites that do expensive or badly-scaling operations.
 
1399
 * fetch - trace history copying between repositories
 
1400
 * graph - trace graph traversal information
 
1401
 * hashcache - log every time a working file is read to determine its hash
 
1402
 * hooks - trace hook execution
 
1403
 * hpss - trace smart protocol requests and responses
 
1404
 * http - trace http connections, requests and responses
 
1405
 * index - trace major index operations
 
1406
 * knit - trace knit operations
 
1407
 * lock - trace when lockdir locks are taken or released
 
1408
 * merge - emit information for debugging merges
 
1409
 * pack - emit information about pack operations
 
1410
 
 
1411
"""
 
1412
'''
 
1413
 
 
1414
 
 
1415
class TestResourceLoading(TestCaseInTempDir):
1598
1416
 
1599
1417
    def test_resource_string(self):
1600
1418
        # test resource in bzrlib
1601
1419
        text = osutils.resource_string('bzrlib', 'debug.py')
1602
 
        self.assertContainsRe(text, "debug_flags = set()")
 
1420
        self.assertEquals(_debug_text, text)
1603
1421
        # test resource under bzrlib
1604
1422
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1605
1423
        self.assertContainsRe(text, "class TextUIFactory")
1608
1426
            'yyy.xx')
1609
1427
        # test unknown resource
1610
1428
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1611
 
 
1612
 
 
1613
 
class TestReCompile(tests.TestCase):
1614
 
 
1615
 
    def test_re_compile_checked(self):
1616
 
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1617
 
        self.assertTrue(r.match('aaaa'))
1618
 
        self.assertTrue(r.match('aAaA'))
1619
 
 
1620
 
    def test_re_compile_checked_error(self):
1621
 
        # like https://bugs.launchpad.net/bzr/+bug/251352
1622
 
        err = self.assertRaises(
1623
 
            errors.BzrCommandError,
1624
 
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1625
 
        self.assertEqual(
1626
 
            "Invalid regular expression in test case: '*': "
1627
 
            "nothing to repeat",
1628
 
            str(err))
1629
 
 
1630
 
 
1631
 
class TestDirReader(tests.TestCaseInTempDir):
1632
 
 
1633
 
    # Set by load_tests
1634
 
    _dir_reader_class = None
1635
 
    _native_to_unicode = None
1636
 
 
1637
 
    def setUp(self):
1638
 
        tests.TestCaseInTempDir.setUp(self)
1639
 
 
1640
 
        # Save platform specific info and reset it
1641
 
        cur_dir_reader = osutils._selected_dir_reader
1642
 
 
1643
 
        def restore():
1644
 
            osutils._selected_dir_reader = cur_dir_reader
1645
 
        self.addCleanup(restore)
1646
 
 
1647
 
        osutils._selected_dir_reader = self._dir_reader_class()
1648
 
 
1649
 
    def _get_ascii_tree(self):
1650
 
        tree = [
1651
 
            '0file',
1652
 
            '1dir/',
1653
 
            '1dir/0file',
1654
 
            '1dir/1dir/',
1655
 
            '2file'
1656
 
            ]
1657
 
        expected_dirblocks = [
1658
 
                (('', '.'),
1659
 
                 [('0file', '0file', 'file'),
1660
 
                  ('1dir', '1dir', 'directory'),
1661
 
                  ('2file', '2file', 'file'),
1662
 
                 ]
1663
 
                ),
1664
 
                (('1dir', './1dir'),
1665
 
                 [('1dir/0file', '0file', 'file'),
1666
 
                  ('1dir/1dir', '1dir', 'directory'),
1667
 
                 ]
1668
 
                ),
1669
 
                (('1dir/1dir', './1dir/1dir'),
1670
 
                 [
1671
 
                 ]
1672
 
                ),
1673
 
            ]
1674
 
        return tree, expected_dirblocks
1675
 
 
1676
 
    def test_walk_cur_dir(self):
1677
 
        tree, expected_dirblocks = self._get_ascii_tree()
1678
 
        self.build_tree(tree)
1679
 
        result = list(osutils._walkdirs_utf8('.'))
1680
 
        # Filter out stat and abspath
1681
 
        self.assertEqual(expected_dirblocks,
1682
 
                         [(dirinfo, [line[0:3] for line in block])
1683
 
                          for dirinfo, block in result])
1684
 
 
1685
 
    def test_walk_sub_dir(self):
1686
 
        tree, expected_dirblocks = self._get_ascii_tree()
1687
 
        self.build_tree(tree)
1688
 
        # you can search a subdir only, with a supplied prefix.
1689
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1690
 
        # Filter out stat and abspath
1691
 
        self.assertEqual(expected_dirblocks[1:],
1692
 
                         [(dirinfo, [line[0:3] for line in block])
1693
 
                          for dirinfo, block in result])
1694
 
 
1695
 
    def _get_unicode_tree(self):
1696
 
        name0u = u'0file-\xb6'
1697
 
        name1u = u'1dir-\u062c\u0648'
1698
 
        name2u = u'2file-\u0633'
1699
 
        tree = [
1700
 
            name0u,
1701
 
            name1u + '/',
1702
 
            name1u + '/' + name0u,
1703
 
            name1u + '/' + name1u + '/',
1704
 
            name2u,
1705
 
            ]
1706
 
        name0 = name0u.encode('UTF-8')
1707
 
        name1 = name1u.encode('UTF-8')
1708
 
        name2 = name2u.encode('UTF-8')
1709
 
        expected_dirblocks = [
1710
 
                (('', '.'),
1711
 
                 [(name0, name0, 'file', './' + name0u),
1712
 
                  (name1, name1, 'directory', './' + name1u),
1713
 
                  (name2, name2, 'file', './' + name2u),
1714
 
                 ]
1715
 
                ),
1716
 
                ((name1, './' + name1u),
1717
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1718
 
                                                        + '/' + name0u),
1719
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1720
 
                                                            + '/' + name1u),
1721
 
                 ]
1722
 
                ),
1723
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1724
 
                 [
1725
 
                 ]
1726
 
                ),
1727
 
            ]
1728
 
        return tree, expected_dirblocks
1729
 
 
1730
 
    def _filter_out(self, raw_dirblocks):
1731
 
        """Filter out a walkdirs_utf8 result.
1732
 
 
1733
 
        stat field is removed, all native paths are converted to unicode
1734
 
        """
1735
 
        filtered_dirblocks = []
1736
 
        for dirinfo, block in raw_dirblocks:
1737
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1738
 
            details = []
1739
 
            for line in block:
1740
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1741
 
            filtered_dirblocks.append((dirinfo, details))
1742
 
        return filtered_dirblocks
1743
 
 
1744
 
    def test_walk_unicode_tree(self):
1745
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1746
 
        tree, expected_dirblocks = self._get_unicode_tree()
1747
 
        self.build_tree(tree)
1748
 
        result = list(osutils._walkdirs_utf8('.'))
1749
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1750
 
 
1751
 
    def test_symlink(self):
1752
 
        self.requireFeature(tests.SymlinkFeature)
1753
 
        self.requireFeature(tests.UnicodeFilenameFeature)
1754
 
        target = u'target\N{Euro Sign}'
1755
 
        link_name = u'l\N{Euro Sign}nk'
1756
 
        os.symlink(target, link_name)
1757
 
        target_utf8 = target.encode('UTF-8')
1758
 
        link_name_utf8 = link_name.encode('UTF-8')
1759
 
        expected_dirblocks = [
1760
 
                (('', '.'),
1761
 
                 [(link_name_utf8, link_name_utf8,
1762
 
                   'symlink', './' + link_name),],
1763
 
                 )]
1764
 
        result = list(osutils._walkdirs_utf8('.'))
1765
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1766
 
 
1767
 
 
1768
 
class TestReadLink(tests.TestCaseInTempDir):
1769
 
    """Exposes os.readlink() problems and the osutils solution.
1770
 
 
1771
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1772
 
    unicode string will be returned if a unicode string is passed.
1773
 
 
1774
 
    But prior python versions failed to properly encode the passed unicode
1775
 
    string.
1776
 
    """
1777
 
    _test_needs_features = [tests.SymlinkFeature, tests.UnicodeFilenameFeature]
1778
 
 
1779
 
    def setUp(self):
1780
 
        super(tests.TestCaseInTempDir, self).setUp()
1781
 
        self.link = u'l\N{Euro Sign}ink'
1782
 
        self.target = u'targe\N{Euro Sign}t'
1783
 
        os.symlink(self.target, self.link)
1784
 
 
1785
 
    def test_os_readlink_link_encoding(self):
1786
 
        if sys.version_info < (2, 6):
1787
 
            self.assertRaises(UnicodeEncodeError, os.readlink, self.link)
1788
 
        else:
1789
 
            self.assertEquals(self.target,  os.readlink(self.link))
1790
 
 
1791
 
    def test_os_readlink_link_decoding(self):
1792
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
1793
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
1794
 
 
1795
 
 
1796
 
class TestConcurrency(tests.TestCase):
1797
 
 
1798
 
    def test_local_concurrency(self):
1799
 
        concurrency = osutils.local_concurrency()
1800
 
        self.assertIsInstance(concurrency, int)