~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: 2008-05-01 11:25:12 UTC
  • mfrom: (3211.7.10 protocol-v3-doc)
  • Revision ID: pqm@pqm.ubuntu.com-20080501112512-b9lgs4w8r43evtn1
Add the smart protocol v3 specification to network-protocol.txt

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 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
19
 
from cStringIO import StringIO
20
19
import errno
21
20
import os
22
 
import re
23
 
import select
24
21
import socket
 
22
import stat
25
23
import sys
26
 
import tempfile
27
 
import time
28
24
 
 
25
import bzrlib
29
26
from bzrlib import (
30
27
    errors,
31
 
    lazy_regex,
32
28
    osutils,
33
 
    symbol_versioning,
34
 
    tests,
35
 
    trace,
36
29
    win32utils,
37
30
    )
 
31
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
32
from bzrlib.osutils import (
 
33
        is_inside_any,
 
34
        is_inside_or_parent_of_any,
 
35
        pathjoin,
 
36
        )
38
37
from bzrlib.tests import (
39
 
    features,
40
 
    file_utils,
41
 
    test__walkdirs_win32,
42
 
    )
43
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
44
 
 
45
 
 
46
 
class _UTF8DirReaderFeature(features.Feature):
47
 
 
48
 
    def _probe(self):
49
 
        try:
50
 
            from bzrlib import _readdir_pyx
51
 
            self.reader = _readdir_pyx.UTF8DirReader
52
 
            return True
53
 
        except ImportError:
54
 
            return False
55
 
 
56
 
    def feature_name(self):
57
 
        return 'bzrlib._readdir_pyx'
58
 
 
59
 
UTF8DirReaderFeature = features.ModuleAvailableFeature('bzrlib._readdir_pyx')
60
 
 
61
 
term_ios_feature = features.ModuleAvailableFeature('termios')
62
 
 
63
 
 
64
 
def _already_unicode(s):
65
 
    return s
66
 
 
67
 
 
68
 
def _utf8_to_unicode(s):
69
 
    return s.decode('UTF-8')
70
 
 
71
 
 
72
 
def dir_reader_scenarios():
73
 
    # For each dir reader we define:
74
 
 
75
 
    # - native_to_unicode: a function converting the native_abspath as returned
76
 
    #   by DirReader.read_dir to its unicode representation
77
 
 
78
 
    # UnicodeDirReader is the fallback, it should be tested on all platforms.
79
 
    scenarios = [('unicode',
80
 
                  dict(_dir_reader_class=osutils.UnicodeDirReader,
81
 
                       _native_to_unicode=_already_unicode))]
82
 
    # Some DirReaders are platform specific and even there they may not be
83
 
    # available.
84
 
    if UTF8DirReaderFeature.available():
85
 
        from bzrlib import _readdir_pyx
86
 
        scenarios.append(('utf8',
87
 
                          dict(_dir_reader_class=_readdir_pyx.UTF8DirReader,
88
 
                               _native_to_unicode=_utf8_to_unicode)))
89
 
 
90
 
    if test__walkdirs_win32.win32_readdir_feature.available():
91
 
        try:
92
 
            from bzrlib import _walkdirs_win32
93
 
            scenarios.append(
94
 
                ('win32',
95
 
                 dict(_dir_reader_class=_walkdirs_win32.Win32ReadDir,
96
 
                      _native_to_unicode=_already_unicode)))
97
 
        except ImportError:
98
 
            pass
99
 
    return scenarios
100
 
 
101
 
 
102
 
load_tests = load_tests_apply_scenarios
103
 
 
104
 
 
105
 
class TestContainsWhitespace(tests.TestCase):
 
38
        probe_unicode_in_user_encoding,
 
39
        StringIOWrapper,
 
40
        SymlinkFeature,
 
41
        TestCase,
 
42
        TestCaseInTempDir,
 
43
        TestSkipped,
 
44
        )
 
45
 
 
46
 
 
47
class TestOSUtils(TestCaseInTempDir):
106
48
 
107
49
    def test_contains_whitespace(self):
108
 
        self.assertTrue(osutils.contains_whitespace(u' '))
109
 
        self.assertTrue(osutils.contains_whitespace(u'hello there'))
110
 
        self.assertTrue(osutils.contains_whitespace(u'hellothere\n'))
111
 
        self.assertTrue(osutils.contains_whitespace(u'hello\nthere'))
112
 
        self.assertTrue(osutils.contains_whitespace(u'hello\rthere'))
113
 
        self.assertTrue(osutils.contains_whitespace(u'hello\tthere'))
 
50
        self.failUnless(osutils.contains_whitespace(u' '))
 
51
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
52
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
53
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
54
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
55
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
114
56
 
115
57
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
116
58
        # is whitespace, but we do not.
117
 
        self.assertFalse(osutils.contains_whitespace(u''))
118
 
        self.assertFalse(osutils.contains_whitespace(u'hellothere'))
119
 
        self.assertFalse(osutils.contains_whitespace(u'hello\xa0there'))
120
 
 
121
 
 
122
 
class TestRename(tests.TestCaseInTempDir):
123
 
 
124
 
    def create_file(self, filename, content):
125
 
        f = open(filename, 'wb')
126
 
        try:
127
 
            f.write(content)
128
 
        finally:
129
 
            f.close()
130
 
 
131
 
    def _fancy_rename(self, a, b):
132
 
        osutils.fancy_rename(a, b, rename_func=os.rename,
133
 
                             unlink_func=os.unlink)
 
59
        self.failIf(osutils.contains_whitespace(u''))
 
60
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
61
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
134
62
 
135
63
    def test_fancy_rename(self):
136
64
        # This should work everywhere
137
 
        self.create_file('a', 'something in a\n')
138
 
        self._fancy_rename('a', 'b')
139
 
        self.assertPathDoesNotExist('a')
140
 
        self.assertPathExists('b')
 
65
        def rename(a, b):
 
66
            osutils.fancy_rename(a, b,
 
67
                    rename_func=os.rename,
 
68
                    unlink_func=os.unlink)
 
69
 
 
70
        open('a', 'wb').write('something in a\n')
 
71
        rename('a', 'b')
 
72
        self.failIfExists('a')
 
73
        self.failUnlessExists('b')
141
74
        self.check_file_contents('b', 'something in a\n')
142
75
 
143
 
        self.create_file('a', 'new something in a\n')
144
 
        self._fancy_rename('b', 'a')
 
76
        open('a', 'wb').write('new something in a\n')
 
77
        rename('b', 'a')
145
78
 
146
79
        self.check_file_contents('a', 'something in a\n')
147
80
 
148
 
    def test_fancy_rename_fails_source_missing(self):
149
 
        # An exception should be raised, and the target should be left in place
150
 
        self.create_file('target', 'data in target\n')
151
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
152
 
                          'missingsource', 'target')
153
 
        self.assertPathExists('target')
154
 
        self.check_file_contents('target', 'data in target\n')
155
 
 
156
 
    def test_fancy_rename_fails_if_source_and_target_missing(self):
157
 
        self.assertRaises((IOError, OSError), self._fancy_rename,
158
 
                          'missingsource', 'missingtarget')
159
 
 
160
81
    def test_rename(self):
161
82
        # Rename should be semi-atomic on all platforms
162
 
        self.create_file('a', 'something in a\n')
 
83
        open('a', 'wb').write('something in a\n')
163
84
        osutils.rename('a', 'b')
164
 
        self.assertPathDoesNotExist('a')
165
 
        self.assertPathExists('b')
 
85
        self.failIfExists('a')
 
86
        self.failUnlessExists('b')
166
87
        self.check_file_contents('b', 'something in a\n')
167
88
 
168
 
        self.create_file('a', 'new something in a\n')
 
89
        open('a', 'wb').write('new something in a\n')
169
90
        osutils.rename('b', 'a')
170
91
 
171
92
        self.check_file_contents('a', 'something in a\n')
182
103
        shape = sorted(os.listdir('.'))
183
104
        self.assertEquals(['A', 'B'], shape)
184
105
 
185
 
    def test_rename_exception(self):
186
 
        try:
187
 
            osutils.rename('nonexistent_path', 'different_nonexistent_path')
188
 
        except OSError, e:
189
 
            self.assertEqual(e.old_filename, 'nonexistent_path')
190
 
            self.assertEqual(e.new_filename, 'different_nonexistent_path')
191
 
            self.assertTrue('nonexistent_path' in e.strerror)
192
 
            self.assertTrue('different_nonexistent_path' in e.strerror)
193
 
 
194
 
 
195
 
class TestRandChars(tests.TestCase):
196
 
 
197
106
    def test_01_rand_chars_empty(self):
198
107
        result = osutils.rand_chars(0)
199
108
        self.assertEqual(result, '')
204
113
        self.assertEqual(type(result), str)
205
114
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
206
115
 
207
 
 
208
 
class TestIsInside(tests.TestCase):
209
 
 
210
116
    def test_is_inside(self):
211
117
        is_inside = osutils.is_inside
212
118
        self.assertTrue(is_inside('src', 'src/foo.c'))
217
123
        self.assertTrue(is_inside('', 'foo.c'))
218
124
 
219
125
    def test_is_inside_any(self):
220
 
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
126
        SRC_FOO_C = pathjoin('src', 'foo.c')
221
127
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
222
128
                         (['src'], SRC_FOO_C),
223
129
                         (['src'], 'src'),
224
130
                         ]:
225
 
            self.assert_(osutils.is_inside_any(dirs, fn))
 
131
            self.assert_(is_inside_any(dirs, fn))
226
132
        for dirs, fn in [(['src'], 'srccontrol'),
227
133
                         (['src'], 'srccontrol/foo')]:
228
 
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
134
            self.assertFalse(is_inside_any(dirs, fn))
229
135
 
230
136
    def test_is_inside_or_parent_of_any(self):
231
137
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
234
140
                         (['src/bar.c', 'bla/foo.c'], 'src'),
235
141
                         (['src'], 'src'),
236
142
                         ]:
237
 
            self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
238
 
 
 
143
            self.assert_(is_inside_or_parent_of_any(dirs, fn))
 
144
            
239
145
        for dirs, fn in [(['src'], 'srccontrol'),
240
146
                         (['srccontrol/foo.c'], 'src'),
241
147
                         (['src'], 'srccontrol/foo')]:
242
 
            self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
243
 
 
244
 
 
245
 
class TestLstat(tests.TestCaseInTempDir):
246
 
 
247
 
    def test_lstat_matches_fstat(self):
248
 
        # On Windows, lstat and fstat don't always agree, primarily in the
249
 
        # 'st_ino' and 'st_dev' fields. So we force them to be '0' in our
250
 
        # custom implementation.
251
 
        if sys.platform == 'win32':
252
 
            # We only have special lstat/fstat if we have the extension.
253
 
            # Without it, we may end up re-reading content when we don't have
254
 
            # to, but otherwise it doesn't effect correctness.
255
 
            self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
256
 
        f = open('test-file.txt', 'wb')
