~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Andrew Bennetts
  • Date: 2009-04-02 05:53:12 UTC
  • mto: This revision was merged to the branch mainline in revision 4242.
  • Revision ID: andrew.bennetts@canonical.com-20090402055312-h7mvgumvm7e620mj
Fix nits in spelling and naming.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
21
21
import os
22
22
import re
23
23
import socket
 
24
import stat
24
25
import sys
25
26
import time
26
27
 
27
28
from bzrlib import (
28
29
    errors,
29
 
    lazy_regex,
30
30
    osutils,
31
 
    symbol_versioning,
32
31
    tests,
33
 
    trace,
34
32
    win32utils,
35
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
        pump_string_file,
 
41
        canonical_relpath,
 
42
        )
36
43
from bzrlib.tests import (
37
 
    features,
38
 
    file_utils,
39
 
    test__walkdirs_win32,
 
44
        Feature,
 
45
        probe_unicode_in_user_encoding,
 
46
        StringIOWrapper,
 
47
        SymlinkFeature,
 
48
        CaseInsCasePresFilenameFeature,
 
49
        TestCase,
 
50
        TestCaseInTempDir,
 
51
        TestSkipped,
 
52
        )
 
53
from bzrlib.tests.file_utils import (
 
54
    FakeReadFile,
40
55
    )
41
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
 
 
43
 
 
44
 
class _UTF8DirReaderFeature(features.Feature):
 
56
from bzrlib.tests.test__walkdirs_win32 import Win32ReadDirFeature
 
57
 
 
58
 
 
59
class _UTF8DirReaderFeature(Feature):
45
60
 
46
61
    def _probe(self):
47
62
        try:
54
69
    def feature_name(self):
55
70
        return 'bzrlib._readdir_pyx'
56
71
 
57
 
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
58
 
 
59
 
term_ios_feature = features.ModuleAvailableFeature('termios')
60
 
 
61
 
 
62
 
def _already_unicode(s):
63
 
    return s
64
 
 
65
 
 
66
 
def _utf8_to_unicode(s):
67
 
    return s.decode('UTF-8')
68
 
 
69
 
 
70
 
def dir_reader_scenarios():
71
 
    # For each dir reader we define:
72
 
 
73
 
    # - native_to_unicode: a function converting the native_abspath as returned
74
 
    #   by DirReader.read_dir to its unicode representation
75
 
 
76
 
    # UnicodeDirReader is the fallback, it should be tested on all platforms.
77
 
    scenarios = [('unicode',
78
 
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
79
 
                       _native_to_unicode=_already_unicode))]
80
 
    # Some DirReaders are platform specific and even there they may not be
81
 
    # available.
82
 
    if UTF8DirReaderFeature.available():
83
 
        from bzrlib import _readdir_pyx
84
 
        scenarios.append(('utf8',
85
 
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
86
 
                               _native_to_unicode=_utf8_to_unicode)))
87
 
 
88
 
    if test__walkdirs_win32.win32_readdir_feature.available():
89
 
        try:
90
 
            from bzrlib import _walkdirs_win32
91
 
            scenarios.append(
92
 
                ('win32',
93
 
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
94
 
                      _native_to_unicode=_already_unicode)))
95
 
        except ImportError:
96
 
            pass
97
 
    return scenarios
98
 
 
99
 
 
100
 
load_tests = load_tests_apply_scenarios
101
 
 
102
 
 
103
 
class TestContainsWhitespace(tests.TestCase):
 
72
UTF8DirReaderFeature = _UTF8DirReaderFeature()
 
73
 
 
74
 
 
75
class TestOSUtils(TestCaseInTempDir):
104
76
 
105
77
    def test_contains_whitespace(self):
106
 
        self.assertTrue(osutils.contains_whitespace(u' '))
107
 
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
108
 
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
109
 
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
110
 
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
111
 
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
 
78
        self.failUnless(osutils.contains_whitespace(u' '))
 
79
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
80
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
81
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
82
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
83
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
112
84
 
113
85
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
114
86
        # is whitespace, but we do not.
115
 
        self.assertFalse(osutils.contains_whitespace(u''))
116
 
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
117
 
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
118
 
 
119
 
 
120
 
class TestRename(tests.TestCaseInTempDir):
121
 
 
122
 
    def create_file(self, filename, content):
123
 
        f = open(filename, 'wb')
124
 
        try:
125
 
            f.write(content)
126
 
        finally:
127
 
            f.close()
128
 
 
129
 
    def _fancy_rename(self, a, b):
130
 
        osutils.fancy_rename(a, b, rename_func=os.rename,
131
 
                             unlink_func=os.unlink)
 
87
        self.failIf(osutils.contains_whitespace(u''))
 
88
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
89
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
132
90
 
133
91
    def test_fancy_rename(self):
134
92
        # This should work everywhere
135
 
        self.create_file('a', 'something in a\n')
136
 
        self._fancy_rename('a', 'b')
137
 
        self.assertPathDoesNotExist('a')
138
 
        self.assertPathExists('b')
 
93
        def rename(a, b):
 
94
            osutils.fancy_rename(a, b,
 
95
                    rename_func=os.rename,
 
96
                    unlink_func=os.unlink)
 
97
 
 
98
        open('a', 'wb').write('something in a\n')
 
99
        rename('a', 'b')
 
100
        self.failIfExists('a')
 
101
        self.failUnlessExists('b')
139
102
        self.check_file_contents('b', 'something in a\n')
140
103
 
141
 
        self.create_file('a', 'new something in a\n')
142
 
        self._fancy_rename('b', 'a')
 
104
        open('a', 'wb').write('new something in a\n')
 
105
        rename('b', 'a')
143
106
 
144
107
        self.check_file_contents('a', 'something in a\n')
145
108
 
146
 
    def test_fancy_rename_fails_source_missing(self):
147
 
        # An exception should be raised, and the target should be left in place
148
 
        self.create_file('target', 'data in target\n')
149
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
150
 
                          'missingsource', 'target')
151
 
        self.assertPathExists('target')
152
 
        self.check_file_contents('target', 'data in target\n')
153
 
 
154
 
    def test_fancy_rename_fails_if_source_and_target_missing(self):
155
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
156
 
                          'missingsource', 'missingtarget')
157
 
 
158
109
    def test_rename(self):
159
110
        # Rename should be semi-atomic on all platforms
160
 
        self.create_file('a', 'something in a\n')
 
111
        open('a', 'wb').write('something in a\n')
161
112
        osutils.rename('a', 'b')
162
 
        self.assertPathDoesNotExist('a')
163
 
        self.assertPathExists('b')
 
113
        self.failIfExists('a')
 
114
        self.failUnlessExists('b')
164
115
        self.check_file_contents('b', 'something in a\n')
165
116
 
166
 
        self.create_file('a', 'new something in a\n')
 
117
        open('a', 'wb').write('new something in a\n')
167
118
        osutils.rename('b', 'a')
168
119
 
169
120
        self.check_file_contents('a', 'something in a\n')
180
131
        shape = sorted(os.listdir('.'))
181
132
        self.assertEquals(['A', 'B'], shape)
182
133
 
183
 
 
184
 
class TestRandChars(tests.TestCase):
185
 
 
186
134
    def test_01_rand_chars_empty(self):
187
135
        result = osutils.rand_chars(0)
188
136
        self.assertEqual(result, '')
193
141
        self.assertEqual(type(result), str)
194
142
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
195
143
 
196
 
 
197
 
class TestIsInside(tests.TestCase):
198
 
 
199
144
    def test_is_inside(self):
200
145
        is_inside = osutils.is_inside
201
146
        self.assertTrue(is_inside('src', 'src/foo.c'))
206
151
        self.assertTrue(is_inside('', 'foo.c'))
207
152
 
208
153
    def test_is_inside_any(self):
209
 
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
154
        SRC_FOO_C = pathjoin('src', 'foo.c')
210
155
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
211
156
                         (['src'], SRC_FOO_C),
212
157
                         (['src'], 'src'),
213
158
                         ]:
214
 
            self.assert_(osutils.is_inside_any(dirs, fn))
 
159
            self.assert_(is_inside_any(dirs, fn))
215
160
        for dirs, fn in [(['src'], 'srccontrol'),
216
161
                         (['src'], 'srccontrol/foo')]:
217
 
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
162
            self.assertFalse(is_inside_any(dirs, fn))
218
163
 
