~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
 
19
from cStringIO import StringIO
19
20
import errno
20
21
import os
 
22
import re
21
23
import socket
22
24
import stat
23
25
import sys
 
26
import time
24
27
 
25
 
import bzrlib
26
28
from bzrlib import (
27
29
    errors,
28
30
    osutils,
 
31
    tests,
29
32
    win32utils,
30
33
    )
31
34
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
35
from bzrlib.osutils import (
 
36
        canonical_relpath,
 
37
        )
32
38
from bzrlib.tests import (
 
39
        Feature,
 
40
        probe_unicode_in_user_encoding,
33
41
        StringIOWrapper,
34
 
        TestCase, 
35
 
        TestCaseInTempDir, 
 
42
        SymlinkFeature,
 
43
        CaseInsCasePresFilenameFeature,
 
44
        TestCase,
 
45
        TestCaseInTempDir,
36
46
        TestSkipped,
37
47
        )
 
48
from bzrlib.tests.file_utils import (
 
49
    FakeReadFile,
 
50
    )
 
51
from bzrlib.tests.test__walkdirs_win32 import Win32ReadDirFeature
 
52
 
 
53
 
 
54
class _UTF8DirReaderFeature(Feature):
 
55
 
 
56
    def _probe(self):
 
57
        try:
 
58
            from bzrlib import _readdir_pyx
 
59
            self.reader = _readdir_pyx.UTF8DirReader
 
60
            return True
 
61
        except ImportError:
 
62
            return False
 
63
 
 
64
    def feature_name(self):
 
65
        return 'bzrlib._readdir_pyx'
 
66
 
 
67
UTF8DirReaderFeature = _UTF8DirReaderFeature()
38
68
 
39
69
 
40
70
class TestOSUtils(TestCaseInTempDir):
86
116
 
87
117
    # TODO: test fancy_rename using a MemoryTransport
88
118
 
 
119
    def test_rename_change_case(self):
 
120
        # on Windows we should be able to change filename case by rename
 
121
        self.build_tree(['a', 'b/'])
 
122
        osutils.rename('a', 'A')
 
123
        osutils.rename('b', 'B')
 
124
        # we can't use failUnlessExists on case-insensitive filesystem
 
125
        # so try to check shape of the tree
 
126
        shape = sorted(os.listdir('.'))
 
127
        self.assertEquals(['A', 'B'], shape)
 
128
 
89
129
    def test_01_rand_chars_empty(self):
90
130
        result = osutils.rand_chars(0)
91
131
        self.assertEqual(result, '')
105
145
        self.assertFalse(is_inside('foo.c', ''))
106
146
        self.assertTrue(is_inside('', 'foo.c'))
107
147
 
 
148
    def test_is_inside_any(self):
 
149
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
150
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
 
151
                         (['src'], SRC_FOO_C),
 
152
                         (['src'], 'src'),
 
153
                         ]:
 
154
            self.assert_(osutils.is_inside_any(dirs, fn))
 
155
        for dirs, fn in [(['src'], 'srccontrol'),
 
156
                         (['src'], 'srccontrol/foo')]:
 
157
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
158
 
 
159
    def test_is_inside_or_parent_of_any(self):
 
160
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
 
161
                         (['src'], 'src/foo.c'),
 
162
                         (['src/bar.c'], 'src'),
 
163
                         (['src/bar.c', 'bla/foo.c'], 'src'),
 
164
                         (['src'], 'src'),
 
165
                         ]:
 
166
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
 
167
 
 
168
        for dirs, fn in [(['src'], 'srccontrol'),
 
169
                         (['srccontrol/foo.c'], 'src'),
 
170
                         (['src'], 'srccontrol/foo')]:
 
171
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
 
172
 
108
173
    def test_rmtree(self):
109
174
        # Check to remove tree with read-only files/dirs
110
175
        os.mkdir('dir')
130
195
        if osutils.has_symlinks():