257
 
        self.addCleanup(f.close)
258
 
        f.write('some content\n')
259
 
        f.flush()
260
 
        self.assertEqualStat(osutils.fstat(f.fileno()),
261
 
                             osutils.lstat('test-file.txt'))
262
 
 
263
 
 
264
 
class TestRmTree(tests.TestCaseInTempDir):
 
148
            self.assertFalse(is_inside_or_parent_of_any(dirs, fn))
265
149
 
266
150
    def test_rmtree(self):
267
151
        # Check to remove tree with read-only files/dirs
278
162
 
279
163
        osutils.rmtree('dir')
280
164
 
281
 
        self.assertPathDoesNotExist('dir/file')
282
 
        self.assertPathDoesNotExist('dir')
283
 
 
284
 
 
285
 
class TestDeleteAny(tests.TestCaseInTempDir):
286
 
 
287
 
    def test_delete_any_readonly(self):
288
 
        # from <https://bugs.launchpad.net/bzr/+bug/218206>
289
 
        self.build_tree(['d/', 'f'])
290
 
        osutils.make_readonly('d')
291
 
        osutils.make_readonly('f')
292
 
 
293
 
        osutils.delete_any('f')
294
 
        osutils.delete_any('d')
295
 
 
296
 
 
297
 
class TestKind(tests.TestCaseInTempDir):
 
165
        self.failIfExists('dir/file')
 
166
        self.failIfExists('dir')
298
167
 
299
168
    def test_file_kind(self):
300
169
        self.build_tree(['file', 'dir/'])
303
172
        if osutils.has_symlinks():
304
173
            os.symlink('symlink', 'symlink')
305
174
            self.assertEquals('symlink', osutils.file_kind('symlink'))
306
 
 
 
175
        
307
176
        # TODO: jam 20060529 Test a block device
308
177
        try:
309
178
            os.lstat('/dev/null')
331
200
                os.remove('socket')
332
201
 
333
202
    def test_kind_marker(self):
334
 
        self.assertEqual("", osutils.kind_marker("file"))
335
 
        self.assertEqual("/", osutils.kind_marker('directory'))
336
 
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
337
 
        self.assertEqual("@", osutils.kind_marker("symlink"))
338
 
        self.assertEqual("+", osutils.kind_marker("tree-reference"))
339
 
        self.assertEqual("", osutils.kind_marker("fifo"))
340
 
        self.assertEqual("", osutils.kind_marker("socket"))
341
 
        self.assertEqual("", osutils.kind_marker("unknown"))
342
 
 
343
 
 
344
 
class TestUmask(tests.TestCaseInTempDir):
 
203
        self.assertEqual(osutils.kind_marker('file'), '')
 
204
        self.assertEqual(osutils.kind_marker('directory'), '/')
 
205
        self.assertEqual(osutils.kind_marker('symlink'), '@')
 
206
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
345
207
 
346
208
    def test_get_umask(self):
347
209
        if sys.platform == 'win32':
350
212
            return
351
213
 
352
214
        orig_umask = osutils.get_umask()
353
 
        self.addCleanup(os.umask, orig_umask)
354
 
        os.umask(0222)
355
 
        self.assertEqual(0222, osutils.get_umask())
356
 
        os.umask(0022)
357
 
        self.assertEqual(0022, osutils.get_umask())
358
 
        os.umask(0002)
359
 
        self.assertEqual(0002, osutils.get_umask())
360
 
        os.umask(0027)
361
 
        self.assertEqual(0027, osutils.get_umask())
362
 
 
363
 
 
364
 
class TestDateTime(tests.TestCase):
 
215
        try:
 
216
            os.umask(0222)
 
217
            self.assertEqual(0222, osutils.get_umask())
 
218
            os.umask(0022)
 
219
            self.assertEqual(0022, osutils.get_umask())
 
220
            os.umask(0002)
 
221
            self.assertEqual(0002, osutils.get_umask())
 
222
            os.umask(0027)
 
223
            self.assertEqual(0027, osutils.get_umask())
 
224
        finally:
 
225
            os.umask(orig_umask)
365
226
 
366
227
    def assertFormatedDelta(self, expected, seconds):
367
228
        """Assert osutils.format_delta formats as expected"""
402
263
    def test_format_date(self):
403
264
        self.assertRaises(errors.UnsupportedTimezoneFormat,
404
265
            osutils.format_date, 0, timezone='foo')
405
 
        self.assertIsInstance(osutils.format_date(0), str)
406
 
        self.assertIsInstance(osutils.format_local_date(0), unicode)
407
 
        # Testing for the actual value of the local weekday without
408
 
        # duplicating the code from format_date is difficult.
409
 
        # Instead blackbox.test_locale should check for localized
410
 
        # dates once they do occur in output strings.
411
 
 
412
 
    def test_format_date_with_offset_in_original_timezone(self):
413
 
        self.assertEqual("Thu 1970-01-01 00:00:00 +0000",
414
 
            osutils.format_date_with_offset_in_original_timezone(0))
415
 
        self.assertEqual("Fri 1970-01-02 03:46:40 +0000",
416
 
            osutils.format_date_with_offset_in_original_timezone(100000))
417
 
        self.assertEqual("Fri 1970-01-02 05:46:40 +0200",
418
 
            osutils.format_date_with_offset_in_original_timezone(100000, 7200))
419
 
 
420
 
    def test_local_time_offset(self):
421
 
        """Test that local_time_offset() returns a sane value."""
422
 
        offset = osutils.local_time_offset()
423
 
        self.assertTrue(isinstance(offset, int))
424
 
        # Test that the offset is no more than a eighteen hours in
425
 
        # either direction.
426
 
        # Time zone handling is system specific, so it is difficult to
427
 
        # do more specific tests, but a value outside of this range is
428
 
        # probably wrong.
429
 
        eighteen_hours = 18 * 3600
430
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
431
 
 
432
 
    def test_local_time_offset_with_timestamp(self):
433
 
        """Test that local_time_offset() works with a timestamp."""
434
 
        offset = osutils.local_time_offset(1000000000.1234567)
435
 
        self.assertTrue(isinstance(offset, int))
436
 
        eighteen_hours = 18 * 3600
437
 
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
438
 
 
439
 
 
440
 
class TestFdatasync(tests.TestCaseInTempDir):
441
 
 
442
 
    def do_fdatasync(self):
443
 
        f = tempfile.NamedTemporaryFile()
444
 
        osutils.fdatasync(f.fileno())
445
 
        f.close()
446
 
 
447
 
    @staticmethod
448
 
    def raise_eopnotsupp(*args, **kwargs):
449
 
        raise IOError(errno.EOPNOTSUPP, os.strerror(errno.EOPNOTSUPP))
450
 
 
451
 
    @staticmethod
452
 
    def raise_enotsup(*args, **kwargs):
453
 
        raise IOError(errno.ENOTSUP, os.strerror(errno.ENOTSUP))
454
 
 
455
 
    def test_fdatasync_handles_system_function(self):
456
 
        self.overrideAttr(os, "fdatasync")
457
 
        self.do_fdatasync()
458
 
 
459
 
    def test_fdatasync_handles_no_fdatasync_no_fsync(self):
460
 
        self.overrideAttr(os, "fdatasync")
461
 
        self.overrideAttr(os, "fsync")
462
 
        self.do_fdatasync()
463
 
 
464
 
    def test_fdatasync_handles_no_EOPNOTSUPP(self):
465
 
        self.overrideAttr(errno, "EOPNOTSUPP")
466
 
        self.do_fdatasync()
467
 
 
468
 
    def test_fdatasync_catches_ENOTSUP(self):
469
 
        enotsup = getattr(errno, "ENOTSUP", None)
470
 
        if enotsup is None:
471
 
            raise tests.TestNotApplicable("No ENOTSUP on this platform")
472
 
        self.overrideAttr(os, "fdatasync", self.raise_enotsup)
473
 
        self.do_fdatasync()
474
 
 
475
 
    def test_fdatasync_catches_EOPNOTSUPP(self):
476
 
        enotsup = getattr(errno, "EOPNOTSUPP", None)
477
 
        if enotsup is None:
478
 
            raise tests.TestNotApplicable("No EOPNOTSUPP on this platform")
479
 
        self.overrideAttr(os, "fdatasync", self.raise_eopnotsupp)
480
 
        self.do_fdatasync()
481
 
 
482
 
 
483
 
class TestLinks(tests.TestCaseInTempDir):
484
266
 
485
267
    def test_dereference_path(self):
486
 
        self.requireFeature(features.SymlinkFeature)
 
268
        self.requireFeature(SymlinkFeature)
487
269
        cwd = osutils.realpath('.')
488
270
        os.mkdir('bar')
489
271
        bar_path = osutils.pathjoin(cwd, 'bar')
492
274
        self.assertEqual(bar_path, osutils.realpath('./bar'))
493
275
        os.symlink('bar', 'foo')
494
276
        self.assertEqual(bar_path, osutils.realpath('./foo'))
495
 
 
 
277
        
496
278
        # Does not dereference terminal symlinks
497
279
        foo_path = osutils.pathjoin(cwd, 'foo')
498
280
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
530
312
            osutils.make_readonly('dangling')
531
313
            osutils.make_writable('dangling')
532
314
 
533
 
    def test_host_os_dereferences_symlinks(self):
534
 
        osutils.host_os_dereferences_symlinks()
535
 
 
536
 
 
537
 
class TestCanonicalRelPath(tests.TestCaseInTempDir):
538
 
 
539
 
    _test_needs_features = [features.CaseInsCasePresFilenameFeature]
540
 
 
541
 
    def test_canonical_relpath_simple(self):
542
 
        f = file('MixedCaseName', 'w')
543
 
        f.close()
544
 
        actual = osutils.canonical_relpath(self.test_base_dir, 'mixedcasename')
545
 
        self.assertEqual('work/MixedCaseName', actual)
546
 
 
547
 
    def test_canonical_relpath_missing_tail(self):
548
 
        os.mkdir('MixedCaseParent')
549
 
        actual = osutils.canonical_relpath(self.test_base_dir,
550
 
                                           'mixedcaseparent/nochild')
551
 
        self.assertEqual('work/MixedCaseParent/nochild', actual)
552
 
 
553
 
 
554
 
class Test_CICPCanonicalRelpath(tests.TestCaseWithTransport):
555
 
 
556
 
    def assertRelpath(self, expected, base, path):
557
 
        actual = osutils._cicp_canonical_relpath(base, path)
558
 
        self.assertEqual(expected, actual)
559
 
 
560
 
    def test_simple(self):
561
 
        self.build_tree(['MixedCaseName'])
562
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
563
 
        self.assertRelpath('MixedCaseName', base, 'mixedcAsename')
564
 
 
565
 
    def test_subdir_missing_tail(self):
566
 
        self.build_tree(['MixedCaseParent/', 'MixedCaseParent/a_child'])
567
 
        base = osutils.realpath(self.get_transport('.').local_abspath('.'))