219
164
    def test_is_inside_or_parent_of_any(self):
220
165
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
223
168
                         (['src/bar.c', 'bla/foo.c'], 'src'),
224
169
                         (['src'], 'src'),
225
170
                         ]:
226
 
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
 
171
            self.assert_(is_inside_or_parent_of_any(dirs, fn))
227
172
 
228
173
        for dirs, fn in [(['src'], 'srccontrol'),
229
174
                         (['srccontrol/foo.c'], 'src'),
230
175
                         (['src'], 'srccontrol/foo')]:
231
 
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
232
 
 
233
 
 
234
 
class TestLstat(tests.TestCaseInTempDir):
235
 
 
236
 
    def test_lstat_matches_fstat(self):
237
 
        # On Windows, lstat and fstat don't always agree, primarily in the
238
 
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
239
 
        # custom implementation.
240
 
        if sys.platform == 'win32':
241
 
            # We only have special lstat/fstat if we have the extension.
242
 
            # Without it, we may end up re-reading content when we don't have
243
 
            # to, but otherwise it doesn't effect correctness.
244
 
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
245
 
        f = open('test-file.txt', 'wb')
246
 
        self.addCleanup(f.close)
247
 
        f.write('some content\n')
248
 
        f.flush()
249
 
        self.assertEqualStat(osutils.fstat(f.fileno()),
250
 
                             osutils.lstat('test-file.txt'))
251
 
 
252
 
 
253
 
class TestRmTree(tests.TestCaseInTempDir):
 
176
            self.assertFalse(is_inside_or_parent_of_any(dirs, fn))
254
177
 
255
178
    def test_rmtree(self):
256
179
        # Check to remove tree with read-only files/dirs
267
190
 
268
191
        osutils.rmtree('dir')
269
192
 
270
 
        self.assertPathDoesNotExist('dir/file')
271
 
        self.assertPathDoesNotExist('dir')
272
 
 
273
 
 
274
 
class TestDeleteAny(tests.TestCaseInTempDir):
275
 
 
276
 
    def test_delete_any_readonly(self):
277
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
278
 
        self.build_tree(['d/', 'f'])
279
 
        osutils.make_readonly('d')
280
 
        osutils.make_readonly('f')
281
 
 
282
 
        osutils.delete_any('f')
283
 
        osutils.delete_any('d')
284
 
 
285
 
 
286
 
class TestKind(tests.TestCaseInTempDir):
 
193
        self.failIfExists('dir/file')
 
194
        self.failIfExists('dir')
287
195
 
288
196
    def test_file_kind(self):
289
197
        self.build_tree(['file', 'dir/'])
320
228
                os.remove('socket')
321
229
 
322
230
    def test_kind_marker(self):
323
 
        self.assertEqual("", osutils.kind_marker("file"))
324
 
        self.assertEqual("/", osutils.kind_marker('directory'))
325
 
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
326
 
        self.assertEqual("@", osutils.kind_marker("symlink"))
327
 
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
328
 
        self.assertEqual("", osutils.kind_marker("fifo"))
329
 
        self.assertEqual("", osutils.kind_marker("socket"))
330
 
        self.assertEqual("", osutils.kind_marker("unknown"))
331
 
 
332
 
 
333
 
class TestUmask(tests.TestCaseInTempDir):
 
231
        self.assertEqual(osutils.kind_marker('file'), '')
 
232
        self.assertEqual(osutils.kind_marker('directory'), '/')
 
233
        self.assertEqual(osutils.kind_marker('symlink'), '@')
 
234
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
334
235
 
335
236
    def test_get_umask(self):
336
237
        if sys.platform == 'win32':
339
240
            return
340
241
 
341
242
        orig_umask = osutils.get_umask()
342
 
        self.addCleanup(os.umask, orig_umask)
343
 
        os.umask(0222)
344
 
        self.assertEqual(0222, osutils.get_umask())
345
 
        os.umask(0022)
346
 
        self.assertEqual(0022, osutils.get_umask())
347
 
        os.umask(0002)
348
 
        self.assertEqual(0002, osutils.get_umask())
349
 
        os.umask(0027)
350
 
        self.assertEqual(0027, osutils.get_umask())
351
 
 
352
 
 
353
 
class TestDateTime(tests.TestCase):
 
243
        try:
 
244
            os.umask(0222)
 
245
            self.assertEqual(0222, osutils.get_umask())
 
246
            os.umask(0022)
 
247
            self.assertEqual(0022, osutils.get_umask())
 
248
            os.umask(0002)
 
249
            self.assertEqual(0002, osutils.get_umask())
 
250
            os.umask(0027)
 
251
            self.assertEqual(0027, osutils.get_umask())
 
252
        finally:
 
253
            os.umask(orig_umask)
354
254
 
355
255
    def assertFormatedDelta(self, expected, seconds):
356
256
        """Assert osutils.format_delta formats as expected"""
398
298
        # Instead blackbox.test_locale should check for localized
399
299
        # dates once they do occur in output strings.
400
300
 
401
 
    def test_format_date_with_offset_in_original_timezone(self):
402
 
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
403
 
            osutils.format_date_with_offset_in_original_timezone(0))
404
 
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
405
 
            osutils.format_date_with_offset_in_original_timezone(100000))
406
 
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
407
 
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
408
 
 
409
 
    def test_local_time_offset(self):
410
 
        """Test that local_time_offset() returns a sane value."""
411
 
        offset = osutils.local_time_offset()
412
 
        self.assertTrue(isinstance(offset, int))
413
 
        # Test that the offset is no more than a eighteen hours in
414
 
        # either direction.
415
 
        # Time zone handling is system specific, so it is difficult to
416
 
        # do more specific tests, but a value outside of this range is
417
 
        # probably wrong.
418
 
        eighteen_hours = 18 * 3600
419
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
420
 
 
421
 
    def test_local_time_offset_with_timestamp(self):
422
 
        """Test that local_time_offset() works with a timestamp."""
423
 
        offset = osutils.local_time_offset(1000000000.1234567)
424
 
        self.assertTrue(isinstance(offset, int))
425
 
        eighteen_hours = 18 * 3600
426
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
427
 
 
428
 
 
429
 
class TestLinks(tests.TestCaseInTempDir):
430
 
 
431
301
    def test_dereference_path(self):
432
 
        self.requireFeature(features.SymlinkFeature)
 
302
        self.requireFeature(SymlinkFeature)
433
303
        cwd = osutils.realpath('.')
434
304
        os.mkdir('bar')
435
305
        bar_path = osutils.pathjoin(cwd, 'bar')
476
346
            osutils.make_readonly('dangling')
477
347
            osutils.make_writable('dangling')
478
348
 
 
349
    def test_kind_marker(self):
 
350
        self.assertEqual("", osutils.kind_marker("file"))
 
351
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
 
352
        self.assertEqual("@", osutils.kind_marker("symlink"))
 
353
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
354
 
479
355
    def test_host_os_dereferences_symlinks(self):
480
356
        osutils.host_os_dereferences_symlinks()
481
357
 
482
358
 
483
 
class TestCanonicalRelPath(tests.TestCaseInTempDir):
 
359
class TestCanonicalRelPath(TestCaseInTempDir):
484
360
 
485
 
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
 
361
    _test_needs_features = [CaseInsCasePresFilenameFeature]
486
362
 
487
363
    def test_canonical_relpath_simple(self):
488
364
        f = file('MixedCaseName', 'w')
489
365
        f.close()
490
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
491
 
        self.assertEqual('work/MixedCaseName', actual)
 
366
        self.failUnlessEqual(
 
367
            canonical_relpath(self.test_base_dir, 'mixedcasename'),
 
368
            'work/MixedCaseName')
492
369
 
493
370
    def test_canonical_relpath_missing_tail(self):
494
371
        os.mkdir('MixedCaseParent')
495
 
        actual = osutils.canonical_relpath(self.test_base_dir,
496
 
                                           'mixedcaseparent/nochild')
497
 
        self.assertEqual('work/MixedCaseParent/nochild', actual)
498
 
 
499
 
 
500
 
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
501
 
 
502
 
    def assertRelpath(self, expected, base, path):
503
 
        actual = osutils._cicp_canonical_relpath(base, path)
504
 
        self.assertEqual(expected, actual)
505
 
 
506
 
    def test_simple(self):
507
 
        self.build_tree(['MixedCaseName'])
508
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
509
 
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
510
 
 
511
 
    def test_subdir_missing_tail(self):