131
196
            os.symlink('symlink', 'symlink')
132
197
            self.assertEquals('symlink', osutils.file_kind('symlink'))
133
 
        
 
198
 
134
199
        # TODO: jam 20060529 Test a block device
135
200
        try:
136
201
            os.lstat('/dev/null')
218
283
        self.assertFormatedDelta('1 second in the future', -1)
219
284
        self.assertFormatedDelta('2 seconds in the future', -2)
220
285
 
 
286
    def test_format_date(self):
 
287
        self.assertRaises(errors.UnsupportedTimezoneFormat,
 
288
            osutils.format_date, 0, timezone='foo')
 
289
        self.assertIsInstance(osutils.format_date(0), str)
 
290
        self.assertIsInstance(osutils.format_local_date(0), unicode)
 
291
        # Testing for the actual value of the local weekday without
 
292
        # duplicating the code from format_date is difficult.
 
293
        # Instead blackbox.test_locale should check for localized
 
294
        # dates once they do occur in output strings.
 
295
 
221
296
    def test_dereference_path(self):
222
 
        if not osutils.has_symlinks():
223
 
            raise TestSkipped('Symlinks are not supported on this platform')
 
297
        self.requireFeature(SymlinkFeature)
224
298
        cwd = osutils.realpath('.')
225
299
        os.mkdir('bar')
226
300
        bar_path = osutils.pathjoin(cwd, 'bar')
229
303
        self.assertEqual(bar_path, osutils.realpath('./bar'))
230
304
        os.symlink('bar', 'foo')
231
305
        self.assertEqual(bar_path, osutils.realpath('./foo'))
232
 
        
 
306
 
233
307
        # Does not dereference terminal symlinks
234
308
        foo_path = osutils.pathjoin(cwd, 'foo')
235
309
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
246
320
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
247
321
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
248
322
 
 
323
    def test_changing_access(self):
 
324
        f = file('file', 'w')
 
325
        f.write('monkey')
 
326
        f.close()
 
327
 
 
328
        # Make a file readonly
 
329
        osutils.make_readonly('file')
 
330
        mode = os.lstat('file').st_mode
 
331
        self.assertEqual(mode, mode & 0777555)
 
332
 
 
333
        # Make a file writable
 
334
        osutils.make_writable('file')
 
335
        mode = os.lstat('file').st_mode
 
336
        self.assertEqual(mode, mode | 0200)
 
337
 
 
338
        if osutils.has_symlinks():
 
339
            # should not error when handed a symlink
 
340
            os.symlink('nonexistent', 'dangling')
 
341
            osutils.make_readonly('dangling')
 
342
            osutils.make_writable('dangling')
249
343
 
250
344
    def test_kind_marker(self):
251
345
        self.assertEqual("", osutils.kind_marker("file"))
253
347
        self.assertEqual("@", osutils.kind_marker("symlink"))
254
348
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
255
349
 
 
350
    def test_host_os_dereferences_symlinks(self):
 
351
        osutils.host_os_dereferences_symlinks()
 
352
 
 
353
 
 
354
class TestCanonicalRelPath(TestCaseInTempDir):
 
355
 
 
356
    _test_needs_features = [CaseInsCasePresFilenameFeature]
 
357
 
 
358
    def test_canonical_relpath_simple(self):
 
359
        f = file('MixedCaseName', 'w')
 
360
        f.close()
 
361
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
362
        real_base_dir = osutils.realpath(self.test_base_dir)
 
363
        actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
 
364
        self.failUnlessEqual('work/MixedCaseName', actual)
 
365
 
 
366
    def test_canonical_relpath_missing_tail(self):
 
367
        os.mkdir('MixedCaseParent')
 
368
        # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
369
        real_base_dir = osutils.realpath(self.test_base_dir)
 
370
        actual = osutils.canonical_relpath(real_base_dir,
 
371
                                           'mixedcaseparent/nochild')
 
372
        self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
 