568
 
        self.assertRelpath('MixedCaseParent/a_child', base,
569
 
                           'MixedCaseParent/a_child')
570
 
        self.assertRelpath('MixedCaseParent/a_child', base,
571
 
                           'MixedCaseParent/A_Child')
572
 
        self.assertRelpath('MixedCaseParent/not_child', base,
573
 
                           'MixedCaseParent/not_child')
574
 
 
575
 
    def test_at_root_slash(self):
576
 
        # We can't test this on Windows, because it has a 'MIN_ABS_PATHLENGTH'
577
 
        # check...
578
 
        if osutils.MIN_ABS_PATHLENGTH > 1:
579
 
            raise tests.TestSkipped('relpath requires %d chars'
580
 
                                    % osutils.MIN_ABS_PATHLENGTH)
581
 
        self.assertRelpath('foo', '/', '/foo')
582
 
 
583
 
    def test_at_root_drive(self):
584
 
        if sys.platform != 'win32':
585
 
            raise tests.TestNotApplicable('we can only test drive-letter relative'
586
 
                                          ' paths on Windows where we have drive'
587
 
                                          ' letters.')
588
 
        # see bug #322807
589
 
        # The specific issue is that when at the root of a drive, 'abspath'
590
 
        # returns "C:/" or just "/". However, the code assumes that abspath
591
 
        # always returns something like "C:/foo" or "/foo" (no trailing slash).
592
 
        self.assertRelpath('foo', 'C:/', 'C:/foo')
593
 
        self.assertRelpath('foo', 'X:/', 'X:/foo')
594
 
        self.assertRelpath('foo', 'X:/', 'X://foo')
595
 
 
596
 
 
597
 
class TestPumpFile(tests.TestCase):
598
 
    """Test pumpfile method."""
599
 
 
600
 
    def setUp(self):
601
 
        super(TestPumpFile, self).setUp()
602
 
        # create a test datablock
603
 
        self.block_size = 512
604
 
        pattern = '0123456789ABCDEF'
605
 
        self.test_data = pattern * (3 * self.block_size / len(pattern))
606
 
        self.test_data_len = len(self.test_data)
607
 
 
608
 
    def test_bracket_block_size(self):
609
 
        """Read data in blocks with the requested read size bracketing the
610
 
        block size."""
611
 
        # make sure test data is larger than max read size
612
 
        self.assertTrue(self.test_data_len > self.block_size)
613
 
 
614
 
        from_file = file_utils.FakeReadFile(self.test_data)
615
 
        to_file = StringIO()
616
 
 
617
 
        # read (max / 2) bytes and verify read size wasn't affected
618
 
        num_bytes_to_read = self.block_size / 2
619
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
620
 
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
621
 
        self.assertEqual(from_file.get_read_count(), 1)
622
 
 
623
 
        # read (max) bytes and verify read size wasn't affected
624
 
        num_bytes_to_read = self.block_size
625
 
        from_file.reset_read_count()
626
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
627
 
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
628
 
        self.assertEqual(from_file.get_read_count(), 1)
629
 
 
630
 
        # read (max + 1) bytes and verify read size was limited
631
 
        num_bytes_to_read = self.block_size + 1
632
 
        from_file.reset_read_count()
633
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
634
 
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
635
 
        self.assertEqual(from_file.get_read_count(), 2)
636
 
 
637
 
        # finish reading the rest of the data
638
 
        num_bytes_to_read = self.test_data_len - to_file.tell()
639
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
640
 
 
641
 
        # report error if the data wasn't equal (we only report the size due
642
 
        # to the length of the data)
643
 
        response_data = to_file.getvalue()
644
 
        if response_data != self.test_data:
645
 
            message = "Data not equal.  Expected %d bytes, received %d."
646
 
            self.fail(message % (len(response_data), self.test_data_len))
647
 
 
648
 
    def test_specified_size(self):
649
 
        """Request a transfer larger than the maximum block size and verify
650
 
        that the maximum read doesn't exceed the block_size."""
651
 
        # make sure test data is larger than max read size
652
 
        self.assertTrue(self.test_data_len > self.block_size)
653
 
 
654
 
        # retrieve data in blocks
655
 
        from_file = file_utils.FakeReadFile(self.test_data)
656
 
        to_file = StringIO()
657
 
        osutils.pumpfile(from_file, to_file, self.test_data_len,
658
 
                         self.block_size)
659
 
 
660
 
        # verify read size was equal to the maximum read size
661
 
        self.assertTrue(from_file.get_max_read_size() > 0)
662
 
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
663
 
        self.assertEqual(from_file.get_read_count(), 3)
664
 
 
665
 
        # report error if the data wasn't equal (we only report the size due
666
 
        # to the length of the data)
667
 
        response_data = to_file.getvalue()
668
 
        if response_data != self.test_data:
669
 
            message = "Data not equal.  Expected %d bytes, received %d."
670
 
            self.fail(message % (len(response_data), self.test_data_len))
671
 
 
672
 
    def test_to_eof(self):
673
 
        """Read to end-of-file and verify that the reads are not larger than
674
 
        the maximum read size."""
675
 
        # make sure test data is larger than max read size
676
 
        self.assertTrue(self.test_data_len > self.block_size)
677
 
 
678
 
        # retrieve data to EOF
679
 
        from_file = file_utils.FakeReadFile(self.test_data)
680
 
        to_file = StringIO()
681
 
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
682
 
 
683
 
        # verify read size was equal to the maximum read size
684
 
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
685
 
        self.assertEqual(from_file.get_read_count(), 4)
686
 
 
687
 
        # report error if the data wasn't equal (we only report the size due
688
 
        # to the length of the data)
689
 
        response_data = to_file.getvalue()
690
 
        if response_data != self.test_data:
691
 
            message = "Data not equal.  Expected %d bytes, received %d."
692
 
            self.fail(message % (len(response_data), self.test_data_len))
693
 
 
694
 
    def test_defaults(self):
695
 
        """Verifies that the default arguments will read to EOF -- this
696
 
        test verifies that any existing usages of pumpfile will not be broken
697
 
        with this new version."""
698
 
        # retrieve data using default (old) pumpfile method
699
 
        from_file = file_utils.FakeReadFile(self.test_data)
700
 
        to_file = StringIO()
701
 
        osutils.pumpfile(from_file, to_file)
702
 
 
703
 
        # report error if the data wasn't equal (we only report the size due
704
 
        # to the length of the data)
705
 
        response_data = to_file.getvalue()
706
 
        if response_data != self.test_data:
707
 
            message = "Data not equal.  Expected %d bytes, received %d."
708
 
            self.fail(message % (len(response_data), self.test_data_len))
709
 
 
710
 
    def test_report_activity(self):
711
 
        activity = []
712
 
        def log_activity(length, direction):
713
 
            activity.append((length, direction))
714
 
        from_file = StringIO(self.test_data)
715
 
        to_file = StringIO()
716
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
717
 
                         report_activity=log_activity, direction='read')
718
 
        self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
719
 
                          (36, 'read')], activity)
720
 
 
721
 
        from_file = StringIO(self.test_data)
722
 
        to_file = StringIO()
723
 
        del activity[:]
724
 
        osutils.pumpfile(from_file, to_file, buff_size=500,
725
 
                         report_activity=log_activity, direction='write')
726
 
        self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
727
 
                          (36, 'write')], activity)
728
 
 
729
 
        # And with a limited amount of data
730
 
        from_file = StringIO(self.test_data)
731
 
        to_file = StringIO()
732
 
        del activity[:]
733
 
        osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
734
 
                         report_activity=log_activity, direction='read')
735
 
        self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
736
 
 
737
 
 
738
 
 
739
 
class TestPumpStringFile(tests.TestCase):
740
 
 
741
 
    def test_empty(self):
742
 
        output = StringIO()
743
 
        osutils.pump_string_file("", output)
744
 
        self.assertEqual("", output.getvalue())
745
 
 
746
 
    def test_more_than_segment_size(self):
747
 
        output = StringIO()
748
 
        osutils.pump_string_file("123456789", output, 2)
749
 
        self.assertEqual("123456789", output.getvalue())
750
 
 
751
 
    def test_segment_size(self):
752
 
        output = StringIO()
753
 
        osutils.pump_string_file("12", output, 2)
754
 
        self.assertEqual("12", output.getvalue())
755
 
 
756
 
    def test_segment_size_multiple(self):
757
 
        output = StringIO()
758
 
        osutils.pump_string_file("1234", output, 2)
759
 
        self.assertEqual("1234", output.getvalue())
760
 
 
761
 
 
762
 
class TestRelpath(tests.TestCase):
763
 
 
764
 
    def test_simple_relpath(self):
765
 
        cwd = osutils.getcwd()
766
 
        subdir = cwd + '/subdir'
767
 
        self.assertEqual('subdir', osutils.relpath(cwd, subdir))
768
 
 
769
 
    def test_deep_relpath(self):
770
 
        cwd = osutils.getcwd()
771
 
        subdir = cwd + '/sub/subsubdir'
772
 
        self.assertEqual('sub/subsubdir', osutils.relpath(cwd, subdir))
773
 
 
774
 
    def test_not_relative(self):
775
 
        self.assertRaises(errors.PathNotChild,
776
 
                          osutils.relpath, 'C:/path', 'H:/path')
777
 
        self.assertRaises(errors.PathNotChild,
778
 
                          osutils.relpath, 'C:/', 'H:/path')
779
 
 
780
 
 
781
 
class TestSafeUnicode(tests.TestCase):
 
315
    def test_kind_marker(self):
 
316
        self.assertEqual("", osutils.kind_marker("file"))
 
317
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
 
318
        self.assertEqual("@", osutils.kind_marker("symlink"))
 
319
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
320
 
 
321
 
 
322
class TestSafeUnicode(TestCase):
782
323
 
783
324
    def test_from_ascii_string(self):
784
325
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
793
334
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
794
335
 
795
336
    def test_bad_utf8_string(self):
796
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
337
        self.assertRaises(BzrBadParameterNotUnicode,
797
338
                          osutils.safe_unicode,
798
339
                          '\xbb\xbb')
799
340
 
800
341
 
801
 
class TestSafeUtf8(tests.TestCase):
 
342
class TestSafeUtf8(TestCase):
802
343
 
803
344
    def test_from_ascii_string(self):
804
345
        f = 'foobar'
814
355
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
815
356
 
816
357
    def test_bad_utf8_string(self):
817
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
358
        self.assertRaises(BzrBadParameterNotUnicode,
818
359
                          osutils.safe_utf8, '\xbb\xbb')
819
360
 
820
361
 
821
 
class TestSafeRevisionId(tests.TestCase):
 
362
class TestSafeRevisionId(TestCase):
822
363
 
823
364
    def test_from_ascii_string(self):
824
365
        # this shouldn't give a warning because it's getting an ascii string
846
387
        self.assertEqual(None, osutils.safe_revision_id(None))
847
388
 
848
389
 
849
 
class TestSafeFileId(tests.TestCase):
 