512
 
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
513
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
514
 
        self.assertRelpath('MixedCaseParent/a_child', base,
515
 
                           'MixedCaseParent/a_child')
516
 
        self.assertRelpath('MixedCaseParent/a_child', base,
517
 
                           'MixedCaseParent/A_Child')
518
 
        self.assertRelpath('MixedCaseParent/not_child', base,
519
 
                           'MixedCaseParent/not_child')
520
 
 
521
 
    def test_at_root_slash(self):
522
 
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
523
 
        # check...
524
 
        if osutils.MIN_ABS_PATHLENGTH > 1:
525
 
            raise tests.TestSkipped('relpath requires %d chars'
526
 
                                    % osutils.MIN_ABS_PATHLENGTH)
527
 
        self.assertRelpath('foo', '/', '/foo')
528
 
 
529
 
    def test_at_root_drive(self):
530
 
        if sys.platform != 'win32':
531
 
            raise tests.TestNotApplicable('we can only test drive-letter relative'
532
 
                                          ' paths on Windows where we have drive'
533
 
                                          ' letters.')
534
 
        # see bug #322807
535
 
        # The specific issue is that when at the root of a drive, 'abspath'
536
 
        # returns "C:/" or just "/". However, the code assumes that abspath
537
 
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
538
 
        self.assertRelpath('foo', 'C:/', 'C:/foo')
539
 
        self.assertRelpath('foo', 'X:/', 'X:/foo')
540
 
        self.assertRelpath('foo', 'X:/', 'X://foo')
541
 
 
542
 
 
543
 
class TestPumpFile(tests.TestCase):
 
372
        self.failUnlessEqual(
 
373
            canonical_relpath(self.test_base_dir, 'mixedcaseparent/nochild'),
 
374
            'work/MixedCaseParent/nochild')
 
375
 
 
376
 
 
377
class TestPumpFile(TestCase):
544
378
    """Test pumpfile method."""
545
 
 
546
379
    def setUp(self):
547
 
        tests.TestCase.setUp(self)
 
380
        TestCase.setUp(self)
548
381
        # create a test datablock
549
382
        self.block_size = 512
550
383
        pattern = '0123456789ABCDEF'
557
390
        # make sure test data is larger than max read size
558
391
        self.assertTrue(self.test_data_len > self.block_size)
559
392
 
560
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
393
        from_file = FakeReadFile(self.test_data)
561
394
        to_file = StringIO()
562
395
 
563
396
        # read (max / 2) bytes and verify read size wasn't affected
564
397
        num_bytes_to_read = self.block_size / 2
565
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
398
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
566
399
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
567
400
        self.assertEqual(from_file.get_read_count(), 1)
568
401
 
569
402
        # read (max) bytes and verify read size wasn't affected
570
403
        num_bytes_to_read = self.block_size
571
404
        from_file.reset_read_count()
572
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
405
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
573
406
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
574
407
        self.assertEqual(from_file.get_read_count(), 1)
575
408
 
576
409
        # read (max + 1) bytes and verify read size was limited
577
410
        num_bytes_to_read = self.block_size + 1
578
411
        from_file.reset_read_count()
579
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
412
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
580
413
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
581
414
        self.assertEqual(from_file.get_read_count(), 2)
582
415
 
583
416
        # finish reading the rest of the data
584
417
        num_bytes_to_read = self.test_data_len - to_file.tell()
585
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
418
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
586
419
 
587
420
        # report error if the data wasn't equal (we only report the size due
588
421
        # to the length of the data)
598
431
        self.assertTrue(self.test_data_len > self.block_size)
599
432
 
600
433
        # retrieve data in blocks
601
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
434
        from_file = FakeReadFile(self.test_data)
602
435
        to_file = StringIO()
603
 
        osutils.pumpfile(from_file, to_file, self.test_data_len,
604
 
                         self.block_size)
 
436
        pumpfile(from_file, to_file, self.test_data_len, self.block_size)
605
437
 
606
438
        # verify read size was equal to the maximum read size
607
439
        self.assertTrue(from_file.get_max_read_size() > 0)
622
454
        self.assertTrue(self.test_data_len > self.block_size)
623
455
 
624
456
        # retrieve data to EOF
625
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
457
        from_file = FakeReadFile(self.test_data)
626
458
        to_file = StringIO()
627
 
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
 
459
        pumpfile(from_file, to_file, -1, self.block_size)
628
460
 
629
461
        # verify read size was equal to the maximum read size
630
462
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
642
474
        test verifies that any existing usages of pumpfile will not be broken