373
 
 
374
 
 
375
class TestPumpFile(TestCase):
 
376
    """Test pumpfile method."""
 
377
    def setUp(self):
 
378
        TestCase.setUp(self)
 
379
        # create a test datablock
 
380
        self.block_size = 512
 
381
        pattern = '0123456789ABCDEF'
 
382
        self.test_data = pattern * (3 * self.block_size / len(pattern))
 
383
        self.test_data_len = len(self.test_data)
 
384
 
 
385
    def test_bracket_block_size(self):
 
386
        """Read data in blocks with the requested read size bracketing the
 
387
        block size."""
 
388
        # make sure test data is larger than max read size
 
389
        self.assertTrue(self.test_data_len > self.block_size)
 
390
 
 
391
        from_file = FakeReadFile(self.test_data)
 
392
        to_file = StringIO()
 
393
 
 
394
        # read (max / 2) bytes and verify read size wasn't affected
 
395
        num_bytes_to_read = self.block_size / 2
 
396
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
397
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
 
398
        self.assertEqual(from_file.get_read_count(), 1)
 
399
 
 
400
        # read (max) bytes and verify read size wasn't affected
 
401
        num_bytes_to_read = self.block_size
 
402
        from_file.reset_read_count()
 
403
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
404
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
 
405
        self.assertEqual(from_file.get_read_count(), 1)
 
406
 
 
407
        # read (max + 1) bytes and verify read size was limited
 
408
        num_bytes_to_read = self.block_size + 1
 
409
        from_file.reset_read_count()
 
410
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
411
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
412
        self.assertEqual(from_file.get_read_count(), 2)
 
413
 
 
414
        # finish reading the rest of the data
 
415
        num_bytes_to_read = self.test_data_len - to_file.tell()
 
416
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
417
 
 
418
        # report error if the data wasn't equal (we only report the size due
 
419
        # to the length of the data)
 
420
        response_data = to_file.getvalue()
 
421
        if response_data != self.test_data:
 
422
            message = "Data not equal.  Expected %d bytes, received %d."
 
423
            self.fail(message % (len(response_data), self.test_data_len))
 
424
 
 
425
    def test_specified_size(self):
 
426
        """Request a transfer larger than the maximum block size and verify
 
427
        that the maximum read doesn't exceed the block_size."""
 
428
        # make sure test data is larger than max read size
 
429
        self.assertTrue(self.test_data_len > self.block_size)
 
430
 
 
431
        # retrieve data in blocks
 
432
        from_file = FakeReadFile(self.test_data)
 
433
        to_file = StringIO()
 
434
        osutils.pumpfile(from_file, to_file, self.test_data_len,
 
435
                         self.block_size)
 
436
 
 
437
        # verify read size was equal to the maximum read size
 
438
        self.assertTrue(from_file.get_max_read_size() > 0)
 
439
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
440
        self.assertEqual(from_file.get_read_count(), 3)
 
441
 
 
442
        # report error if the data wasn't equal (we only report the size due
 
443
        # to the length of the data)
 
444
        response_data = to_file.getvalue()
 
445
        if response_data != self.test_data:
 
446
            message = "Data not equal.  Expected %d bytes, received %d."
 
447
            self.fail(message % (len(response_data), self.test_data_len))
 
448
 
 
449
    def test_to_eof(self):
 
450
        """Read to end-of-file and verify that the reads are not larger than
 
451
        the maximum read size."""
 
452
        # make sure test data is larger than max read size
 
453
        self.assertTrue(self.test_data_len > self.block_size)
 
454
 
 
455
        # retrieve data to EOF
 
456
        from_file = FakeReadFile(self.test_data)
 
457
        to_file = StringIO()
 
458
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
 
459
 
 
460
        # verify read size was equal to the maximum read size
 
461
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
 
462
        self.assertEqual(from_file.get_read_count(), 4)
 
463
 
 
464
        # report error if the data wasn't equal (we only report the size due
 
465
        # to the length of the data)
 