390
class TestSafeFileId(TestCase):
850
391
 
851
392
    def test_from_ascii_string(self):
852
393
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
872
413
        self.assertEqual(None, osutils.safe_file_id(None))
873
414
 
874
415
 
875
 
class TestSendAll(tests.TestCase):
876
 
 
877
 
    def test_send_with_disconnected_socket(self):
878
 
        class DisconnectedSocket(object):
879
 
            def __init__(self, err):
880
 
                self.err = err
881
 
            def send(self, content):
882
 
                raise self.err
883
 
            def close(self):
884
 
                pass
885
 
        # All of these should be treated as ConnectionReset
886
 
        errs = []
887
 
        for err_cls in (IOError, socket.error):
888
 
            for errnum in osutils._end_of_stream_errors:
889
 
                errs.append(err_cls(errnum))
890
 
        for err in errs:
891
 
            sock = DisconnectedSocket(err)
892
 
            self.assertRaises(errors.ConnectionReset,
893
 
                osutils.send_all, sock, 'some more content')
894
 
 
895
 
    def test_send_with_no_progress(self):
896
 
        # See https://bugs.launchpad.net/bzr/+bug/1047309
897
 
        # It seems that paramiko can get into a state where it doesn't error,
898
 
        # but it returns 0 bytes sent for requests over and over again.
899
 
        class NoSendingSocket(object):
900
 
            def __init__(self):
901
 
                self.call_count = 0
902
 
            def send(self, bytes):
903
 
                self.call_count += 1
904
 
                if self.call_count > 100:
905
 
                    # Prevent the test suite from hanging
906
 
                    raise RuntimeError('too many calls')
907
 
                return 0
908
 
        sock = NoSendingSocket()
909
 
        self.assertRaises(errors.ConnectionReset,
910
 
                          osutils.send_all, sock, 'content')
911
 
        self.assertEqual(1, sock.call_count)
912
 
 
913
 
 
914
 
class TestPosixFuncs(tests.TestCase):
915
 
    """Test that the posix version of normpath returns an appropriate path
916
 
       when used with 2 leading slashes."""
917
 
 
918
 
    def test_normpath(self):
919
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
920
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('//etc/shadow'))
921
 
        self.assertEqual('/etc/shadow', osutils._posix_normpath('///etc/shadow'))
922
 
 
923
 
 
924
 
class TestWin32Funcs(tests.TestCase):
925
 
    """Test that _win32 versions of os utilities return appropriate paths."""
 
416
class TestWin32Funcs(TestCase):
 
417
    """Test that the _win32 versions of os utilities return appropriate paths."""
926
418
 
927
419
    def test_abspath(self):
928
420
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
935
427
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
936
428
 
937
429
    def test_pathjoin(self):
938
 
        self.assertEqual('path/to/foo',
939
 
                         osutils._win32_pathjoin('path', 'to', 'foo'))