643
475
        with this new version."""
644
476
        # retrieve data using default (old) pumpfile method
645
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
477
        from_file = FakeReadFile(self.test_data)
646
478
        to_file = StringIO()
647
 
        osutils.pumpfile(from_file, to_file)
 
479
        pumpfile(from_file, to_file)
648
480
 
649
481
        # report error if the data wasn't equal (we only report the size due
650
482
        # to the length of the data)
659
491
            activity.append((length, direction))
660
492
        from_file = StringIO(self.test_data)
661
493
        to_file = StringIO()
662
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
663
 
                         report_activity=log_activity, direction='read')
 
494
        pumpfile(from_file, to_file, buff_size=500,
 
495
                 report_activity=log_activity, direction='read')
664
496
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
665
497
                          (36, 'read')], activity)
666
498
 
667
499
        from_file = StringIO(self.test_data)
668
500
        to_file = StringIO()
669
501
        del activity[:]
670
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
671
 
                         report_activity=log_activity, direction='write')
 
502
        pumpfile(from_file, to_file, buff_size=500,
 
503
                 report_activity=log_activity, direction='write')
672
504
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
673
505
                          (36, 'write')], activity)
674
506
 
676
508
        from_file = StringIO(self.test_data)
677
509
        to_file = StringIO()
678
510
        del activity[:]
679
 
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
680
 
                         report_activity=log_activity, direction='read')
 
511
        pumpfile(from_file, to_file, buff_size=500, read_length=1028,
 
512
                 report_activity=log_activity, direction='read')
681
513
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
682
514
 
683
515
 
684
516
 
685
 
class TestPumpStringFile(tests.TestCase):
 
517
class TestPumpStringFile(TestCase):
686
518
 
687
519
    def test_empty(self):
688
520
        output = StringIO()
689
 
        osutils.pump_string_file("", output)
 
521
        pump_string_file("", output)
690
522
        self.assertEqual("", output.getvalue())
691
523
 
692
524
    def test_more_than_segment_size(self):
693
525
        output = StringIO()
694
 
        osutils.pump_string_file("123456789", output, 2)
 
526
        pump_string_file("123456789", output, 2)
695
527
        self.assertEqual("123456789", output.getvalue())
696
528
 
697
529
    def test_segment_size(self):
698
530
        output = StringIO()
699
 
        osutils.pump_string_file("12", output, 2)
 
531
        pump_string_file("12", output, 2)
700
532
        self.assertEqual("12", output.getvalue())
701
533
 
702
534
    def test_segment_size_multiple(self):
703
535
        output = StringIO()
704
 
        osutils.pump_string_file("1234", output, 2)
 
536
        pump_string_file("1234", output, 2)
705
537
        self.assertEqual("1234", output.getvalue())
706
538
 
707
539
 
708
 
class TestRelpath(tests.TestCase):
709
 
 
710
 
    def test_simple_relpath(self):
711
 
        cwd = osutils.getcwd()
712
 
        subdir = cwd + '/subdir'
713
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
714
 
 
715
 
    def test_deep_relpath(self):
716
 
        cwd = osutils.getcwd()
717
 
        subdir = cwd + '/sub/subsubdir'
718
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
719
 
 
720
 
    def test_not_relative(self):
721
 
        self.assertRaises(errors.PathNotChild,
722
 
                          osutils.relpath, 'C:/path', 'H:/path')
723
 
        self.assertRaises(errors.PathNotChild,
724
 
                          osutils.relpath, 'C:/', 'H:/path')
725
 
 
726
 
 
727
 
class TestSafeUnicode(tests.TestCase):
 
540
class TestSafeUnicode(TestCase):
728
541
 
729
542
    def test_from_ascii_string(self):
730
543
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
739
552
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
740
553
 
741
554
    def test_bad_utf8_string(self):
742
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
555
        self.assertRaises(BzrBadParameterNotUnicode,
743
556
                          osutils.safe_unicode,
744
557
                          '\xbb\xbb')
745
558
 
746
559
 
747
 
class TestSafeUtf8(tests.TestCase):
 
560
class TestSafeUtf8(TestCase):
748
561
 
749
562
    def test_from_ascii_string(self):
750
563
        f = 'foobar'
760
573
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
761
574
 
762
575
    def test_bad_utf8_string(self):
763
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
576
        self.assertRaises(BzrBadParameterNotUnicode,
764
577
                          osutils.safe_utf8, '\xbb\xbb')
765
578
 
766
579
 
767
 
class TestSafeRevisionId(tests.TestCase):
 
580
class TestSafeRevisionId(TestCase):
768
581
 
769
582
    def test_from_ascii_string(self):
770
583
        # this shouldn't give a warning because it's getting an ascii string
792
605
        self.assertEqual(None, osutils.safe_revision_id(None))
793
606
 
794
607
 
795
 
class TestSafeFileId(tests.TestCase):
 
608
class TestSafeFileId(TestCase):
796
609
 
797
610
    def test_from_ascii_string(self):
798
611
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
818
631
        self.assertEqual(None, osutils.safe_file_id(None))
819
632
 
820
633
 
821
 
class TestWin32Funcs(tests.TestCase):
822
 
    """Test that _win32 versions of os utilities return appropriate paths."""
 
634
class TestWin32Funcs(TestCase):
 
635
    """Test that the _win32 versions of os utilities return appropriate paths."""
823
636
 
824
637
    def test_abspath(self):
825
638
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
832
645
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
833
646
 
834
647
    def test_pathjoin(self):
835
 
        self.assertEqual('path/to/foo',
836
 
                         osutils._win32_pathjoin('path', 'to', 'foo'))
837
 
        self.assertEqual('C:/foo',
838
 
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
839
 
        self.assertEqual('C:/foo',
840
 
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
841
 
        self.assertEqual('path/to/foo',
842
 
                         osutils._win32_pathjoin('path/to/', 'foo'))
843
 
        self.assertEqual('/foo',
844
 
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
845
 
        self.assertEqual('/foo',
846
 
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
648
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
649
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
650
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
651
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
652
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
653
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
847
654
 
848
655
    def test_normpath(self):
849
 
        self.assertEqual('path/to/foo',
850
 
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
851
 
        self.assertEqual('path/to/foo',
852
 
                         osutils._win32_normpath('path//from/../to/./foo'))
 
656
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
657
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
853
658
 
854
659
    def test_getcwd(self):
855
660
        cwd = osutils._win32_getcwd()
876
681
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
877
682
        # relative path
878
683
        cwd = osutils.getcwd().rstrip('/')
879
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
684
        drive = osutils._nt_splitdrive(cwd)[0]
880
685
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
881
686
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
882
687
        # unicode path
884
689
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
885
690
 
886
691
 
887
 
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
 
692
class TestWin32FuncsDirs(TestCaseInTempDir):
888
693
    """Test win32 functions that create files."""
889
694
 
890
695
    def test_getcwd(self):
891
 
        self.requireFeature(features.UnicodeFilenameFeature)
892
 
        os.mkdir(u'mu-\xb5')
 
696
        if win32utils.winver == 'Windows 98':
 
697
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
698
        # Make sure getcwd can handle unicode filenames
 
699
        try:
 
700
            os.mkdir(u'mu-\xb5')
 
701
        except UnicodeError:
 
702
            raise TestSkipped("Unable to create Unicode filename")
 
703
 
893
704
        os.chdir(u'mu-\xb5')
894
705
        # TODO: jam 20060427 This will probably fail on Mac OSX because
895
706
        #       it will change the normalization of B\xe5gfors
900
711
    def test_minimum_path_selection(self):
901
712
        self.assertEqual(set(),
902
713
            osutils.minimum_path_selection([]))
903
 
        self.assertEqual(set(['a']),
904
 
            osutils.minimum_path_selection(['a']))
905
714
        self.assertEqual(set(['a', 'b']),
906
715
            osutils.minimum_path_selection(['a', 'b']))
907
716
        self.assertEqual(set(['a/', 'b']),
908
717
            osutils.minimum_path_selection(['a/', 'b']))
909
718
        self.assertEqual(set(['a/', 'b']),
910
719
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
911
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
912
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
913
720
 
914
721
    def test_mkdtemp(self):
915
722
        tmpdir = osutils._win32_mkdtemp(dir='.')
924
731
        b.close()
925
732
 
926
733
        osutils._win32_rename('b', 'a')
927
 
        self.assertPathExists('a')
928
 
        self.assertPathDoesNotExist('b')
 
734
        self.failUnlessExists('a')
 
735
        self.failIfExists('b')
929
736
        self.assertFileEqual('baz\n', 'a')
930
737
 
931
738
    def test_rename_missing_file(self):
971
778
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
972
779
 
973
780
 
974
 
class TestParentDirectories(tests.TestCaseInTempDir):
975
 
    """Test osutils.parent_directories()"""
976
 
 
977
 
    def test_parent_directories(self):
978
 
        self.assertEqual([], osutils.parent_directories('a'))
979
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
980
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
981
 
 
982
 
 
983
 
class TestMacFuncsDirs(tests.TestCaseInTempDir):
 
781
class TestMacFuncsDirs(TestCaseInTempDir):
984
782
    """Test mac special functions that require directories."""
985
783
 
986
784
    def test_getcwd(self):
987
 
        self.requireFeature(features.UnicodeFilenameFeature)
988
 
        os.mkdir(u'B\xe5gfors')
 
785
        # On Mac, this will actually create Ba\u030agfors
 
786
        # but chdir will still work, because it accepts both paths
 
787
        try:
 
788
            os.mkdir(u'B\xe5gfors')
 
789
        except UnicodeError:
 
790
            raise TestSkipped("Unable to create Unicode filename")
 
791
 
989
792
        os.chdir(u'B\xe5gfors')
990
793
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
991
794
 
992
795
    def test_getcwd_nonnorm(self):
993
 
        self.requireFeature(features.UnicodeFilenameFeature)
994
796
        # Test that _mac_getcwd() will normalize this path
995
 
        os.mkdir(u'Ba\u030agfors')
 
797
        try:
 
798
            os.mkdir(u'Ba\u030agfors')
 
799
        except UnicodeError:
 
800
            raise TestSkipped("Unable to create Unicode filename")
 
801
 
996
802
        os.chdir(u'Ba\u030agfors')
997
803
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
998
804
 
999
805
 
1000
 
class TestChunksToLines(tests.TestCase):
 
806
class TestChunksToLines(TestCase):
1001
807
 
1002
808
    def test_smoketest(self):
1003
809
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
1007
813
 
1008
814
    def test_osutils_binding(self):
1009
815
        from bzrlib.tests import test__chunks_to_lines
1010
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
 
816
        if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
1011
817
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1012
818
        else:
1013
819
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1014
820
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
1015
821
 
1016
822
 
1017
 
class TestSplitLines(tests.TestCase):
 
823
class TestSplitLines(TestCase):
1018
824
 
1019
825
    def test_split_unicode(self):
1020
826
        self.assertEqual([u'foo\n', u'bar\xae'],
1027
833
                         osutils.split_lines('foo\rbar\n'))
1028
834
 
1029
835
 
1030
 
class TestWalkDirs(tests.TestCaseInTempDir):
1031
 
 
1032
 
    def assertExpectedBlocks(self, expected, result):
1033
 
        self.assertEqual(expected,
1034
 
                         [(dirinfo, [line[0:3] for line in block])
1035
 
                          for dirinfo, block in result])
 
836
class TestWalkDirs(TestCaseInTempDir):
1036
837
 
1037
838
    def test_walkdirs(self):
1038
839
        tree = [
1071
872
            result.append((dirdetail, dirblock))
1072
873
 
1073
874
        self.assertTrue(found_bzrdir)
1074
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
875
        self.assertEqual(expected_dirblocks,
 
876
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1075
877
        # you can search a subdir only, with a supplied prefix.
1076
878
        result = []
1077
879
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1078
880
            result.append(dirblock)
1079
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
881
        self.assertEqual(expected_dirblocks[1:],
 
882
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1080
883
 
1081
884
    def test_walkdirs_os_error(self):
1082
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
 
885
        # <https://bugs.edge.launchpad.net/bzr/+bug/338653>
1083
886
        # Pyrex readdir didn't raise useful messages if it had an error
1084
887
        # reading the directory
1085
888
        if sys.platform == 'win32':
1086
889
            raise tests.TestNotApplicable(
1087
890
                "readdir IOError not tested on win32")
1088
 
        self.requireFeature(features.not_running_as_root)
1089
891
        os.mkdir("test-unreadable")
1090
892
        os.chmod("test-unreadable", 0000)
1091
893
        # must chmod it back so that it can be removed
1092
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
 
894
        self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
1093
895
        # The error is not raised until the generator is actually evaluated.
1094
896
        # (It would be ok if it happened earlier but at the moment it
1095
897
        # doesn't.)
1099
901
        # Ensure the message contains the file name
1100
902
        self.assertContainsRe(str(e), "\./test-unreadable")
1101
903
 
1102
 
 
1103
 
    def test_walkdirs_encoding_error(self):
1104
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1105
 
        # walkdirs didn't raise a useful message when the filenames
1106
 
        # are not using the filesystem's encoding
1107
 
 
1108
 
        # require a bytestring based filesystem
1109
 
        self.requireFeature(features.ByteStringNamedFilesystem)
1110
 
 
1111
 
        tree = [
1112
 
            '.bzr',
1113
 
            '0file',
1114
 
            '1dir/',
1115
 
            '1dir/0file',
1116
 
            '1dir/1dir/',
1117
 
            '1file'
1118
 
            ]
1119
 
 
1120
 
        self.build_tree(tree)
1121
 
 
1122
 
        # rename the 1file to a latin-1 filename
1123
 
        os.rename("./1file", "\xe8file")
1124
 
        if "\xe8file" not in os.listdir("."):
1125
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1126
 
 
1127
 
        self._save_platform_info()
1128
 
        win32utils.winver = None # Avoid the win32 detection code
1129
 
        osutils._fs_enc = 'UTF-8'
1130
 
 
1131
 
        # this should raise on error
1132
 
        def attempt():
1133
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1134
 
                pass
1135
 
 
1136
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1137
 
 
1138
904
    def test__walkdirs_utf8(self):
1139
905
        tree = [
1140
906
            '.bzr',
1172
938
            result.append((dirdetail, dirblock))
1173
939
 
1174
940
        self.assertTrue(found_bzrdir)
1175
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1176
 
 
 
941
        self.assertEqual(expected_dirblocks,
 
942
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1177
943
        # you can search a subdir only, with a supplied prefix.
1178
944
        result = []
1179
945
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1180
946
            result.append(dirblock)
1181
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
947
        self.assertEqual(expected_dirblocks[1:],
 
948
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1182
949
 
1183
950
    def _filter_out_stat(self, result):
1184
951
        """Filter out the stat value from the walkdirs result"""
1190
957
            dirblock[:] = new_dirblock
1191
958
 
1192
959
    def _save_platform_info(self):
1193
 
        self.overrideAttr(win32utils, 'winver')
1194
 
        self.overrideAttr(osutils, '_fs_enc')
1195
 
        self.overrideAttr(osutils, '_selected_dir_reader')
 
960
        cur_winver = win32utils.winver
 
961
        cur_fs_enc = osutils._fs_enc
 
962
        cur_dir_reader = osutils._selected_dir_reader
 
963
        def restore():
 
964
            win32utils.winver = cur_winver
 
965
            osutils._fs_enc = cur_fs_enc
 
966
            osutils._selected_dir_reader = cur_dir_reader
 
967
        self.addCleanup(restore)
1196
968
 
1197
 
    def assertDirReaderIs(self, expected):
 
969
    def assertReadFSDirIs(self, expected):
1198
970
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1199
971
        # Force it to redetect
1200
972
        osutils._selected_dir_reader = None
1207
979
        self._save_platform_info()
1208
980
        win32utils.winver = None # Avoid the win32 detection code
1209
981
        osutils._fs_enc = 'UTF-8'
1210
 
        self.assertDirReaderIs(
1211
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
982
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1212
983
 
1213
984
    def test_force_walkdirs_utf8_fs_ascii(self):
1214
985
        self.requireFeature(UTF8DirReaderFeature)
1215
986
        self._save_platform_info()
1216
987
        win32utils.winver = None # Avoid the win32 detection code
1217
988
        osutils._fs_enc = 'US-ASCII'
1218
 
        self.assertDirReaderIs(
1219
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
989
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1220
990
 
1221
991
    def test_force_walkdirs_utf8_fs_ANSI(self):
1222
992
        self.requireFeature(UTF8DirReaderFeature)
1223
993
        self._save_platform_info()
1224
994
        win32utils.winver = None # Avoid the win32 detection code
1225
995
        osutils._fs_enc = 'ANSI_X3.4-1968'
1226
 
        self.assertDirReaderIs(
1227
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
996
        self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
1228
997
 
1229
998
    def test_force_walkdirs_utf8_fs_latin1(self):
1230
999
        self._save_platform_info()
1231
1000
        win32utils.winver = None # Avoid the win32 detection code
1232
1001
        osutils._fs_enc = 'latin1'
1233
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
1002
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1234
1003
 
1235
1004
    def test_force_walkdirs_utf8_nt(self):
1236
1005
        # Disabled because the thunk of the whole walkdirs api is disabled.
1237
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1006
        self.requireFeature(Win32ReadDirFeature)
1238
1007
        self._save_platform_info()
1239
1008
        win32utils.winver = 'Windows NT'
1240
1009
        from bzrlib._walkdirs_win32 import Win32ReadDir
1241
 
        self.assertDirReaderIs(Win32ReadDir)
 
1010
        self.assertReadFSDirIs(Win32ReadDir)
1242
1011
 
1243
1012
    def test_force_walkdirs_utf8_98(self):
1244
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
1013
        self.requireFeature(Win32ReadDirFeature)
1245
1014
        self._save_platform_info()
1246
1015
        win32utils.winver = 'Windows 98'
1247
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
1016
        self.assertReadFSDirIs(osutils.UnicodeDirReader)
1248
1017
 
1249
1018
    def test_unicode_walkdirs(self):
1250
1019
        """Walkdirs should always return unicode paths."""
1251
 
        self.requireFeature(features.UnicodeFilenameFeature)
1252
1020
        name0 = u'0file-\xb6'
1253
1021
        name1 = u'1dir-\u062c\u0648'
1254
1022
        name2 = u'2file-\u0633'
1259
1027
            name1 + '/' + name1 + '/',
1260
1028
            name2,
1261
1029
            ]
1262
 
        self.build_tree(tree)
 
1030
        try:
 
1031
            self.build_tree(tree)
 
1032
        except UnicodeError:
 
1033
            raise TestSkipped('Could not represent Unicode chars'
 
1034
                              ' in current encoding.')
1263
1035
        expected_dirblocks = [
1264
1036
                ((u'', u'.'),
1265
1037
                 [(name0, name0, 'file', './' + name0),
1291
1063
 
1292
1064
        The abspath portion might be in unicode or utf-8
1293
1065
        """