466
        response_data = to_file.getvalue()
 
467
        if response_data != self.test_data:
 
468
            message = "Data not equal.  Expected %d bytes, received %d."
 
469
            self.fail(message % (len(response_data), self.test_data_len))
 
470
 
 
471
    def test_defaults(self):
 
472
        """Verifies that the default arguments will read to EOF -- this
 
473
        test verifies that any existing usages of pumpfile will not be broken
 
474
        with this new version."""
 
475
        # retrieve data using default (old) pumpfile method
 
476
        from_file = FakeReadFile(self.test_data)
 
477
        to_file = StringIO()
 
478
        osutils.pumpfile(from_file, to_file)
 
479
 
 
480
        # report error if the data wasn't equal (we only report the size due
 
481
        # to the length of the data)
 
482
        response_data = to_file.getvalue()
 
483
        if response_data != self.test_data:
 
484
            message = "Data not equal.  Expected %d bytes, received %d."
 
485
            self.fail(message % (len(response_data), self.test_data_len))
 
486
 
 
487
    def test_report_activity(self):
 
488
        activity = []
 
489
        def log_activity(length, direction):
 
490
            activity.append((length, direction))
 
491
        from_file = StringIO(self.test_data)
 
492
        to_file = StringIO()
 
493
        osutils.pumpfile(from_file, to_file, buff_size=500,
 
494
                         report_activity=log_activity, direction='read')
 
495
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
 
496
                          (36, 'read')], activity)
 
497
 
 
498
        from_file = StringIO(self.test_data)
 
499
        to_file = StringIO()
 
500
        del activity[:]
 
501
        osutils.pumpfile(from_file, to_file, buff_size=500,
 
502
                         report_activity=log_activity, direction='write')
 
503
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
 
504
                          (36, 'write')], activity)
 
505
 
 
506
        # And with a limited amount of data
 
507
        from_file = StringIO(self.test_data)
 
508
        to_file = StringIO()
 
509
        del activity[:]
 
510
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
 
511
                         report_activity=log_activity, direction='read')
 
512
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
 
513
 
 
514
 
 
515
 
 
516
class TestPumpStringFile(TestCase):
 
517
 
 
518
    def test_empty(self):
 
519
        output = StringIO()
 
520
        osutils.pump_string_file("", output)
 
521
        self.assertEqual("", output.getvalue())
 
522
 
 
523
    def test_more_than_segment_size(self):
 
524
        output = StringIO()
 
525
        osutils.pump_string_file("123456789", output, 2)
 
526
        self.assertEqual("123456789", output.getvalue())
 
527
 
 
528
    def test_segment_size(self):
 
529
        output = StringIO()
 
530
        osutils.pump_string_file("12", output, 2)
 
531
        self.assertEqual("12", output.getvalue())
 
532
 
 
533
    def test_segment_size_multiple(self):
 
534
        output = StringIO()
 
535
        osutils.pump_string_file("1234", output, 2)
 
536
        self.assertEqual("1234", output.getvalue())
 
537
 
256
538
 
257
539
class TestSafeUnicode(TestCase):
258
540
 
297
579
class TestSafeRevisionId(TestCase):
298
580
 
299
581
    def test_from_ascii_string(self):
 
582
        # this shouldn't give a warning because it's getting an ascii string
300
583
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
301
584
 
302
585
    def test_from_unicode_string_ascii_contents(self):
407
690
 
408
691
class TestWin32FuncsDirs(TestCaseInTempDir):
409
692
    """Test win32 functions that create files."""
410
 
    
 
693
 
411
694
    def test_getcwd(self):
412
695
        if win32utils.winver == 'Windows 98':
413
696
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
424
707
        #       osutils.getcwd() renormalize the path.
425
708
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
426
709
 
 
710
    def test_minimum_path_selection(self):
 
711
        self.assertEqual(set(),
 
712
            osutils.minimum_path_selection([]))
 