940
 
        self.assertEqual('C:/foo',
941
 
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
942
 
        self.assertEqual('C:/foo',
943
 
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
944
 
        self.assertEqual('path/to/foo',
945
 
                         osutils._win32_pathjoin('path/to/', 'foo'))
946
 
        self.assertEqual('/foo',
947
 
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
948
 
        self.assertEqual('/foo',
949
 
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
430
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
431
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
432
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
433
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
434
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
435
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
950
436
 
951
437
    def test_normpath(self):
952
 
        self.assertEqual('path/to/foo',
953
 
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
954
 
        self.assertEqual('path/to/foo',
955
 
                         osutils._win32_normpath('path//from/../to/./foo'))
 
438
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
439
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
956
440
 
957
441
    def test_getcwd(self):
958
442
        cwd = osutils._win32_getcwd()
979
463
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
980
464
        # relative path
981
465
        cwd = osutils.getcwd().rstrip('/')
982
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
466
        drive = osutils._nt_splitdrive(cwd)[0]
983
467
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
984
468
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
985
469
        # unicode path
987
471
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
988
472
 
989
473
 
990
 
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
 
474
class TestWin32FuncsDirs(TestCaseInTempDir):
991
475
    """Test win32 functions that create files."""
 
476
    
 
477
    def test_getcwd(self):
 
478
        if win32utils.winver == 'Windows 98':
 
479
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
480
        # Make sure getcwd can handle unicode filenames
 
481
        try:
 
482
            os.mkdir(u'mu-\xb5')
 
483
        except UnicodeError:
 
484
            raise TestSkipped("Unable to create Unicode filename")
992
485
 
993
 
    def test_getcwd(self):
994
 
        self.requireFeature(features.UnicodeFilenameFeature)
995
 
        os.mkdir(u'mu-\xb5')
996
486
        os.chdir(u'mu-\xb5')
997
487
        # TODO: jam 20060427 This will probably fail on Mac OSX because
998
488
        #       it will change the normalization of B\xe5gfors
1003
493
    def test_minimum_path_selection(self):
1004
494
        self.assertEqual(set(),
1005
495
            osutils.minimum_path_selection([]))
1006
 
        self.assertEqual(set(['a']),
1007
 
            osutils.minimum_path_selection(['a']))
1008
496
        self.assertEqual(set(['a', 'b']),
1009
497
            osutils.minimum_path_selection(['a', 'b']))
1010
498
        self.assertEqual(set(['a/', 'b']),
1011
499
            osutils.minimum_path_selection(['a/', 'b']))
1012
500
        self.assertEqual(set(['a/', 'b']),
1013
501
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
1014
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
1015
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
1016
502
 
1017
503
    def test_mkdtemp(self):
1018
504
        tmpdir = osutils._win32_mkdtemp(dir='.')
1027
513
        b.close()
1028
514
 
1029
515
        osutils._win32_rename('b', 'a')
1030
 
        self.assertPathExists('a')
1031
 
        self.assertPathDoesNotExist('b')
 
516
        self.failUnlessExists('a')
 
517
        self.failIfExists('b')
1032
518
        self.assertFileEqual('baz\n', 'a')
1033
519
 
1034
520
    def test_rename_missing_file(self):
1074
560
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
1075
561
 
1076
562
 
1077
 
class TestParentDirectories(tests.TestCaseInTempDir):
1078
 
    """Test osutils.parent_directories()"""
1079
 
 
1080
 
    def test_parent_directories(self):
1081
 
        self.assertEqual([], osutils.parent_directories('a'))
1082
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
1083
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
1084
 
 
1085
 
 
1086
 
class TestMacFuncsDirs(tests.TestCaseInTempDir):
 
563
class TestMacFuncsDirs(TestCaseInTempDir):
1087
564
    """Test mac special functions that require directories."""
1088
565
 
1089
566
    def test_getcwd(self):
1090
 
        self.requireFeature(features.UnicodeFilenameFeature)
1091
 
        os.mkdir(u'B\xe5gfors')
 
567
        # On Mac, this will actually create Ba\u030agfors
 
568
        # but chdir will still work, because it accepts both paths
 
569
        try:
 
570
            os.mkdir(u'B\xe5gfors')
 
571
        except UnicodeError:
 
572
            raise TestSkipped("Unable to create Unicode filename")
 
573
 
1092
574
        os.chdir(u'B\xe5gfors')
1093
575
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1094
576
 
1095
577
    def test_getcwd_nonnorm(self):
1096
 
        self.requireFeature(features.UnicodeFilenameFeature)
1097
578
        # Test that _mac_getcwd() will normalize this path
1098
 
        os.mkdir(u'Ba\u030agfors')
 
579
        try:
 
580
            os.mkdir(u'Ba\u030agfors')
 
581
        except UnicodeError:
 
582
            raise TestSkipped("Unable to create Unicode filename")
 
583
 
1099
584
        os.chdir(u'Ba\u030agfors')
1100
585
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1101
586
 
1102
587
 
1103
 
class TestChunksToLines(tests.TestCase):
1104
 
 
1105
 
    def test_smoketest(self):
1106
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
1107
 
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
1108
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
1109
 
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
1110
 
 
1111
 
    def test_osutils_binding(self):
1112
 
        from bzrlib.tests import test__chunks_to_lines
1113
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
1114
 
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1115
 
        else:
1116
 
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1117
 
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
1118
 
 
1119
 
 
1120
 
class TestSplitLines(tests.TestCase):
 
588
class TestSplitLines(TestCase):
1121
589
 
1122
590
    def test_split_unicode(self):
1123
591
        self.assertEqual([u'foo\n', u'bar\xae'],
1130
598
                         osutils.split_lines('foo\rbar\n'))
1131
599
 
1132
600
 
1133
 
class TestWalkDirs(tests.TestCaseInTempDir):
1134
 
 
1135
 
    def assertExpectedBlocks(self, expected, result):
1136
 
        self.assertEqual(expected,
1137
 
                         [(dirinfo, [line[0:3] for line in block])
1138
 
                          for dirinfo, block in result])
 
601
class TestWalkDirs(TestCaseInTempDir):
1139
602
 
1140
603
    def test_walkdirs(self):
1141
604
        tree = [
1174
637
            result.append((dirdetail, dirblock))
1175
638
 
1176
639
        self.assertTrue(found_bzrdir)
1177
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
640
        self.assertEqual(expected_dirblocks,
 
641
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1178
642
        # you can search a subdir only, with a supplied prefix.
1179
643
        result = []
1180
644
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1181
645
            result.append(dirblock)
1182
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1183
 
 
1184
 
    def test_walkdirs_os_error(self):
1185
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
1186
 
        # Pyrex readdir didn't raise useful messages if it had an error
1187
 
        # reading the directory
1188
 
        if sys.platform == 'win32':
1189
 
            raise tests.TestNotApplicable(
1190
 
                "readdir IOError not tested on win32")
1191
 
        self.requireFeature(features.not_running_as_root)
1192
 
        os.mkdir("test-unreadable")
1193
 
        os.chmod("test-unreadable", 0000)
1194
 
        # must chmod it back so that it can be removed
1195
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
1196
 
        # The error is not raised until the generator is actually evaluated.
1197
 
        # (It would be ok if it happened earlier but at the moment it
1198
 
        # doesn't.)
1199
 
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1200
 
        self.assertEquals('./test-unreadable', e.filename)
1201
 
        self.assertEquals(errno.EACCES, e.errno)
1202
 
        # Ensure the message contains the file name
1203
 
        self.assertContainsRe(str(e), "\./test-unreadable")
1204
 
 
1205
 
 
1206
 
    def test_walkdirs_encoding_error(self):
1207
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1208
 
        # walkdirs didn't raise a useful message when the filenames
1209
 
        # are not using the filesystem's encoding
1210
 
 
1211
 
        # require a bytestring based filesystem
1212
 
        self.requireFeature(features.ByteStringNamedFilesystem)
1213
 
 
1214
 
        tree = [
1215
 
            '.bzr',
1216
 
            '0file',
1217
 
            '1dir/',
1218
 
            '1dir/0file',
1219
 
            '1dir/1dir/',
1220
 
            '1file'
1221
 
            ]
1222
 
 
1223
 
        self.build_tree(tree)
1224
 
 
1225
 
        # rename the 1file to a latin-1 filename
1226
 
        os.rename("./1file", "\xe8file")
1227
 
        if "\xe8file" not in os.listdir("."):
1228
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1229
 
 
1230
 
        self._save_platform_info()
1231
 
        win32utils.winver = None # Avoid the win32 detection code
1232
 
        osutils._fs_enc = 'UTF-8'
1233
 
 
1234
 
        # this should raise on error
1235
 
        def attempt():
1236
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1237
 
                pass
1238
 
 
1239
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
 
646
        self.assertEqual(expected_dirblocks[1:],
 
647
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1240
648
 
1241
649
    def test__walkdirs_utf8(self):
1242
650
        tree = [
1275
683
            result.append((dirdetail, dirblock))
1276
684
 
1277
685
        self.assertTrue(found_bzrdir)
1278
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1279
 
 
 
686
        self.assertEqual(expected_dirblocks,
 
687
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1280
688
        # you can search a subdir only, with a supplied prefix.
1281
689
        result = []
1282
690
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1283
691
            result.append(dirblock)
1284
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
692
        self.assertEqual(expected_dirblocks[1:],
 
693
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1285
694
 
1286
695
    def _filter_out_stat(self, result):
1287
696
        """Filter out the stat value from the walkdirs result"""
1292
701
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1293
702
            dirblock[:] = new_dirblock
1294
703
 
1295
 
    def _save_platform_info(self):
1296
 
        self.overrideAttr(win32utils, 'winver')
1297
 
        self.overrideAttr(osutils, '_fs_enc')
1298
 
        self.overrideAttr(osutils, '_selected_dir_reader')
1299
 
 
1300
 
    def assertDirReaderIs(self, expected):
1301
 
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1302
 
        # Force it to redetect
1303
 
        osutils._selected_dir_reader = None
1304
 
        # Nothing to list, but should still trigger the selection logic
1305
 
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1306
 
        self.assertIsInstance(osutils._selected_dir_reader, expected)
1307
 
 
1308
 
    def test_force_walkdirs_utf8_fs_utf8(self):
1309
 
        self.requireFeature(UTF8DirReaderFeature)
1310
 
        self._save_platform_info()
1311
 
        win32utils.winver = None # Avoid the win32 detection code
1312
 
        osutils._fs_enc = 'utf-8'
1313
 
        self.assertDirReaderIs(
1314
 
            UTF8DirReaderFeature.module.UTF8DirReader)
1315
 
 
1316
 
    def test_force_walkdirs_utf8_fs_ascii(self):
1317
 
        self.requireFeature(UTF8DirReaderFeature)
1318
 
        self._save_platform_info()
1319
 
        win32utils.winver = None # Avoid the win32 detection code
1320
 
        osutils._fs_enc = 'ascii'
1321
 
        self.assertDirReaderIs(
1322
 
            UTF8DirReaderFeature.module.UTF8DirReader)
1323
 
 
1324
 
    def test_force_walkdirs_utf8_fs_latin1(self):
1325
 
        self._save_platform_info()
1326
 
        win32utils.winver = None # Avoid the win32 detection code
1327
 
        osutils._fs_enc = 'iso-8859-1'
1328
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1329
 
 
1330
 
    def test_force_walkdirs_utf8_nt(self):
1331
 
        # Disabled because the thunk of the whole walkdirs api is disabled.
1332
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1333
 
        self._save_platform_info()
1334
 
        win32utils.winver = 'Windows NT'
1335
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1336
 
        self.assertDirReaderIs(Win32ReadDir)
1337
 
 
1338
 
    def test_force_walkdirs_utf8_98(self):
1339
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1340
 
        self._save_platform_info()
1341
 
        win32utils.winver = 'Windows 98'
1342
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
1343
 
 
1344
704
    def test_unicode_walkdirs(self):
1345
705
        """Walkdirs should always return unicode paths."""
1346
 
        self.requireFeature(features.UnicodeFilenameFeature)
1347
706
        name0 = u'0file-\xb6'
1348
707
        name1 = u'1dir-\u062c\u0648'
1349
708
        name2 = u'2file-\u0633'
1354
713
            name1 + '/' + name1 + '/',
1355
714
            name2,
1356
715
            ]
1357
 
        self.build_tree(tree)
 
716
        try:
 
717
            self.build_tree(tree)
 
718
        except UnicodeError:
 
719
            raise TestSkipped('Could not represent Unicode chars'
 
720
                              ' in current encoding.')
1358
721
        expected_dirblocks = [
1359
722
                ((u'', u'.'),
1360
723
                 [(name0, name0, 'file', './' + name0),
1386
749
 
1387
750
        The abspath portion might be in unicode or utf-8
1388
751
        """
1389
 
        self.requireFeature(features.UnicodeFilenameFeature)
1390
752
        name0 = u'0file-\xb6'
1391
753
        name1 = u'1dir-\u062c\u0648'
1392
754
        name2 = u'2file-\u0633'
1397
759
            name1 + '/' + name1 + '/',
1398
760
            name2,
1399
761
            ]
1400
 
        self.build_tree(tree)
 
762
        try:
 
763
            self.build_tree(tree)
 
764
        except UnicodeError:
 
765
            raise TestSkipped('Could not represent Unicode chars'
 
766
                              ' in current encoding.')
1401
767
        name0 = name0.encode('utf8')
1402
768
        name1 = name1.encode('utf8')
1403
769
        name2 = name2.encode('utf8')
1442
808
            result.append((dirdetail, new_dirblock))
1443
809
        self.assertEqual(expected_dirblocks, result)
1444
810
 
1445
 
    def test__walkdirs_utf8_with_unicode_fs(self):
1446
 
        """UnicodeDirReader should be a safe fallback everywhere
 
811
    def test_unicode__walkdirs_unicode_to_utf8(self):
 
812
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
1447
813
 
1448
814
        The abspath portion should be in unicode
1449
815
        """
1450
 
        self.requireFeature(features.UnicodeFilenameFeature)
1451
 
        # Use the unicode reader. TODO: split into driver-and-driven unit
1452
 
        # tests.
1453
 
        self._save_platform_info()
1454
 
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
1455
 
        name0u = u'0file-\xb6'
1456
 
        name1u = u'1dir-\u062c\u0648'
1457
 
        name2u = u'2file-\u0633'
1458
 
        tree = [
1459
 
            name0u,
1460
 
            name1u + '/',
1461
 
            name1u + '/' + name0u,
1462
 
            name1u + '/' + name1u + '/',
1463
 
            name2u,
1464
 
            ]
1465
 
        self.build_tree(tree)
1466
 
        name0 = name0u.encode('utf8')
1467
 
        name1 = name1u.encode('utf8')
1468
 
        name2 = name2u.encode('utf8')
1469
 
 
1470
 
        # All of the abspaths should be in unicode, all of the relative paths
1471
 
        # should be in utf8
1472
 
        expected_dirblocks = [
1473
 
                (('', '.'),
1474
 
                 [(name0, name0, 'file', './' + name0u),
1475
 
                  (name1, name1, 'directory', './' + name1u),
1476
 
                  (name2, name2, 'file', './' + name2u),
1477
 
                 ]
1478
 
                ),
1479
 
                ((name1, './' + name1u),
1480
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1481
 
                                                        + '/' + name0u),
1482
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1483
 
                                                            + '/' + name1u),
1484
 
                 ]
1485
 
                ),
1486
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1487
 
                 [
1488
 
                 ]
1489
 
                ),
1490
 
            ]
1491
 
        result = list(osutils._walkdirs_utf8('.'))
1492
 
        self._filter_out_stat(result)
1493
 
        self.assertEqual(expected_dirblocks, result)
1494
 
 
1495
 
    def test__walkdirs_utf8_win32readdir(self):
1496
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1497
 
        self.requireFeature(features.UnicodeFilenameFeature)
1498
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1499
 
        self._save_platform_info()
1500
 
        osutils._selected_dir_reader = Win32ReadDir()
1501
 
        name0u = u'0file-\xb6'
1502
 
        name1u = u'1dir-\u062c\u0648'
1503
 
        name2u = u'2file-\u0633'
1504
 
        tree = [
1505
 
            name0u,
1506
 
            name1u + '/',
1507
 
            name1u + '/' + name0u,
1508
 
            name1u + '/' + name1u + '/',
1509
 
            name2u,
1510
 
            ]
1511
 
        self.build_tree(tree)
1512
 
        name0 = name0u.encode('utf8')
1513
 
        name1 = name1u.encode('utf8')
1514
 
        name2 = name2u.encode('utf8')
1515
 
 
1516
 
        # All of the abspaths should be in unicode, all of the relative paths
1517
 
        # should be in utf8
1518
 
        expected_dirblocks = [
1519
 
                (('', '.'),
1520
 
                 [(name0, name0, 'file', './' + name0u),
1521
 
                  (name1, name1, 'directory', './' + name1u),
1522
 
                  (name2, name2, 'file', './' + name2u),
1523
 
                 ]
1524
 
                ),
1525
 
                ((name1, './' + name1u),
1526
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1527
 
                                                        + '/' + name0u),
1528
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1529
 
                                                            + '/' + name1u),
1530
 
                 ]
1531
 
                ),
1532
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1533
 
                 [
1534
 
                 ]
1535
 
                ),
1536
 
            ]
1537
 
        result = list(osutils._walkdirs_utf8(u'.'))
1538
 
        self._filter_out_stat(result)
1539
 
        self.assertEqual(expected_dirblocks, result)
1540
 
 
1541
 
    def assertStatIsCorrect(self, path, win32stat):
1542
 
        os_stat = os.stat(path)
1543
 
        self.assertEqual(os_stat.st_size, win32stat.st_size)
1544
 
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
1545
 
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
1546
 
        self.assertAlmostEqual(os_stat.st_atime, win32stat.st_atime, places=4)
1547
 
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
1548
 
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
1549
 
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
1550
 
 
1551
 
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1552
 
        """make sure our Stat values are valid"""
1553
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1554
 
        self.requireFeature(features.UnicodeFilenameFeature)
1555
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1556
 
        name0u = u'0file-\xb6'
1557
 
        name0 = name0u.encode('utf8')
1558
 
        self.build_tree([name0u])
1559
 
        # I hate to sleep() here, but I'm trying to make the ctime different
1560
 
        # from the mtime
1561
 
        time.sleep(2)
1562
 
        f = open(name0u, 'ab')
 
816
        name0u = u'0file-\xb6'
 
817
        name1u = u'1dir-\u062c\u0648'
 
818
        name2u = u'2file-\u0633'
 
819
        tree = [
 
820
            name0u,
 
821
            name1u + '/',
 
822
            name1u + '/' + name0u,
 
823
            name1u + '/' + name1u + '/',
 
824
            name2u,
 
825
            ]
1563
826
        try:
1564
 
            f.write('just a small update')
1565
 
        finally:
1566
 
            f.close()
1567
 
 
1568
 
        result = Win32ReadDir().read_dir('', u'.')
1569
 
        entry = result[0]
1570
 
        self.assertEqual((name0, name0, 'file'), entry[:3])
1571
 
        self.assertEqual(u'./' + name0u, entry[4])
1572
 
        self.assertStatIsCorrect(entry[4], entry[3])
1573
 
        self.assertNotEqual(entry[3].st_mtime, entry[3].st_ctime)
1574
 
 
1575
 
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1576
 
        """make sure our Stat values are valid"""
1577
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1578
 
        self.requireFeature(features.UnicodeFilenameFeature)
1579
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1580
 
        name0u = u'0dir-\u062c\u0648'
 
827
            self.build_tree(tree)
 
828
        except UnicodeError:
 
829
            raise TestSkipped('Could not represent Unicode chars'
 
830
                              ' in current encoding.')
1581
831
        name0 = name0u.encode('utf8')
1582
 
        self.build_tree([name0u + '/'])
 
832
        name1 = name1u.encode('utf8')
 
833
        name2 = name2u.encode('utf8')
1583
834
 
1584
 
        result = Win32ReadDir().read_dir('', u'.')
1585
 
        entry = result[0]
1586
 
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1587
 
        self.assertEqual(u'./' + name0u, entry[4])
1588
 
        self.assertStatIsCorrect(entry[4], entry[3])
 
835
        # All of the abspaths should be in unicode, all of the relative paths
 
836
        # should be in utf8
 
837
        expected_dirblocks = [
 
838
                (('', '.'),
 
839
                 [(name0, name0, 'file', './' + name0u),
 
840
                  (name1, name1, 'directory', './' + name1u),
 
841
                  (name2, name2, 'file', './' + name2u),
 
842
                 ]
 
843
                ),
 
844
                ((name1, './' + name1u),
 
845
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
846
                                                        + '/' + name0u),
 
847
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
848
                                                            + '/' + name1u),
 
849
                 ]
 
850
                ),
 
851
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
852
                 [
 
853
                 ]
 
854
                ),
 
855
            ]
 
856
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
 
857
        self._filter_out_stat(result)
 
858
        self.assertEqual(expected_dirblocks, result)
1589
859
 
1590
860
    def assertPathCompare(self, path_less, path_greater):
1591
861
        """check that path_less and path_greater compare correctly."""
1665
935
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1666
936
 
1667
937
 
1668
 
class TestCopyTree(tests.TestCaseInTempDir):
1669
 
 
 
938
class TestCopyTree(TestCaseInTempDir):
 
939
    
1670
940
    def test_copy_basic_tree(self):
1671
941
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1672
942
        osutils.copy_tree('source', 'target')
1681
951
        self.assertEqual(['c'], os.listdir('target/b'))
1682
952
 
1683
953
    def test_copy_tree_symlinks(self):
1684
 
        self.requireFeature(features.SymlinkFeature)
 
954
        self.requireFeature(SymlinkFeature)
1685
955
        self.build_tree(['source/'])
1686
956
        os.symlink('a/generic/path', 'source/lnk')
1687
957
        osutils.copy_tree('source', 'target')
1712
982
                          ('d', 'source/b', 'target/b'),
1713
983
                          ('f', 'source/b/c', 'target/b/c'),
1714
984
                         ], processed_files)
1715
 
        self.assertPathDoesNotExist('target')
 
985
        self.failIfExists('target')
1716
986
        if osutils.has_symlinks():
1717
987
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1718
988
 
1719
989
 
1720
 
class TestSetUnsetEnv(tests.TestCase):
 
990
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
991
# [bialix] 2006/12/26
 
992
 
 
993
 
 
994
class TestSetUnsetEnv(TestCase):
1721
995
    """Test updating the environment"""
1722
996
 
1723
997
    def setUp(self):
1729
1003
        def cleanup():
1730
1004
            if 'BZR_TEST_ENV_VAR' in os.environ:
1731
1005
                del os.environ['BZR_TEST_ENV_VAR']
 
1006
 
1732
1007
        self.addCleanup(cleanup)
1733
1008
 
1734
1009
    def test_set(self):
1746
1021
 
1747
1022
    def test_unicode(self):
1748
1023
        """Environment can only contain plain strings
1749
 
 
 
1024
        
1750
1025
        So Unicode strings must be encoded.
1751
1026
        """
1752
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
1027
        uni_val, env_val = probe_unicode_in_user_encoding()
1753
1028
        if uni_val is None:
1754
 
            raise tests.TestSkipped(
1755
 
                'Cannot find a unicode character that works in encoding %s'
1756
 
                % (osutils.get_user_encoding(),))
 
1029
            raise TestSkipped('Cannot find a unicode character that works in'
 
1030
                              ' encoding %s' % (bzrlib.user_encoding,))
1757
1031
 
1758
1032
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1759
1033
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1764
1038
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1765
1039
        self.assertEqual('foo', old)
1766
1040
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1767
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1768
 
 
1769
 
 
1770
 
class TestSizeShaFile(tests.TestCaseInTempDir):
1771
 
 
1772
 
    def test_sha_empty(self):
1773
 
        self.build_tree_contents([('foo', '')])
1774
 
        expected_sha = osutils.sha_string('')
1775
 
        f = open('foo')
1776
 
        self.addCleanup(f.close)
1777
 
        size, sha = osutils.size_sha_file(f)
1778
 
        self.assertEqual(0, size)
1779
 
        self.assertEqual(expected_sha, sha)
1780
 
 
1781
 
    def test_sha_mixed_endings(self):
1782
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1783
 
        self.build_tree_contents([('foo', text)])
1784
 
        expected_sha = osutils.sha_string(text)
1785
 
        f = open('foo', 'rb')
1786
 
        self.addCleanup(f.close)
1787
 
        size, sha = osutils.size_sha_file(f)
1788
 
        self.assertEqual(38, size)
1789
 
        self.assertEqual(expected_sha, sha)
1790
 
 
1791
 
 
1792
 
class TestShaFileByName(tests.TestCaseInTempDir):
1793
 
 
1794
 
    def test_sha_empty(self):
1795
 
        self.build_tree_contents([('foo', '')])
1796
 
        expected_sha = osutils.sha_string('')
1797
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1798
 
 
1799
 
    def test_sha_mixed_endings(self):
1800
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1801
 
        self.build_tree_contents([('foo', text)])
1802
 
        expected_sha = osutils.sha_string(text)
1803
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1804
 
 
1805
 
 
1806
 
class TestResourceLoading(tests.TestCaseInTempDir):
 
1041
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1042
 
 
1043
 
 
1044
class TestLocalTimeOffset(TestCase):
 
1045
 
 
1046
    def test_local_time_offset(self):
 
1047
        """Test that local_time_offset() returns a sane value."""
 
1048
        offset = osutils.local_time_offset()
 
1049
        self.assertTrue(isinstance(offset, int))
 
1050
        # Test that the offset is no more than a eighteen hours in
 
1051
        # either direction.
 
1052
        # Time zone handling is system specific, so it is difficult to
 
1053
        # do more specific tests, but a value outside of this range is
 
1054
        # probably wrong.
 
1055
        eighteen_hours = 18 * 3600
 
1056
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1057
 
 
1058
    def test_local_time_offset_with_timestamp(self):
 
1059
        """Test that local_time_offset() works with a timestamp."""
 
1060
        offset = osutils.local_time_offset(1000000000.1234567)
 
1061
        self.assertTrue(isinstance(offset, int))
 
1062
        eighteen_hours = 18 * 3600
 
1063
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1064
 
 
1065
 
 
1066
class TestShaFileByName(TestCaseInTempDir):
 
1067
 
 
1068
    def test_sha_empty(self):
 
1069
        self.build_tree_contents([('foo', '')])
 
1070
        expected_sha = osutils.sha_string('')
 
1071
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1072
 
 
1073
    def test_sha_mixed_endings(self):
 
1074
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1075
        self.build_tree_contents([('foo', text)])
 
1076
        expected_sha = osutils.sha_string(text)
 
1077
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1078
 
 
1079
 
 
1080
_debug_text = \
 
1081
r'''# Copyright (C) 2005, 2006 Canonical Ltd
 
1082
#
 
1083
# This program is free software; you can redistribute it and/or modify
 
1084
# it under the terms of the GNU General Public License as published by
 
1085
# the Free Software Foundation; either version 2 of the License, or
 
1086
# (at your option) any later version.
 
1087
#
 
1088
# This program is distributed in the hope that it will be useful,
 
1089
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
1090
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
1091
# GNU General Public License for more details.
 
1092
#
 
1093
# You should have received a copy of the GNU General Public License
 
1094
# along with this program; if not, write to the Free Software
 
1095
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
1096
 
 
1097
 
 
1098
# NOTE: If update these, please also update the help for global-options in
 
1099
#       bzrlib/help_topics/__init__.py
 
1100
 
 
1101
debug_flags = set()
 
1102
"""Set of flags that enable different debug behaviour.
 
1103
 
 
1104
These are set with eg ``-Dlock`` on the bzr command line.
 
1105
 
 
1106
Options include:
 
1107
 
 
1108
 * auth - show authentication sections used
 
1109
 * error - show stack traces for all top level exceptions
 
1110
 * evil - capture call sites that do expensive or badly-scaling operations.
 
1111
 * fetch - trace history copying between repositories
 
1112
 * hashcache - log every time a working file is read to determine its hash
 
1113
 * hooks - trace hook execution
 
1114
 * hpss - trace smart protocol requests and responses
 
1115
 * http - trace http connections, requests and responses
 
1116
 * index - trace major index operations
 
1117
 * knit - trace knit operations
 
1118
 * lock - trace when lockdir locks are taken or released
 
1119
 * merge - emit information for debugging merges
 
1120
 * pack - emit information about pack operations
 
1121
 * selftest_debug - do not disable all debug flags when running selftest
 
1122
 
 
1123
"""
 
1124
'''
 
1125
 
 
1126
 
 
1127
class TestResourceLoading(TestCaseInTempDir):
1807
1128
 
1808
1129
    def test_resource_string(self):
1809
1130
        # test resource in bzrlib
1810
1131
        text = osutils.resource_string('bzrlib', 'debug.py')
1811
 
        self.assertContainsRe(text, "debug_flags = set()")
 
1132
        self.assertEquals(_debug_text, text)
1812
1133
        # test resource under bzrlib
1813
1134
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1814
1135
        self.assertContainsRe(text, "class TextUIFactory")
1817
1138
            'yyy.xx')
1818
1139
        # test unknown resource
1819
1140
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1820
 
 
1821
 
 
1822
 
class TestReCompile(tests.TestCase):
1823
 
 
1824
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1825
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1826
 
            osutils.re_compile_checked, *args, **kwargs)
1827
 
 
1828
 
    def test_re_compile_checked(self):
1829
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1830
 
        self.assertTrue(r.match('aaaa'))
1831
 
        self.assertTrue(r.match('aAaA'))
1832
 
 
1833
 
    def test_re_compile_checked_error(self):
1834
 
        # like https://bugs.launchpad.net/bzr/+bug/251352
1835
 
 
1836
 
        # Due to possible test isolation error, re.compile is not lazy at
1837
 
        # this point. We re-install lazy compile.
1838
 
        lazy_regex.install_lazy_compile()
1839
 
        err = self.assertRaises(
1840
 
            errors.BzrCommandError,
1841
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1842
 
        self.assertEqual(
1843
 
            'Invalid regular expression in test case: '
1844
 
            '"*" nothing to repeat',
1845
 
            str(err))
1846
 
 
1847
 
 
1848
 
class TestDirReader(tests.TestCaseInTempDir):
1849
 
 
1850
 
    scenarios = dir_reader_scenarios()
1851
 
 
1852
 
    # Set by load_tests
1853
 
    _dir_reader_class = None
1854
 
    _native_to_unicode = None
1855
 
 
1856
 
    def setUp(self):
1857
 
        super(TestDirReader, self).setUp()
1858
 
        self.overrideAttr(osutils,
1859
 
                          '_selected_dir_reader', self._dir_reader_class())
1860
 
 
1861
 
    def _get_ascii_tree(self):
1862
 
        tree = [
1863
 
            '0file',
1864
 
            '1dir/',
1865
 
            '1dir/0file',
1866
 
            '1dir/1dir/',
1867
 
            '2file'
1868
 
            ]
1869
 
        expected_dirblocks = [
1870
 
                (('', '.'),
1871
 
                 [('0file', '0file', 'file'),
1872
 
                  ('1dir', '1dir', 'directory'),
1873
 
                  ('2file', '2file', 'file'),
1874
 
                 ]
1875
 
                ),
1876
 
                (('1dir', './1dir'),
1877
 
                 [('1dir/0file', '0file', 'file'),
1878
 
                  ('1dir/1dir', '1dir', 'directory'),
1879
 
                 ]
1880
 
                ),
1881
 
                (('1dir/1dir', './1dir/1dir'),
1882
 
                 [
1883
 
                 ]
1884
 
                ),
1885
 
            ]
1886
 
        return tree, expected_dirblocks
1887
 
 
1888
 
    def test_walk_cur_dir(self):
1889
 
        tree, expected_dirblocks = self._get_ascii_tree()
1890
 
        self.build_tree(tree)
1891
 
        result = list(osutils._walkdirs_utf8('.'))
1892
 
        # Filter out stat and abspath
1893
 
        self.assertEqual(expected_dirblocks,
1894
 
                         [(dirinfo, [line[0:3] for line in block])
1895
 
                          for dirinfo, block in result])
1896
 
 
1897
 
    def test_walk_sub_dir(self):
1898
 
        tree, expected_dirblocks = self._get_ascii_tree()
1899
 
        self.build_tree(tree)
1900
 
        # you can search a subdir only, with a supplied prefix.
1901
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1902
 
        # Filter out stat and abspath
1903
 
        self.assertEqual(expected_dirblocks[1:],
1904
 
                         [(dirinfo, [line[0:3] for line in block])
1905
 
                          for dirinfo, block in result])
1906
 
 
1907
 
    def _get_unicode_tree(self):
1908
 
        name0u = u'0file-\xb6'
1909
 
        name1u = u'1dir-\u062c\u0648'
1910
 
        name2u = u'2file-\u0633'
1911
 
        tree = [
1912
 
            name0u,
1913
 
            name1u + '/',
1914
 
            name1u + '/' + name0u,
1915
 
            name1u + '/' + name1u + '/',
1916
 
            name2u,
1917
 
            ]
1918
 
        name0 = name0u.encode('UTF-8')
1919
 
        name1 = name1u.encode('UTF-8')
1920
 
        name2 = name2u.encode('UTF-8')
1921
 
        expected_dirblocks = [
1922
 
                (('', '.'),
1923
 
                 [(name0, name0, 'file', './' + name0u),
1924
 
                  (name1, name1, 'directory', './' + name1u),
1925
 
                  (name2, name2, 'file', './' + name2u),
1926
 
                 ]
1927
 
                ),
1928
 
                ((name1, './' + name1u),
1929
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1930
 
                                                        + '/' + name0u),
1931
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1932
 
                                                            + '/' + name1u),
1933
 
                 ]
1934
 
                ),
1935
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1936
 
                 [
1937
 
                 ]
1938
 
                ),
1939
 
            ]
1940
 
        return tree, expected_dirblocks
1941
 
 
1942
 
    def _filter_out(self, raw_dirblocks):
1943
 
        """Filter out a walkdirs_utf8 result.
1944
 
 
1945
 
        stat field is removed, all native paths are converted to unicode
1946
 
        """
1947
 
        filtered_dirblocks = []
1948
 
        for dirinfo, block in raw_dirblocks:
1949
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1950
 
            details = []
1951
 
            for line in block:
1952
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1953
 
            filtered_dirblocks.append((dirinfo, details))
1954
 
        return filtered_dirblocks
1955
 
 
1956
 
    def test_walk_unicode_tree(self):
1957
 
        self.requireFeature(features.UnicodeFilenameFeature)
1958
 
        tree, expected_dirblocks = self._get_unicode_tree()
1959
 
        self.build_tree(tree)
1960
 
        result = list(osutils._walkdirs_utf8('.'))
1961
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1962
 
 
1963
 
    def test_symlink(self):
1964
 
        self.requireFeature(features.SymlinkFeature)
1965
 
        self.requireFeature(features.UnicodeFilenameFeature)
1966
 
        target = u'target\N{Euro Sign}'
1967
 
        link_name = u'l\N{Euro Sign}nk'
1968
 
        os.symlink(target, link_name)
1969
 
        target_utf8 = target.encode('UTF-8')
1970
 
        link_name_utf8 = link_name.encode('UTF-8')
1971
 
        expected_dirblocks = [
1972
 
                (('', '.'),
1973
 
                 [(link_name_utf8, link_name_utf8,
1974
 
                   'symlink', './' + link_name),],
1975
 
                 )]
1976
 
        result = list(osutils._walkdirs_utf8('.'))
1977
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1978
 
 
1979
 
 
1980
 
class TestReadLink(tests.TestCaseInTempDir):
1981
 
    """Exposes os.readlink() problems and the osutils solution.
1982
 
 
1983
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1984
 
    unicode string will be returned if a unicode string is passed.
1985
 
 
1986
 
    But prior python versions failed to properly encode the passed unicode
1987
 
    string.
1988
 
    """
1989
 
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1990
 
 
1991
 
    def setUp(self):
1992
 
        super(tests.TestCaseInTempDir, self).setUp()
1993
 
        self.link = u'l\N{Euro Sign}ink'
1994
 
        self.target = u'targe\N{Euro Sign}t'
1995
 
        os.symlink(self.target, self.link)
1996
 
 
1997
 
    def test_os_readlink_link_encoding(self):
1998
 
        self.assertEquals(self.target,  os.readlink(self.link))
1999
 
 
2000
 
    def test_os_readlink_link_decoding(self):
2001
 
        self.assertEquals(self.target.encode(osutils._fs_enc),
2002
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
2003
 
 
2004
 
 
2005
 
class TestConcurrency(tests.TestCase):
2006
 
 
2007
 
    def setUp(self):
2008
 
        super(TestConcurrency, self).setUp()
2009
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
2010
 
 
2011
 
    def test_local_concurrency(self):
2012
 
        concurrency = osutils.local_concurrency()
2013
 
        self.assertIsInstance(concurrency, int)
2014
 
 
2015
 
    def test_local_concurrency_environment_variable(self):
2016
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
2017
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
2018
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
2019
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
2020
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
2021
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
2022
 
 
2023
 
    def test_option_concurrency(self):
2024
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
2025
 
        self.run_bzr('rocks --concurrency 42')
2026
 
        # Command line overrides environment variable
2027
 
        self.assertEquals('42', os.environ['BZR_CONCURRENCY'])
2028
 
        self.assertEquals(42, osutils.local_concurrency(use_cache=False))
2029
 
 
2030
 
 
2031
 
class TestFailedToLoadExtension(tests.TestCase):
2032
 
 
2033
 
    def _try_loading(self):
2034
 
        try:
2035
 
            import bzrlib._fictional_extension_py
2036
 
        except ImportError, e:
2037
 
            osutils.failed_to_load_extension(e)
2038
 
            return True
2039
 
 
2040
 
    def setUp(self):
2041
 
        super(TestFailedToLoadExtension, self).setUp()
2042
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
2043
 
 
2044
 
    def test_failure_to_load(self):
2045
 
        self._try_loading()
2046
 
        self.assertLength(1, osutils._extension_load_failures)
2047
 
        self.assertEquals(osutils._extension_load_failures[0],
2048
 
            "No module named _fictional_extension_py")
2049
 
 
2050
 
    def test_report_extension_load_failures_no_warning(self):
2051
 
        self.assertTrue(self._try_loading())
2052
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
2053
 
        # it used to give a Python warning; it no longer does
2054
 
        self.assertLength(0, warnings)
2055
 
 
2056
 
    def test_report_extension_load_failures_message(self):
2057
 
        log = StringIO()
2058
 
        trace.push_log_file(log)
2059
 
        self.assertTrue(self._try_loading())
2060
 
        osutils.report_extension_load_failures()
2061
 
        self.assertContainsRe(
2062
 
            log.getvalue(),
2063
 
            r"bzr: warning: some compiled extensions could not be loaded; "
2064
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
2065
 
            )
2066
 
 
2067
 
 
2068
 
class TestTerminalWidth(tests.TestCase):
2069
 
 
2070
 
    def setUp(self):
2071
 
        super(TestTerminalWidth, self).setUp()
2072
 
        self._orig_terminal_size_state = osutils._terminal_size_state
2073
 
        self._orig_first_terminal_size = osutils._first_terminal_size
2074
 
        self.addCleanup(self.restore_osutils_globals)
2075
 
        osutils._terminal_size_state = 'no_data'
2076
 
        osutils._first_terminal_size = None
2077
 
 
2078
 
    def restore_osutils_globals(self):
2079
 
        osutils._terminal_size_state = self._orig_terminal_size_state
2080
 
        osutils._first_terminal_size = self._orig_first_terminal_size
2081
 
 
2082
 
    def replace_stdout(self, new):
2083
 
        self.overrideAttr(sys, 'stdout', new)
2084
 
 
2085
 
    def replace__terminal_size(self, new):
2086
 
        self.overrideAttr(osutils, '_terminal_size', new)
2087
 
 
2088
 
    def set_fake_tty(self):
2089
 
 
2090
 
        class I_am_a_tty(object):
2091
 
            def isatty(self):
2092
 
                return True
2093
 
 
2094
 
        self.replace_stdout(I_am_a_tty())
2095
 
 
2096
 
    def test_default_values(self):
2097
 
        self.assertEqual(80, osutils.default_terminal_width)
2098
 
 
2099
 
    def test_defaults_to_BZR_COLUMNS(self):
2100
 
        # BZR_COLUMNS is set by the test framework
2101
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2102
 
        self.overrideEnv('BZR_COLUMNS', '12')
2103
 
        self.assertEqual(12, osutils.terminal_width())
2104
 
 
2105
 
    def test_BZR_COLUMNS_0_no_limit(self):
2106
 
        self.overrideEnv('BZR_COLUMNS', '0')
2107
 
        self.assertEqual(None, osutils.terminal_width())
2108
 
 
2109
 
    def test_falls_back_to_COLUMNS(self):
2110
 
        self.overrideEnv('BZR_COLUMNS', None)
2111
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
2112
 
        self.set_fake_tty()
2113
 
        self.overrideEnv('COLUMNS', '42')
2114
 
        self.assertEqual(42, osutils.terminal_width())
2115
 
 
2116
 
    def test_tty_default_without_columns(self):
2117
 
        self.overrideEnv('BZR_COLUMNS', None)
2118
 
        self.overrideEnv('COLUMNS', None)
2119
 
 
2120
 
        def terminal_size(w, h):
2121
 
            return 42, 42
2122
 
 
2123
 
        self.set_fake_tty()
2124
 
        # We need to override the osutils definition as it depends on the
2125
 
        # running environment that we can't control (PQM running without a
2126
 
        # controlling terminal is one example).
2127
 
        self.replace__terminal_size(terminal_size)
2128
 
        self.assertEqual(42, osutils.terminal_width())
2129
 
 
2130
 
    def test_non_tty_default_without_columns(self):
2131
 
        self.overrideEnv('BZR_COLUMNS', None)
2132
 
        self.overrideEnv('COLUMNS', None)
2133
 
        self.replace_stdout(None)
2134
 
        self.assertEqual(None, osutils.terminal_width())
2135
 
 
2136
 
    def test_no_TIOCGWINSZ(self):
2137
 
        self.requireFeature(term_ios_feature)
2138
 
        termios = term_ios_feature.module
2139
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2140
 
        try:
2141
 
            orig = termios.TIOCGWINSZ
2142
 
        except AttributeError:
2143
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2144
 
            pass
2145
 
        else:
2146
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2147
 
            del termios.TIOCGWINSZ
2148
 
        self.overrideEnv('BZR_COLUMNS', None)
2149
 
        self.overrideEnv('COLUMNS', None)
2150
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2151
 
        osutils.terminal_width()
2152
 
 
2153
 
 
2154
 
class TestCreationOps(tests.TestCaseInTempDir):
2155
 
    _test_needs_features = [features.chown_feature]
2156
 
 
2157
 
    def setUp(self):
2158
 
        super(TestCreationOps, self).setUp()
2159
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2160
 
 
2161
 
        # params set by call to _dummy_chown
2162
 
        self.path = self.uid = self.gid = None
2163
 
 
2164
 
    def _dummy_chown(self, path, uid, gid):
2165
 
        self.path, self.uid, self.gid = path, uid, gid
2166
 
 
2167
 
    def test_copy_ownership_from_path(self):
2168
 
        """copy_ownership_from_path test with specified src."""
2169
 
        ownsrc = '/'
2170
 
        f = open('test_file', 'wt')
2171
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2172
 
 
2173
 
        s = os.stat(ownsrc)
2174
 
        self.assertEquals(self.path, 'test_file')
2175
 
        self.assertEquals(self.uid, s.st_uid)
2176
 
        self.assertEquals(self.gid, s.st_gid)
2177
 
 
2178
 
    def test_copy_ownership_nonesrc(self):
2179
 
        """copy_ownership_from_path test with src=None."""
2180
 
        f = open('test_file', 'wt')
2181
 
        # should use parent dir for permissions
2182
 
        osutils.copy_ownership_from_path('test_file')
2183
 
 
2184
 
        s = os.stat('..')
2185
 
        self.assertEquals(self.path, 'test_file')
2186
 
        self.assertEquals(self.uid, s.st_uid)
2187
 
        self.assertEquals(self.gid, s.st_gid)
2188
 
 
2189
 
 
2190
 
class TestPathFromEnviron(tests.TestCase):
2191
 
 
2192
 
    def test_is_unicode(self):
2193
 
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
2194
 
        path = osutils.path_from_environ('BZR_TEST_PATH')
2195
 
        self.assertIsInstance(path, unicode)
2196
 
        self.assertEqual(u'./anywhere at all/', path)
2197
 
 
2198
 
    def test_posix_path_env_ascii(self):
2199
 
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
2200
 
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
2201
 
        self.assertIsInstance(home, unicode)
2202
 
        self.assertEqual(u'/tmp', home)
2203
 
 
2204
 
    def test_posix_path_env_unicode(self):
2205
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2206
 
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
2207
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2208
 
        self.assertEqual(u'/home/\xa7test',
2209
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2210
 
        osutils._fs_enc = "iso8859-5"
2211
 
        self.assertEqual(u'/home/\u0407test',
2212
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2213
 
        osutils._fs_enc = "utf-8"
2214
 
        self.assertRaises(errors.BadFilenameEncoding,
2215
 
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
2216
 
 
2217
 
 
2218
 
class TestGetHomeDir(tests.TestCase):
2219
 
 
2220
 
    def test_is_unicode(self):
2221
 
        home = osutils._get_home_dir()
2222
 
        self.assertIsInstance(home, unicode)
2223
 
 
2224
 
    def test_posix_homeless(self):
2225
 
        self.overrideEnv('HOME', None)
2226
 
        home = osutils._get_home_dir()
2227
 
        self.assertIsInstance(home, unicode)
2228
 
 
2229
 
    def test_posix_home_ascii(self):
2230
 
        self.overrideEnv('HOME', '/home/test')
2231
 
        home = osutils._posix_get_home_dir()
2232
 
        self.assertIsInstance(home, unicode)
2233
 
        self.assertEqual(u'/home/test', home)
2234
 
 
2235
 
    def test_posix_home_unicode(self):
2236
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2237
 
        self.overrideEnv('HOME', '/home/\xa7test')
2238
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2239
 
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2240
 
        osutils._fs_enc = "iso8859-5"
2241
 
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
2242
 
        osutils._fs_enc = "utf-8"
2243
 
        self.assertRaises(errors.BadFilenameEncoding,
2244
 
            osutils._posix_get_home_dir)
2245
 
 
2246
 
 
2247
 
class TestGetuserUnicode(tests.TestCase):
2248
 
 
2249
 
    def test_is_unicode(self):
2250
 
        user = osutils.getuser_unicode()
2251
 
        self.assertIsInstance(user, unicode)
2252
 
 
2253
 
    def envvar_to_override(self):
2254
 
        if sys.platform == "win32":
2255
 
            # Disable use of platform calls on windows so envvar is used
2256
 
            self.overrideAttr(win32utils, 'has_ctypes', False)
2257
 
            return 'USERNAME' # only variable used on windows
2258
 
        return 'LOGNAME' # first variable checked by getpass.getuser()
2259
 
 
2260
 
    def test_ascii_user(self):
2261
 
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
2262
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2263
 
 
2264
 
    def test_unicode_user(self):
2265
 
        ue = osutils.get_user_encoding()
2266
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2267
 
        if uni_val is None:
2268
 
            raise tests.TestSkipped(
2269
 
                'Cannot find a unicode character that works in encoding %s'
2270
 
                % (osutils.get_user_encoding(),))
2271
 
        uni_username = u'jrandom' + uni_val
2272
 
        encoded_username = uni_username.encode(ue)
2273
 
        self.overrideEnv(self.envvar_to_override(), encoded_username)
2274
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2275
 
 
2276
 
 
2277
 
class TestBackupNames(tests.TestCase):
2278
 
 
2279
 
    def setUp(self):
2280
 
        super(TestBackupNames, self).setUp()
2281
 
        self.backups = []
2282
 
 
2283
 
    def backup_exists(self, name):
2284
 
        return name in self.backups
2285
 
 
2286
 
    def available_backup_name(self, name):
2287
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2288
 
        self.backups.append(backup_name)
2289
 
        return backup_name
2290
 
 
2291
 
    def assertBackupName(self, expected, name):
2292
 
        self.assertEqual(expected, self.available_backup_name(name))
2293
 
 
2294
 
    def test_empty(self):
2295
 
        self.assertBackupName('file.~1~', 'file')
2296
 
 
2297
 
    def test_existing(self):
2298
 
        self.available_backup_name('file')
2299
 
        self.available_backup_name('file')
2300
 
        self.assertBackupName('file.~3~', 'file')
2301
 
        # Empty slots are found, this is not a strict requirement and may be
2302
 
        # revisited if we test against all implementations.
2303
 
        self.backups.remove('file.~2~')
2304
 
        self.assertBackupName('file.~2~', 'file')
2305
 
 
2306
 
 
2307
 
class TestFindExecutableInPath(tests.TestCase):
2308
 
 
2309
 
    def test_windows(self):
2310
 
        if sys.platform != 'win32':
2311
 
            raise tests.TestSkipped('test requires win32')
2312
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2313
 
        self.assertTrue(
2314
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2315
 
        self.assertTrue(
2316
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2317
 
        self.assertTrue(
2318
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2319
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2320
 
        
2321
 
    def test_windows_app_path(self):
2322
 
        if sys.platform != 'win32':
2323
 
            raise tests.TestSkipped('test requires win32')
2324
 
        # Override PATH env var so that exe can only be found on App Path
2325
 
        self.overrideEnv('PATH', '')
2326
 
        # Internt Explorer is always registered in the App Path
2327
 
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2328
 
 
2329
 
    def test_other(self):
2330
 
        if sys.platform == 'win32':
2331
 
            raise tests.TestSkipped('test requires non-win32')
2332
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2333
 
        self.assertTrue(
2334
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2335
 
 
2336
 
 
2337
 
class TestEnvironmentErrors(tests.TestCase):
2338
 
    """Test handling of environmental errors"""
2339
 
 
2340
 
    def test_is_oserror(self):
2341
 
        self.assertTrue(osutils.is_environment_error(
2342
 
            OSError(errno.EINVAL, "Invalid parameter")))
2343
 
 
2344
 
    def test_is_ioerror(self):
2345
 
        self.assertTrue(osutils.is_environment_error(
2346
 
            IOError(errno.EINVAL, "Invalid parameter")))
2347
 
 
2348
 
    def test_is_socket_error(self):
2349
 
        self.assertTrue(osutils.is_environment_error(
2350
 
            socket.error(errno.EINVAL, "Invalid parameter")))
2351
 
 
2352
 
    def test_is_select_error(self):
2353
 
        self.assertTrue(osutils.is_environment_error(
2354
 
            select.error(errno.EINVAL, "Invalid parameter")))
2355
 
 
2356
 
    def test_is_pywintypes_error(self):
2357
 
        self.requireFeature(features.pywintypes)
2358
 
        import pywintypes
2359
 
        self.assertTrue(osutils.is_environment_error(
2360
 
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))