1294
 
        self.requireFeature(features.UnicodeFilenameFeature)
1295
1066
        name0 = u'0file-\xb6'
1296
1067
        name1 = u'1dir-\u062c\u0648'
1297
1068
        name2 = u'2file-\u0633'
1302
1073
            name1 + '/' + name1 + '/',
1303
1074
            name2,
1304
1075
            ]
1305
 
        self.build_tree(tree)
 
1076
        try:
 
1077
            self.build_tree(tree)
 
1078
        except UnicodeError:
 
1079
            raise TestSkipped('Could not represent Unicode chars'
 
1080
                              ' in current encoding.')
1306
1081
        name0 = name0.encode('utf8')
1307
1082
        name1 = name1.encode('utf8')
1308
1083
        name2 = name2.encode('utf8')
1352
1127
 
1353
1128
        The abspath portion should be in unicode
1354
1129
        """
1355
 
        self.requireFeature(features.UnicodeFilenameFeature)
1356
1130
        # Use the unicode reader. TODO: split into driver-and-driven unit
1357
1131
        # tests.
1358
1132
        self._save_platform_info()
1367
1141
            name1u + '/' + name1u + '/',
1368
1142
            name2u,
1369
1143
            ]
1370
 
        self.build_tree(tree)
 
1144
        try:
 
1145
            self.build_tree(tree)
 
1146
        except UnicodeError:
 
1147
            raise TestSkipped('Could not represent Unicode chars'
 
1148
                              ' in current encoding.')
1371
1149
        name0 = name0u.encode('utf8')
1372
1150
        name1 = name1u.encode('utf8')
1373
1151
        name2 = name2u.encode('utf8')
1398
1176
        self.assertEqual(expected_dirblocks, result)
1399
1177
 
1400
1178
    def test__walkdirs_utf8_win32readdir(self):
1401
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1402
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1179
        self.requireFeature(Win32ReadDirFeature)
 
1180
        self.requireFeature(tests.UnicodeFilenameFeature)
1403
1181
        from bzrlib._walkdirs_win32 import Win32ReadDir
1404
1182
        self._save_platform_info()
1405
1183
        osutils._selected_dir_reader = Win32ReadDir()
1455
1233
 
1456
1234
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1457
1235
        """make sure our Stat values are valid"""
1458
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1459
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1236
        self.requireFeature(Win32ReadDirFeature)
 
1237
        self.requireFeature(tests.UnicodeFilenameFeature)
1460
1238
        from bzrlib._walkdirs_win32 import Win32ReadDir
1461
1239
        name0u = u'0file-\xb6'
1462
1240
        name0 = name0u.encode('utf8')
1479
1257
 
1480
1258
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1481
1259
        """make sure our Stat values are valid"""
1482
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1483
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
1260
        self.requireFeature(Win32ReadDirFeature)
 
1261
        self.requireFeature(tests.UnicodeFilenameFeature)
1484
1262
        from bzrlib._walkdirs_win32 import Win32ReadDir
1485
1263
        name0u = u'0dir-\u062c\u0648'
1486
1264
        name0 = name0u.encode('utf8')
1570
1348
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1571
1349
 
1572
1350
 
1573
 
class TestCopyTree(tests.TestCaseInTempDir):
 
1351
class TestCopyTree(TestCaseInTempDir):
1574
1352
 
1575
1353
    def test_copy_basic_tree(self):
1576
1354
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1586
1364
        self.assertEqual(['c'], os.listdir('target/b'))
1587
1365
 
1588
1366
    def test_copy_tree_symlinks(self):
1589
 
        self.requireFeature(features.SymlinkFeature)
 
1367
        self.requireFeature(SymlinkFeature)
1590
1368
        self.build_tree(['source/'])
1591
1369
        os.symlink('a/generic/path', 'source/lnk')
1592
1370
        osutils.copy_tree('source', 'target')
1617
1395
                          ('d', 'source/b', 'target/b'),
1618
1396
                          ('f', 'source/b/c', 'target/b/c'),
1619
1397
                         ], processed_files)
1620
 
        self.assertPathDoesNotExist('target')
 
1398
        self.failIfExists('target')
1621
1399
        if osutils.has_symlinks():
1622
1400
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1623
1401
 
1624
1402
 
1625
 
class TestSetUnsetEnv(tests.TestCase):
 
1403
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
1404
# [bialix] 2006/12/26
 
1405
 
 
1406
 
 
1407
class TestSetUnsetEnv(TestCase):
1626
1408
    """Test updating the environment"""
1627
1409
 
1628
1410
    def setUp(self):
1634
1416
        def cleanup():
1635
1417
            if 'BZR_TEST_ENV_VAR' in os.environ:
1636
1418
                del os.environ['BZR_TEST_ENV_VAR']
 
1419
 
1637
1420
        self.addCleanup(cleanup)
1638
1421
 
1639
1422
    def test_set(self):
1654
1437
 
1655
1438
        So Unicode strings must be encoded.
1656
1439
        """