713
        self.assertEqual(set(['a', 'b']),
 
714
            osutils.minimum_path_selection(['a', 'b']))
 
715
        self.assertEqual(set(['a/', 'b']),
 
716
            osutils.minimum_path_selection(['a/', 'b']))
 
717
        self.assertEqual(set(['a/', 'b']),
 
718
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
 
719
 
427
720
    def test_mkdtemp(self):
428
721
        tmpdir = osutils._win32_mkdtemp(dir='.')
429
722
        self.assertFalse('\\' in tmpdir)
509
802
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
510
803
 
511
804
 
 
805
class TestChunksToLines(TestCase):
 
806
 
 
807
    def test_smoketest(self):
 
808
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
 
809
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
 
810
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
 
811
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
 
812
 
 
813
    def test_osutils_binding(self):
 
814
        from bzrlib.tests import test__chunks_to_lines
 
815
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
 
816
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
817
        else:
 
818
            from bzrlib._chunks_to_lines_py import chunks_to_lines
 
819
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
 
820
 
 
821
 
512
822
class TestSplitLines(TestCase):
513
823
 
514
824
    def test_split_unicode(self):
570
880
        self.assertEqual(expected_dirblocks[1:],
571
881
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
572
882
 
 
883
    def test_walkdirs_os_error(self):
 
884
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
 
885
        # Pyrex readdir didn't raise useful messages if it had an error
 
886
        # reading the directory
 
887
        if sys.platform == 'win32':
 
888
            raise tests.TestNotApplicable(
 
889
                "readdir IOError not tested on win32")
 
890
        os.mkdir("test-unreadable")
 
891
        os.chmod("test-unreadable", 0000)
 
892
        # must chmod it back so that it can be removed
 
893
        self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
 
894
        # The error is not raised until the generator is actually evaluated.
 
895
        # (It would be ok if it happened earlier but at the moment it
 
896
        # doesn't.)
 
897
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
 
898
        self.assertEquals('./test-unreadable', e.filename)
 
899
        self.assertEquals(errno.EACCES, e.errno)
 
900
        # Ensure the message contains the file name
 
901
        self.assertContainsRe(str(e), "\./test-unreadable")
 
902
 
573
903
    def test__walkdirs_utf8(self):
574
904
        tree = [
575
905
            '.bzr',
625
955
                new_dirblock.append((info[0], info[1], info[2], info[4]))
626
956
            dirblock[:] = new_dirblock
627
957
 
 
958
    def _save_platform_info(self):
 
959
        cur_winver = win32utils.winver
 
960
        cur_fs_enc = osutils._fs_enc
 
961
        cur_dir_reader = osutils._selected_dir_reader
 
962
        def restore():
 
963
            win32utils.winver = cur_winver
 
964
            osutils._fs_enc = cur_fs_enc
 
965
            osutils._selected_dir_reader = cur_dir_reader
 
966
        self.addCleanup(restore)
 
967
 
 
968
    def assertReadFSDirIs(self, expected):
 
969
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
 
970
        # Force it to redetect
 
971
        osutils._selected_dir_reader = None
 
972
        # Nothing to list, but should still trigger the selection logic
 
973
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
 
974
        self.assertIsInstance(osutils._selected_dir_reader, expected)
 
975
 
 
976
    def test_force_walkdirs_utf8_fs_utf8(self):
 
977
        self.requireFeature(UTF8DirReaderFeature)
 
978
        self._save_platform_info()
 
979
        win32utils.winver = None # Avoid the win32 detection code
 
980
        osutils._fs_enc = 'UTF-8'
 
981
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
 
982
 
 
983
    def test_force_walkdirs_utf8_fs_ascii(self):
 
984
        self.requireFeature(UTF8DirReaderFeature)
 
985
        self._save_platform_info()
 
986
        win32utils.winver = None # Avoid the win32 detection code
 
987
        osutils._fs_enc = 'US-ASCII'
 
988
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
 
989
 
 
990
    def test_force_walkdirs_utf8_fs_ANSI(self):
 
991
        self.requireFeature(UTF8DirReaderFeature)
 
992
        self._save_platform_info()
 
993
        win32utils.winver = None # Avoid the win32 detection code
 
994
        osutils._fs_enc = 'ANSI_X3.4-1968'
 
995
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
 
996
 
 
997
    def test_force_walkdirs_utf8_fs_latin1(self):
 
998
        self._save_platform_info()
 
999
        win32utils.winver = None # Avoid the win32 detection code
 
1000
        osutils._fs_enc = 'latin1'
 
1001
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
 
1002
 
 
1003
    def test_force_walkdirs_utf8_nt(self):
 
1004
        # Disabled because the thunk of the whole walkdirs api is disabled.
 
1005
        self.requireFeature(Win32ReadDirFeature)
 
1006
        self._save_platform_info()
 
1007
        win32utils.winver = 'Windows NT'
 
1008
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1009
        self.assertReadFSDirIs(Win32ReadDir)
 
1010
 
 
1011
    def test_force_walkdirs_utf8_98(self):
 
1012
        self.requireFeature(Win32ReadDirFeature)
 
1013
        self._save_platform_info()
 
1014
        win32utils.winver = 'Windows 98'
 
1015
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
 
1016
 
628
1017
    def test_unicode_walkdirs(self):
629
1018
        """Walkdirs should always return unicode paths."""
630
1019
        name0 = u'0file-\xb6'
732
1121
            result.append((dirdetail, new_dirblock))
733
1122
        self.assertEqual(expected_dirblocks, result)
734
1123
 
735
 
    def test_unicode__walkdirs_unicode_to_utf8(self):
736
 
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
 
1124
    def test__walkdirs_utf8_with_unicode_fs(self):
 
1125
        """UnicodeDirReader should be a safe fallback everywhere
737
1126
 
738
1127
        The abspath portion should be in unicode
739
1128
        """
 
1129
        # Use the unicode reader. TODO: split into driver-and-driven unit
 
1130
        # tests.
 
1131
        self._save_platform_info()
 
1132
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
740
1133
        name0u = u'0file-\xb6'
741
1134
        name1u = u'1dir-\u062c\u0648'
742
1135
        name2u = u'2file-\u0633'
777
1170
                 ]
778
1171
                ),
779
1172
            ]