1657
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
1440
        uni_val, env_val = probe_unicode_in_user_encoding()
1658
1441
        if uni_val is None:
1659
 
            raise tests.TestSkipped(
1660
 
                'Cannot find a unicode character that works in encoding %s'
1661
 
                % (osutils.get_user_encoding(),))
 
1442
            raise TestSkipped('Cannot find a unicode character that works in'
 
1443
                              ' encoding %s' % (osutils.get_user_encoding(),))
1662
1444
 
1663
1445
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1664
1446
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1669
1451
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1670
1452
        self.assertEqual('foo', old)
1671
1453
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1672
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1673
 
 
1674
 
 
1675
 
class TestSizeShaFile(tests.TestCaseInTempDir):
 
1454
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1455
 
 
1456
 
 
1457
class TestLocalTimeOffset(TestCase):
 
1458
 
 
1459
    def test_local_time_offset(self):
 
1460
        """Test that local_time_offset() returns a sane value."""
 
1461
        offset = osutils.local_time_offset()
 
1462
        self.assertTrue(isinstance(offset, int))
 
1463
        # Test that the offset is no more than a eighteen hours in
 
1464
        # either direction.
 
1465
        # Time zone handling is system specific, so it is difficult to
 
1466
        # do more specific tests, but a value outside of this range is
 
1467
        # probably wrong.
 
1468
        eighteen_hours = 18 * 3600
 
1469
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1470
 
 
1471
    def test_local_time_offset_with_timestamp(self):
 
1472
        """Test that local_time_offset() works with a timestamp."""
 
1473
        offset = osutils.local_time_offset(1000000000.1234567)
 
1474
        self.assertTrue(isinstance(offset, int))
 
1475
        eighteen_hours = 18 * 3600
 
1476
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1477
 
 
1478
 
 
1479
class TestSizeShaFile(TestCaseInTempDir):
1676
1480
 
1677
1481
    def test_sha_empty(self):
1678
1482
        self.build_tree_contents([('foo', '')])
1687
1491
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1688
1492
        self.build_tree_contents([('foo', text)])
1689
1493
        expected_sha = osutils.sha_string(text)
1690
 
        f = open('foo', 'rb')
 
1494
        f = open('foo')
1691
1495
        self.addCleanup(f.close)
1692
1496
        size, sha = osutils.size_sha_file(f)
1693
1497
        self.assertEqual(38, size)
1694
1498
        self.assertEqual(expected_sha, sha)
1695
1499
 
1696
1500
 
1697
 
class TestShaFileByName(tests.TestCaseInTempDir):
 
1501
class TestShaFileByName(TestCaseInTempDir):
1698
1502
 
1699
1503
    def test_sha_empty(self):
1700
1504
        self.build_tree_contents([('foo', '')])
1708
1512
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1709
1513
 
1710
1514
 
1711
 
class TestResourceLoading(tests.TestCaseInTempDir):
 
1515
class TestResourceLoading(TestCaseInTempDir):
1712
1516
 
1713
1517
    def test_resource_string(self):
1714
1518
        # test resource in bzrlib
1724
1528
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1725
1529
 
1726
1530
 
1727
 
class TestReCompile(tests.TestCase):
1728
 
 
1729
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1730
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1731
 
            osutils.re_compile_checked, *args, **kwargs)
 
1531
class TestReCompile(TestCase):
1732
1532
 
1733
1533
    def test_re_compile_checked(self):
1734
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
 
1534
        r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1735
1535
        self.assertTrue(r.match('aaaa'))
1736
1536
        self.assertTrue(r.match('aAaA'))
1737
1537
 
1738
1538
    def test_re_compile_checked_error(self):
1739
1539
        # like https://bugs.launchpad.net/bzr/+bug/251352
1740
 
 
1741
 
        # Due to possible test isolation error, re.compile is not lazy at
1742
 
        # this point. We re-install lazy compile.
1743
 
        lazy_regex.install_lazy_compile()
1744
1540
        err = self.assertRaises(
1745
1541
            errors.BzrCommandError,
1746
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
 
1542
            osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1747
1543
        self.assertEqual(
1748
 
            'Invalid regular expression in test case: '
1749
 
            '"*" nothing to repeat',
 
1544
            "Invalid regular expression in test case: '*': "
 
1545
            "nothing to repeat",
1750
1546
            str(err))
1751
 
 
1752
 
 
1753
 
class TestDirReader(tests.TestCaseInTempDir):
1754
 
 
1755
 
    scenarios = dir_reader_scenarios()
1756
 
 
1757
 
    # Set by load_tests
1758
 
    _dir_reader_class = None
1759
 
    _native_to_unicode = None
1760
 
 
1761
 
    def setUp(self):
1762
 
        tests.TestCaseInTempDir.setUp(self)
1763
 
        self.overrideAttr(osutils,
1764
 
                          '_selected_dir_reader', self._dir_reader_class())
1765
 
 
1766
 
    def _get_ascii_tree(self):
1767
 
        tree = [
1768
 
            '0file',
1769
 
            '1dir/',
1770
 
            '1dir/0file',
1771
 
            '1dir/1dir/',
1772
 
            '2file'
1773
 
            ]
1774
 
        expected_dirblocks = [
1775
 
                (('', '.'),
1776
 
                 [('0file', '0file', 'file'),
1777
 
                  ('1dir', '1dir', 'directory'),
1778
 
                  ('2file', '2file', 'file'),
1779
 
                 ]
1780
 
                ),
1781
 
                (('1dir', './1dir'),
1782
 
                 [('1dir/0file', '0file', 'file'),
1783
 
                  ('1dir/1dir', '1dir', 'directory'),
1784
 
                 ]
1785
 
                ),
1786
 
                (('1dir/1dir', './1dir/1dir'),
1787
 
                 [
1788
 
                 ]
1789
 
                ),
1790
 
            ]
1791
 
        return tree, expected_dirblocks
1792
 
 
1793
 
    def test_walk_cur_dir(self):
1794
 
        tree, expected_dirblocks = self._get_ascii_tree()
1795
 
        self.build_tree(tree)
1796
 
        result = list(osutils._walkdirs_utf8('.'))
1797
 
        # Filter out stat and abspath
1798
 
        self.assertEqual(expected_dirblocks,
1799
 
                         [(dirinfo, [line[0:3] for line in block])
1800
 
                          for dirinfo, block in result])
1801
 
 
1802
 
    def test_walk_sub_dir(self):
1803
 
        tree, expected_dirblocks = self._get_ascii_tree()
1804
 
        self.build_tree(tree)
1805
 
        # you can search a subdir only, with a supplied prefix.
1806
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1807
 
        # Filter out stat and abspath
1808
 
        self.assertEqual(expected_dirblocks[1:],
1809
 
                         [(dirinfo, [line[0:3] for line in block])
1810
 
                          for dirinfo, block in result])
1811
 
 
1812
 
    def _get_unicode_tree(self):
1813
 
        name0u = u'0file-\xb6'
1814
 
        name1u = u'1dir-\u062c\u0648'
1815
 
        name2u = u'2file-\u0633'
1816
 
        tree = [
1817
 
            name0u,
1818
 
            name1u + '/',
1819
 
            name1u + '/' + name0u,
1820
 
            name1u + '/' + name1u + '/',
1821
 
            name2u,
1822
 
            ]
1823
 
        name0 = name0u.encode('UTF-8')
1824
 
        name1 = name1u.encode('UTF-8')
1825
 
        name2 = name2u.encode('UTF-8')
1826
 
        expected_dirblocks = [
1827
 
                (('', '.'),
1828
 
                 [(name0, name0, 'file', './' + name0u),
1829
 
                  (name1, name1, 'directory', './' + name1u),
1830
 
                  (name2, name2, 'file', './' + name2u),
1831
 
                 ]
1832
 
                ),
1833
 
                ((name1, './' + name1u),
1834
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1835
 
                                                        + '/' + name0u),
1836
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1837
 
                                                            + '/' + name1u),
1838
 
                 ]
1839
 
                ),
1840
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1841
 
                 [
1842
 
                 ]
1843
 
                ),
1844
 
            ]
1845
 
        return tree, expected_dirblocks
1846
 
 
1847
 
    def _filter_out(self, raw_dirblocks):
1848
 
        """Filter out a walkdirs_utf8 result.
1849
 
 
1850
 
        stat field is removed, all native paths are converted to unicode
1851
 
        """
1852
 
        filtered_dirblocks = []
1853
 
        for dirinfo, block in raw_dirblocks:
1854
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1855
 
            details = []
1856
 
            for line in block:
1857
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1858
 
            filtered_dirblocks.append((dirinfo, details))
1859
 
        return filtered_dirblocks
1860
 
 
1861
 
    def test_walk_unicode_tree(self):
1862
 
        self.requireFeature(features.UnicodeFilenameFeature)
1863
 
        tree, expected_dirblocks = self._get_unicode_tree()
1864
 
        self.build_tree(tree)
1865
 
        result = list(osutils._walkdirs_utf8('.'))
1866
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1867
 
 
1868
 
    def test_symlink(self):
1869
 
        self.requireFeature(features.SymlinkFeature)
1870
 
        self.requireFeature(features.UnicodeFilenameFeature)
1871
 
        target = u'target\N{Euro Sign}'
1872
 
        link_name = u'l\N{Euro Sign}nk'
1873
 
        os.symlink(target, link_name)
1874
 
        target_utf8 = target.encode('UTF-8')
1875
 
        link_name_utf8 = link_name.encode('UTF-8')
1876
 
        expected_dirblocks = [
1877
 
                (('', '.'),
1878
 
                 [(link_name_utf8, link_name_utf8,
1879
 
                   'symlink', './' + link_name),],
1880
 
                 )]
1881
 
        result = list(osutils._walkdirs_utf8('.'))
1882
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1883
 
 
1884
 
 
1885
 
class TestReadLink(tests.TestCaseInTempDir):
1886
 
    """Exposes os.readlink() problems and the osutils solution.
1887
 
 
1888
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1889
 
    unicode string will be returned if a unicode string is passed.
1890
 
 
1891
 
    But prior python versions failed to properly encode the passed unicode
1892
 
    string.
1893
 
    """
1894
 
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1895
 
 
1896
 
    def setUp(self):
1897
 
        super(tests.TestCaseInTempDir, self).setUp()
1898
 
        self.link = u'l\N{Euro Sign}ink'
1899
 
        self.target = u'targe\N{Euro Sign}t'
1900
 
        os.symlink(self.target, self.link)
1901
 
 
1902
 
    def test_os_readlink_link_encoding(self):
1903
 
        self.assertEquals(self.target,  os.readlink(self.link))
1904
 
 
1905
 
    def test_os_readlink_link_decoding(self):
1906
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
1907
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
1908
 
 
1909
 
 
1910
 
class TestConcurrency(tests.TestCase):
1911
 
 
1912
 
    def setUp(self):
1913
 
        super(TestConcurrency, self).setUp()
1914
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
1915
 
 
1916
 
    def test_local_concurrency(self):
1917
 
        concurrency = osutils.local_concurrency()
1918
 
        self.assertIsInstance(concurrency, int)
1919
 
 
1920
 
    def test_local_concurrency_environment_variable(self):
1921
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
1922
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
1923
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
1924
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
1925
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
1926
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1927
 
 
1928
 
    def test_option_concurrency(self):
1929
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
1930
 
        self.run_bzr('rocks --concurrency 42')
1931
 
        # Command line overrides environment variable
1932
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
1933
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
1934
 
 
1935
 
 
1936
 
class TestFailedToLoadExtension(tests.TestCase):
1937
 
 
1938
 
    def _try_loading(self):
1939
 
        try:
1940
 
            import bzrlib._fictional_extension_py
1941
 
        except ImportError, e:
1942
 
            osutils.failed_to_load_extension(e)
1943
 
            return True
1944
 
 
1945
 
    def setUp(self):
1946
 
        super(TestFailedToLoadExtension, self).setUp()
1947
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
1948
 
 
1949
 
    def test_failure_to_load(self):
1950
 
        self._try_loading()
1951
 
        self.assertLength(1, osutils._extension_load_failures)
1952
 
        self.assertEquals(osutils._extension_load_failures[0],
1953
 
            "No module named _fictional_extension_py")
1954
 
 
1955
 
    def test_report_extension_load_failures_no_warning(self):
1956
 
        self.assertTrue(self._try_loading())
1957
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
1958
 
        # it used to give a Python warning; it no longer does
1959
 
        self.assertLength(0, warnings)
1960
 
 
1961
 
    def test_report_extension_load_failures_message(self):
1962
 
        log = StringIO()
1963
 
        trace.push_log_file(log)
1964
 
        self.assertTrue(self._try_loading())
1965
 
        osutils.report_extension_load_failures()
1966
 
        self.assertContainsRe(
1967
 
            log.getvalue(),
1968
 
            r"bzr: warning: some compiled extensions could not be loaded; "
1969
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
1970
 
            )
1971
 
 
1972
 
 
1973
 
class TestTerminalWidth(tests.TestCase):
1974
 
 
1975
 
    def setUp(self):
1976
 
        tests.TestCase.setUp(self)