780
 
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
781
 
        self._filter_out_stat(result)
782
 
        self.assertEqual(expected_dirblocks, result)
 
1173
        result = list(osutils._walkdirs_utf8('.'))
 
1174
        self._filter_out_stat(result)
 
1175
        self.assertEqual(expected_dirblocks, result)
 
1176
 
 
1177
    def test__walkdirs_utf8_win32readdir(self):
 
1178
        self.requireFeature(Win32ReadDirFeature)
 
1179
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1180
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1181
        self._save_platform_info()
 
1182
        osutils._selected_dir_reader = Win32ReadDir()
 
1183
        name0u = u'0file-\xb6'
 
1184
        name1u = u'1dir-\u062c\u0648'
 
1185
        name2u = u'2file-\u0633'
 
1186
        tree = [
 
1187
            name0u,
 
1188
            name1u + '/',
 
1189
            name1u + '/' + name0u,
 
1190
            name1u + '/' + name1u + '/',
 
1191
            name2u,
 
1192
            ]
 
1193
        self.build_tree(tree)
 
1194
        name0 = name0u.encode('utf8')
 
1195
        name1 = name1u.encode('utf8')
 
1196
        name2 = name2u.encode('utf8')
 
1197
 
 
1198
        # All of the abspaths should be in unicode, all of the relative paths
 
1199
        # should be in utf8
 
1200
        expected_dirblocks = [
 
1201
                (('', '.'),
 
1202
                 [(name0, name0, 'file', './' + name0u),
 
1203
                  (name1, name1, 'directory', './' + name1u),
 
1204
                  (name2, name2, 'file', './' + name2u),
 
1205
                 ]
 
1206
                ),
 
1207
                ((name1, './' + name1u),
 
1208
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
1209
                                                        + '/' + name0u),
 
1210
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
1211
                                                            + '/' + name1u),
 
1212
                 ]
 
1213
                ),
 
1214
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
1215
                 [
 
1216
                 ]
 
1217
                ),
 
1218
            ]
 
1219
        result = list(osutils._walkdirs_utf8(u'.'))
 
1220
        self._filter_out_stat(result)
 
1221
        self.assertEqual(expected_dirblocks, result)
 
1222
 
 
1223
    def assertStatIsCorrect(self, path, win32stat):
 
1224
        os_stat = os.stat(path)
 
1225
        self.assertEqual(os_stat.st_size, win32stat.st_size)
 
1226
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
 
1227
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
 
1228
        self.assertAlmostEqual(os_stat.st_atime, win32stat.st_atime, places=4)
 
1229
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
 
1230
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
 
1231
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
 
1232
 
 
1233
    def test__walkdirs_utf_win32_find_file_stat_file(self):
 
1234
        """make sure our Stat values are valid"""
 
1235
        self.requireFeature(Win32ReadDirFeature)
 
1236
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1237
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1238
        name0u = u'0file-\xb6'
 
1239
        name0 = name0u.encode('utf8')
 
1240
        self.build_tree([name0u])
 
1241
        # I hate to sleep() here, but I'm trying to make the ctime different
 
1242
        # from the mtime
 
1243
        time.sleep(2)
 
1244
        f = open(name0u, 'ab')
 
1245
        try:
 
1246
            f.write('just a small update')
 
1247
        finally:
 
1248
            f.close()
 
1249
 
 
1250
        result = Win32ReadDir().read_dir('', u'.')
 
1251
        entry = result[0]
 
1252
        self.assertEqual((name0, name0, 'file'), entry[:3])
 
1253
        self.assertEqual(u'./' + name0u, entry[4])
 
1254
        self.assertStatIsCorrect(entry[4], entry[3])
 
1255
        self.assertNotEqual(entry[3].st_mtime, entry[3].st_ctime)
 
1256
 
 
1257
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
 
1258
        """make sure our Stat values are valid"""
 
1259
        self.requireFeature(Win32ReadDirFeature)
 
1260
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1261
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1262
        name0u = u'0dir-\u062c\u0648'
 
1263
        name0 = name0u.encode('utf8')
 
1264
        self.build_tree([name0u + '/'])
 
1265
 
 
1266
        result = Win32ReadDir().read_dir('', u'.')
 
1267
        entry = result[0]
 
1268
        self.assertEqual((name0, name0, 'directory'), entry[:3])
 
1269
        self.assertEqual(u'./' + name0u, entry[4])
 
1270
        self.assertStatIsCorrect(entry[4], entry[3])
783
1271
 
784
1272
    def assertPathCompare(self, path_less, path_greater):
785
1273
        """check that path_less and path_greater compare correctly."""
860
1348
 
861
1349
 
862
1350
class TestCopyTree(TestCaseInTempDir):
863
 
    
 
1351
 
864
1352
    def test_copy_basic_tree(self):
865
1353
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
866
1354
        osutils.copy_tree('source', 'target')
875
1363
        self.assertEqual(['c'], os.listdir('target/b'))
876
1364
 
877
1365
    def test_copy_tree_symlinks(self):
878
 
        if not osutils.has_symlinks():
879
 
            return
 
1366
        self.requireFeature(SymlinkFeature)
880
1367
        self.build_tree(['source/'])
881
1368
        os.symlink('a/generic/path', 'source/lnk')
882
1369
        osutils.copy_tree('source', 'target')
946
1433
 
947
1434
    def test_unicode(self):
948
1435
        """Environment can only contain plain strings
949
 
        
 
1436
 
950
1437
        So Unicode strings must be encoded.
951
1438
        """