1977
 
        self._orig_terminal_size_state = osutils._terminal_size_state
1978
 
        self._orig_first_terminal_size = osutils._first_terminal_size
1979
 
        self.addCleanup(self.restore_osutils_globals)
1980
 
        osutils._terminal_size_state = 'no_data'
1981
 
        osutils._first_terminal_size = None
1982
 
 
1983
 
    def restore_osutils_globals(self):
1984
 
        osutils._terminal_size_state = self._orig_terminal_size_state
1985
 
        osutils._first_terminal_size = self._orig_first_terminal_size
1986
 
 
1987
 
    def replace_stdout(self, new):
1988
 
        self.overrideAttr(sys, 'stdout', new)
1989
 
 
1990
 
    def replace__terminal_size(self, new):
1991
 
        self.overrideAttr(osutils, '_terminal_size', new)
1992
 
 
1993
 
    def set_fake_tty(self):
1994
 
 
1995
 
        class I_am_a_tty(object):
1996
 
            def isatty(self):
1997
 
                return True
1998
 
 
1999
 
        self.replace_stdout(I_am_a_tty())
2000
 
 
2001
 
    def test_default_values(self):
2002
 
        self.assertEqual(80, osutils.default_terminal_width)
2003
 
 
2004
 
    def test_defaults_to_BZR_COLUMNS(self):
2005
 
        # BZR_COLUMNS is set by the test framework
2006
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2007
 
        self.overrideEnv('BZR_COLUMNS', '12')
2008
 
        self.assertEqual(12, osutils.terminal_width())
2009
 
 
2010
 
    def test_BZR_COLUMNS_0_no_limit(self):
2011
 
        self.overrideEnv('BZR_COLUMNS', '0')
2012
 
        self.assertEqual(None, osutils.terminal_width())
2013
 
 
2014
 
    def test_falls_back_to_COLUMNS(self):
2015
 
        self.overrideEnv('BZR_COLUMNS', None)
2016
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
2017
 
        self.set_fake_tty()
2018
 
        self.overrideEnv('COLUMNS', '42')
2019
 
        self.assertEqual(42, osutils.terminal_width())
2020
 
 
2021
 
    def test_tty_default_without_columns(self):
2022
 
        self.overrideEnv('BZR_COLUMNS', None)
2023
 
        self.overrideEnv('COLUMNS', None)
2024
 
 
2025
 
        def terminal_size(w, h):
2026
 
            return 42, 42
2027
 
 
2028
 
        self.set_fake_tty()
2029
 
        # We need to override the osutils definition as it depends on the
2030
 
        # running environment that we can't control (PQM running without a
2031
 
        # controlling terminal is one example).
2032
 
        self.replace__terminal_size(terminal_size)
2033
 
        self.assertEqual(42, osutils.terminal_width())
2034
 
 
2035
 
    def test_non_tty_default_without_columns(self):
2036
 
        self.overrideEnv('BZR_COLUMNS', None)
2037
 
        self.overrideEnv('COLUMNS', None)
2038
 
        self.replace_stdout(None)
2039
 
        self.assertEqual(None, osutils.terminal_width())
2040
 
 
2041
 
    def test_no_TIOCGWINSZ(self):
2042
 
        self.requireFeature(term_ios_feature)
2043
 
        termios = term_ios_feature.module
2044
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2045
 
        try:
2046
 
            orig = termios.TIOCGWINSZ
2047
 
        except AttributeError:
2048
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2049
 
            pass
2050
 
        else:
2051
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2052
 
            del termios.TIOCGWINSZ
2053
 
        self.overrideEnv('BZR_COLUMNS', None)
2054
 
        self.overrideEnv('COLUMNS', None)
2055
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2056
 
        osutils.terminal_width()
2057
 
 
2058
 
 
2059
 
class TestCreationOps(tests.TestCaseInTempDir):
2060
 
    _test_needs_features = [features.chown_feature]
2061
 
 
2062
 
    def setUp(self):
2063
 
        tests.TestCaseInTempDir.setUp(self)
2064
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2065
 
 
2066
 
        # params set by call to _dummy_chown
2067
 
        self.path = self.uid = self.gid = None
2068
 
 
2069
 
    def _dummy_chown(self, path, uid, gid):
2070
 
        self.path, self.uid, self.gid = path, uid, gid
2071
 
 
2072
 
    def test_copy_ownership_from_path(self):
2073
 
        """copy_ownership_from_path test with specified src."""
2074
 
        ownsrc = '/'
2075
 
        f = open('test_file', 'wt')
2076
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2077
 
 
2078
 
        s = os.stat(ownsrc)
2079
 
        self.assertEquals(self.path, 'test_file')
2080
 
        self.assertEquals(self.uid, s.st_uid)
2081
 
        self.assertEquals(self.gid, s.st_gid)
2082
 
 
2083
 
    def test_copy_ownership_nonesrc(self):
2084
 
        """copy_ownership_from_path test with src=None."""
2085
 
        f = open('test_file', 'wt')
2086
 
        # should use parent dir for permissions
2087
 
        osutils.copy_ownership_from_path('test_file')
2088
 
 
2089
 
        s = os.stat('..')
2090
 
        self.assertEquals(self.path, 'test_file')
2091
 
        self.assertEquals(self.uid, s.st_uid)
2092
 
        self.assertEquals(self.gid, s.st_gid)
2093
 
 
2094
 
 
2095
 
class TestGetuserUnicode(tests.TestCase):
2096
 
 
2097
 
    def test_ascii_user(self):
2098
 
        self.overrideEnv('LOGNAME', 'jrandom')
2099
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2100
 
 
2101
 
    def test_unicode_user(self):
2102
 
        ue = osutils.get_user_encoding()
2103
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2104
 
        if uni_val is None:
2105
 
            raise tests.TestSkipped(
2106
 
                'Cannot find a unicode character that works in encoding %s'
2107
 
                % (osutils.get_user_encoding(),))
2108
 
        uni_username = u'jrandom' + uni_val
2109
 
        encoded_username = uni_username.encode(ue)
2110
 
        self.overrideEnv('LOGNAME', encoded_username)
2111
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2112
 
        self.overrideEnv('LOGNAME', u'jrandom\xb6'.encode(ue))
2113
 
        self.assertEqual(u'jrandom\xb6', osutils.getuser_unicode())
2114
 
 
2115
 
    def test_no_username_bug_660174(self):
2116
 
        self.requireFeature(features.win32_feature)
2117
 
        for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
2118
 
            self.overrideEnv(name, None)
2119
 
        self.assertEqual(u'UNKNOWN', osutils.getuser_unicode())
2120
 
 
2121
 
 
2122
 
class TestBackupNames(tests.TestCase):
2123
 
 
2124
 
    def setUp(self):
2125
 
        super(TestBackupNames, self).setUp()
2126
 
        self.backups = []
2127
 
 
2128
 
    def backup_exists(self, name):
2129
 
        return name in self.backups
2130
 
 
2131
 
    def available_backup_name(self, name):
2132
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2133
 
        self.backups.append(backup_name)
2134
 
        return backup_name
2135
 
 
2136
 
    def assertBackupName(self, expected, name):
2137
 
        self.assertEqual(expected, self.available_backup_name(name))
2138
 
 
2139
 
    def test_empty(self):
2140
 
        self.assertBackupName('file.~1~', 'file')
2141
 
 
2142
 
    def test_existing(self):
2143
 
        self.available_backup_name('file')
2144
 
        self.available_backup_name('file')
2145
 
        self.assertBackupName('file.~3~', 'file')
2146
 
        # Empty slots are found, this is not a strict requirement and may be
2147
 
        # revisited if we test against all implementations.
2148
 
        self.backups.remove('file.~2~')
2149
 
        self.assertBackupName('file.~2~', 'file')
2150
 
 
2151
 
 
2152
 
class TestFindExecutableInPath(tests.TestCase):
2153
 
 
2154
 
    def test_windows(self):
2155
 
        if sys.platform != 'win32':
2156
 
            raise tests.TestSkipped('test requires win32')
2157
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2158
 
        self.assertTrue(
2159
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2160
 
        self.assertTrue(
2161
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2162
 
        self.assertTrue(
2163
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2164
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2165
 
 
2166
 
    def test_other(self):
2167
 
        if sys.platform == 'win32':
2168
 
            raise tests.TestSkipped('test requires non-win32')
2169
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2170
 
        self.assertTrue(
2171
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)