952
 
        # Try a few different characters, to see if we can get
953
 
        # one that will be valid in the user_encoding
954
 
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
955
 
        for uni_val in possible_vals:
956
 
            try:
957
 
                env_val = uni_val.encode(bzrlib.user_encoding)
958
 
            except UnicodeEncodeError:
959
 
                # Try a different character
960
 
                pass
961
 
            else:
962
 
                break
963
 
        else:
 
1439
        uni_val, env_val = probe_unicode_in_user_encoding()
 
1440
        if uni_val is None:
964
1441
            raise TestSkipped('Cannot find a unicode character that works in'
965
 
                              ' encoding %s' % (bzrlib.user_encoding,))
 
1442
                              ' encoding %s' % (osutils.get_user_encoding(),))
966
1443
 
967
1444
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
968
1445
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
996
1473
        self.assertTrue(isinstance(offset, int))
997
1474
        eighteen_hours = 18 * 3600
998
1475
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1476
 
 
1477
 
 
1478
class TestSizeShaFile(TestCaseInTempDir):
 
1479
 
 
1480
    def test_sha_empty(self):
 
1481
        self.build_tree_contents([('foo', '')])
 
1482
        expected_sha = osutils.sha_string('')
 
1483
        f = open('foo')
 
1484
        self.addCleanup(f.close)
 
1485
        size, sha = osutils.size_sha_file(f)
 
1486
        self.assertEqual(0, size)
 
1487
        self.assertEqual(expected_sha, sha)
 
1488
 
 
1489
    def test_sha_mixed_endings(self):
 
1490
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1491
        self.build_tree_contents([('foo', text)])
 
1492
        expected_sha = osutils.sha_string(text)
 
1493
        f = open('foo')
 
1494
        self.addCleanup(f.close)
 
1495
        size, sha = osutils.size_sha_file(f)
 
1496
        self.assertEqual(38, size)
 
1497
        self.assertEqual(expected_sha, sha)
 
1498
 
 
1499
 
 
1500
class TestShaFileByName(TestCaseInTempDir):
 
1501
 
 
1502
    def test_sha_empty(self):
 
1503
        self.build_tree_contents([('foo', '')])
 
1504
        expected_sha = osutils.sha_string('')
 
1505
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1506
 
 
1507
    def test_sha_mixed_endings(self):
 
1508
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1509
        self.build_tree_contents([('foo', text)])
 
1510
        expected_sha = osutils.sha_string(text)
 
1511
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1512
 
 
1513
 
 
1514
class TestResourceLoading(TestCaseInTempDir):
 
1515
 
 
1516
    def test_resource_string(self):
 
1517
        # test resource in bzrlib
 
1518
        text = osutils.resource_string('bzrlib', 'debug.py')
 
1519
        self.assertContainsRe(text, "debug_flags = set()")
 
1520
        # test resource under bzrlib
 
1521
        text = osutils.resource_string('bzrlib.ui', 'text.py')
 
1522
        self.assertContainsRe(text, "class TextUIFactory")
 
1523
        # test unsupported package
 
1524
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
 
1525
            'yyy.xx')
 
1526
        # test unknown resource
 
1527
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
 
1528
 
 
1529
 
 
1530
class TestReCompile(TestCase):
 
1531
 
 
1532
    def test_re_compile_checked(self):
 
1533
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
 
1534
        self.assertTrue(r.match('aaaa'))
 
1535
        self.assertTrue(r.match('aAaA'))
 
1536
 
 
1537
    def test_re_compile_checked_error(self):
 
1538
        # like https://bugs.launchpad.net/bzr/+bug/251352
 
1539
        err = self.assertRaises(
 
1540
            errors.BzrCommandError,
 
1541
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1542
        self.assertEqual(
 
1543
            "Invalid regular expression in test case: '*': "
 
1544
            "nothing to repeat",
 
1545
            str(err))