~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2016 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the osutils wrapper."""
18
18
 
19
19
from cStringIO import StringIO
20
20
import errno
21
21
import os
22
 
import re
23
 
import select
24
22
import socket
 
23
import stat
25
24
import sys
26
 
import tempfile
27
25
import time
28
26
 
 
27
import bzrlib
29
28
from bzrlib import (
30
29
    errors,
31
 
    lazy_regex,
32
30
    osutils,
33
 
    symbol_versioning,
34
31
    tests,
35
 
    trace,
36
32
    win32utils,
37
33
    )
 
34
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
35
from bzrlib.osutils import (
 
36
        is_inside_any,
 
37
        is_inside_or_parent_of_any,
 
38
        pathjoin,
 
39
        pumpfile,
 
40
        pump_string_file,
 
41
        )
38
42
from bzrlib.tests import (
39
 
    features,
40
 
    file_utils,
41
 
    test__walkdirs_win32,
 
43
        adapt_tests,
 
44
        Feature,
 
45
        probe_unicode_in_user_encoding,
 
46
        split_suite_by_re,
 
47
        StringIOWrapper,
 
48
        SymlinkFeature,
 
49
        TestCase,
 
50
        TestCaseInTempDir,
 
51
        TestScenarioApplier,
 
52
        TestSkipped,
 
53
        )
 
54
from bzrlib.tests.file_utils import (
 
55
    FakeReadFile,
42
56
    )
43
 
from bzrlib.tests.scenarios import load_tests_apply_scenarios
44
 
 
45
 
 
46
 
class _UTF8DirReaderFeature(features.Feature):
 
57
from bzrlib.tests.test__walkdirs_win32 import WalkdirsWin32Feature
 
58
 
 
59
 
 
60
def load_tests(standard_tests, module, loader):
 
61
    """Parameterize readdir tests."""
 
62
    to_adapt, result = split_suite_by_re(standard_tests, "readdir")
 
63
    adapter = TestScenarioApplier()
 
64
    from bzrlib import _readdir_py
 
65
    adapter.scenarios = [('python', {'read_dir': _readdir_py.read_dir})]
 
66
    if ReadDirFeature.available():
 
67
        adapter.scenarios.append(('pyrex',
 
68
            {'read_dir': ReadDirFeature.read_dir}))
 
69
    adapt_tests(to_adapt, adapter, result)
 
70
    return result
 
71
 
 
72
 
 
73
class _ReadDirFeature(Feature):
47
74
 
48
75
    def _probe(self):
49
76
        try:
50
77
            from bzrlib import _readdir_pyx
51
 
            self.reader = _readdir_pyx.UTF8DirReader
 
78
            self.read_dir = _readdir_pyx.read_dir
52
79
            return True
53
80
        except ImportError:
54
81
            return False
56
83
    def feature_name(self):
57
84
        return 'bzrlib._readdir_pyx'
58
85
 
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):
 
86
ReadDirFeature = _ReadDirFeature()
 
87
 
 
88
 
 
89
class TestOSUtils(TestCaseInTempDir):
106
90
 
107
91
    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'))
 
92
        self.failUnless(osutils.contains_whitespace(u' '))
 
93
        self.failUnless(osutils.contains_whitespace(u'hello there'))
 
94
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
 
95
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
 
96
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
 
97
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
114
98
 
115
99
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
116
100
        # 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)
 
101
        self.failIf(osutils.contains_whitespace(u''))
 
102
        self.failIf(osutils.contains_whitespace(u'hellothere'))
 
103
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
134
104
 
135
105
    def test_fancy_rename(self):
136
106
        # 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')
 
107
        def rename(a, b):
 
108
            osutils.fancy_rename(a, b,
 
109
                    rename_func=os.rename,
 
110
                    unlink_func=os.unlink)
 
111
 
 
112
        open('a', 'wb').write('something in a\n')
 
113
        rename('a', 'b')
 
114
        self.failIfExists('a')
 
115
        self.failUnlessExists('b')
141
116
        self.check_file_contents('b', 'something in a\n')
142
117
 
143
 
        self.create_file('a', 'new something in a\n')
144
 
        self._fancy_rename('b', 'a')
 
118
        open('a', 'wb').write('new something in a\n')
 
119
        rename('b', 'a')
145
120
 
146
121
        self.check_file_contents('a', 'something in a\n')
147
122
 
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
123
    def test_rename(self):
161
124
        # Rename should be semi-atomic on all platforms
162
 
        self.create_file('a', 'something in a\n')
 
125
        open('a', 'wb').write('something in a\n')
163
126
        osutils.rename('a', 'b')
164
 
        self.assertPathDoesNotExist('a')
165
 
        self.assertPathExists('b')
 
127
        self.failIfExists('a')
 
128
        self.failUnlessExists('b')
166
129
        self.check_file_contents('b', 'something in a\n')
167
130
 
168
 
        self.create_file('a', 'new something in a\n')
 
131
        open('a', 'wb').write('new something in a\n')
169
132
        osutils.rename('b', 'a')
170
133
 
171
134
        self.check_file_contents('a', 'something in a\n')
180
143
        # we can't use failUnlessExists on case-insensitive filesystem
181
144
        # so try to check shape of the tree
182
145
        shape = sorted(os.listdir('.'))
183
 
        self.assertEqual(['A', 'B'], shape)
184
 
 
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):
 
146
        self.assertEquals(['A', 'B'], shape)
196
147
 
197
148
    def test_01_rand_chars_empty(self):
198
149
        result = osutils.rand_chars(0)
204
155
        self.assertEqual(type(result), str)
205
156
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
206
157
 
207
 
 
208
 
class TestIsInside(tests.TestCase):
209
 
 
210
158
    def test_is_inside(self):
211
159
        is_inside = osutils.is_inside
212
160
        self.assertTrue(is_inside('src', 'src/foo.c'))
217
165
        self.assertTrue(is_inside('', 'foo.c'))
218
166
 
219
167
    def test_is_inside_any(self):
220
 
        SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
 
168
        SRC_FOO_C = pathjoin('src', 'foo.c')
221
169
        for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
222
170
                         (['src'], SRC_FOO_C),
223
171
                         (['src'], 'src'),
224
172
                         ]:
225
 
            self.assertTrue(osutils.is_inside_any(dirs, fn))
 
173
            self.assert_(is_inside_any(dirs, fn))
226
174
        for dirs, fn in [(['src'], 'srccontrol'),
227
175
                         (['src'], 'srccontrol/foo')]:
228
 
            self.assertFalse(osutils.is_inside_any(dirs, fn))
 
176
            self.assertFalse(is_inside_any(dirs, fn))
229
177
 
230
178
    def test_is_inside_or_parent_of_any(self):
231
179
        for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
234
182
                         (['src/bar.c', 'bla/foo.c'], 'src'),
235
183
                         (['src'], 'src'),
236
184
                         ]:
237
 
            self.assertTrue(osutils.is_inside_or_parent_of_any(dirs, fn))
238
 
 
 
185
            self.assert_(is_inside_or_parent_of_any(dirs, fn))
 
186
            
239
187
        for dirs, fn in [(['src'], 'srccontrol'),
240
188
                         (['srccontrol/foo.c'], 'src'),
241
189
                         (['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):
 
190
            self.assertFalse(is_inside_or_parent_of_any(dirs, fn))
265
191
 
266
192
    def test_rmtree(self):
267
193
        # Check to remove tree with read-only files/dirs
278
204
 
279
205
        osutils.rmtree('dir')
280
206
 
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):
 
207
        self.failIfExists('dir/file')
 
208
        self.failIfExists('dir')
298
209
 
299
210
    def test_file_kind(self):
300
211
        self.build_tree(['file', 'dir/'])
301
 
        self.assertEqual('file', osutils.file_kind('file'))
302
 
        self.assertEqual('directory', osutils.file_kind('dir/'))
 
212
        self.assertEquals('file', osutils.file_kind('file'))
 
213
        self.assertEquals('directory', osutils.file_kind('dir/'))
303
214
        if osutils.has_symlinks():
304
215
            os.symlink('symlink', 'symlink')
305
 
            self.assertEqual('symlink', osutils.file_kind('symlink'))
306
 
 
 
216
            self.assertEquals('symlink', osutils.file_kind('symlink'))
 
217
        
307
218
        # TODO: jam 20060529 Test a block device
308
219
        try:
309
220
            os.lstat('/dev/null')
311
222
            if e.errno not in (errno.ENOENT,):
312
223
                raise
313
224
        else:
314
 
            self.assertEqual('chardev', osutils.file_kind('/dev/null'))
 
225
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
315
226
 
316
227
        mkfifo = getattr(os, 'mkfifo', None)
317
228
        if mkfifo:
318
229
            mkfifo('fifo')
319
230
            try:
320
 
                self.assertEqual('fifo', osutils.file_kind('fifo'))
 
231
                self.assertEquals('fifo', osutils.file_kind('fifo'))
321
232
            finally:
322
233
                os.remove('fifo')
323
234
 
326
237
            s = socket.socket(AF_UNIX)
327
238
            s.bind('socket')
328
239
            try:
329
 
                self.assertEqual('socket', osutils.file_kind('socket'))
 
240
                self.assertEquals('socket', osutils.file_kind('socket'))
330
241
            finally:
331
242
                os.remove('socket')
332
243
 
333
244
    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):
 
245
        self.assertEqual(osutils.kind_marker('file'), '')
 
246
        self.assertEqual(osutils.kind_marker('directory'), '/')
 
247
        self.assertEqual(osutils.kind_marker('symlink'), '@')
 
248
        self.assertEqual(osutils.kind_marker('tree-reference'), '+')
345
249
 
346
250
    def test_get_umask(self):
347
251
        if sys.platform == 'win32':
350
254
            return
351
255
 
352
256
        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):
 
257
        try:
 
258
            os.umask(0222)
 
259
            self.assertEqual(0222, osutils.get_umask())
 
260
            os.umask(0022)
 
261
            self.assertEqual(0022, osutils.get_umask())
 
262
            os.umask(0002)
 
263
            self.assertEqual(0002, osutils.get_umask())
 
264
            os.umask(0027)
 
265
            self.assertEqual(0027, osutils.get_umask())
 
266
        finally:
 
267
            os.umask(orig_umask)
365
268
 
366
269
    def assertFormatedDelta(self, expected, seconds):
367
270
        """Assert osutils.format_delta formats as expected"""
402
305
    def test_format_date(self):
403
306
        self.assertRaises(errors.UnsupportedTimezoneFormat,
404
307
            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
308
 
485
309
    def test_dereference_path(self):
486
 
        self.requireFeature(features.SymlinkFeature)
 
310
        self.requireFeature(SymlinkFeature)
487
311
        cwd = osutils.realpath('.')
488
312
        os.mkdir('bar')
489
313
        bar_path = osutils.pathjoin(cwd, 'bar')
492
316
        self.assertEqual(bar_path, osutils.realpath('./bar'))
493
317
        os.symlink('bar', 'foo')
494
318
        self.assertEqual(bar_path, osutils.realpath('./foo'))
495
 
 
 
319
        
496
320
        # Does not dereference terminal symlinks
497
321
        foo_path = osutils.pathjoin(cwd, 'foo')
498
322
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
530
354
            osutils.make_readonly('dangling')
531
355
            osutils.make_writable('dangling')
532
356
 
 
357
    def test_kind_marker(self):
 
358
        self.assertEqual("", osutils.kind_marker("file"))
 
359
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
 
360
        self.assertEqual("@", osutils.kind_marker("symlink"))
 
361
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
 
362
 
533
363
    def test_host_os_dereferences_symlinks(self):
534
364
        osutils.host_os_dereferences_symlinks()
535
365
 
536
366
 
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):
 
367
class TestPumpFile(TestCase):
598
368
    """Test pumpfile method."""
599
 
 
600
369
    def setUp(self):
601
 
        super(TestPumpFile, self).setUp()
602
370
        # create a test datablock
603
371
        self.block_size = 512
604
372
        pattern = '0123456789ABCDEF'
611
379
        # make sure test data is larger than max read size
612
380
        self.assertTrue(self.test_data_len > self.block_size)
613
381
 
614
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
382
        from_file = FakeReadFile(self.test_data)
615
383
        to_file = StringIO()
616
384
 
617
385
        # read (max / 2) bytes and verify read size wasn't affected
618
386
        num_bytes_to_read = self.block_size / 2
619
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
387
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
620
388
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
621
389
        self.assertEqual(from_file.get_read_count(), 1)
622
390
 
623
391
        # read (max) bytes and verify read size wasn't affected
624
392
        num_bytes_to_read = self.block_size
625
393
        from_file.reset_read_count()
626
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
394
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
627
395
        self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
628
396
        self.assertEqual(from_file.get_read_count(), 1)
629
397
 
630
398
        # read (max + 1) bytes and verify read size was limited
631
399
        num_bytes_to_read = self.block_size + 1
632
400
        from_file.reset_read_count()
633
 
        osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
 
401
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
634
402
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
635
403
        self.assertEqual(from_file.get_read_count(), 2)
636
404
 
637
405
        # finish reading the rest of the data
638
406
        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)
 
407
        pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
640
408
 
641
409
        # report error if the data wasn't equal (we only report the size due
642
410
        # to the length of the data)
652
420
        self.assertTrue(self.test_data_len > self.block_size)
653
421
 
654
422
        # retrieve data in blocks
655
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
423
        from_file = FakeReadFile(self.test_data)
656
424
        to_file = StringIO()
657
 
        osutils.pumpfile(from_file, to_file, self.test_data_len,
658
 
                         self.block_size)
 
425
        pumpfile(from_file, to_file, self.test_data_len, self.block_size)
659
426
 
660
427
        # verify read size was equal to the maximum read size
661
428
        self.assertTrue(from_file.get_max_read_size() > 0)
676
443
        self.assertTrue(self.test_data_len > self.block_size)
677
444
 
678
445
        # retrieve data to EOF
679
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
446
        from_file = FakeReadFile(self.test_data)
680
447
        to_file = StringIO()
681
 
        osutils.pumpfile(from_file, to_file, -1, self.block_size)
 
448
        pumpfile(from_file, to_file, -1, self.block_size)
682
449
 
683
450
        # verify read size was equal to the maximum read size
684
451
        self.assertEqual(from_file.get_max_read_size(), self.block_size)
696
463
        test verifies that any existing usages of pumpfile will not be broken
697
464
        with this new version."""
698
465
        # retrieve data using default (old) pumpfile method
699
 
        from_file = file_utils.FakeReadFile(self.test_data)
 
466
        from_file = FakeReadFile(self.test_data)
700
467
        to_file = StringIO()
701
 
        osutils.pumpfile(from_file, to_file)
 
468
        pumpfile(from_file, to_file)
702
469
 
703
470
        # report error if the data wasn't equal (we only report the size due
704
471
        # to the length of the data)
707
474
            message = "Data not equal.  Expected %d bytes, received %d."
708
475
            self.fail(message % (len(response_data), self.test_data_len))
709
476
 
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):
 
477
 
 
478
class TestPumpStringFile(TestCase):
740
479
 
741
480
    def test_empty(self):
742
481
        output = StringIO()
743
 
        osutils.pump_string_file("", output)
 
482
        pump_string_file("", output)
744
483
        self.assertEqual("", output.getvalue())
745
484
 
746
485
    def test_more_than_segment_size(self):
747
486
        output = StringIO()
748
 
        osutils.pump_string_file("123456789", output, 2)
 
487
        pump_string_file("123456789", output, 2)
749
488
        self.assertEqual("123456789", output.getvalue())
750
489
 
751
490
    def test_segment_size(self):
752
491
        output = StringIO()
753
 
        osutils.pump_string_file("12", output, 2)
 
492
        pump_string_file("12", output, 2)
754
493
        self.assertEqual("12", output.getvalue())
755
494
 
756
495
    def test_segment_size_multiple(self):
757
496
        output = StringIO()
758
 
        osutils.pump_string_file("1234", output, 2)
 
497
        pump_string_file("1234", output, 2)
759
498
        self.assertEqual("1234", output.getvalue())
760
499
 
761
500
 
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):
 
501
class TestSafeUnicode(TestCase):
782
502
 
783
503
    def test_from_ascii_string(self):
784
504
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
793
513
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
794
514
 
795
515
    def test_bad_utf8_string(self):
796
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
516
        self.assertRaises(BzrBadParameterNotUnicode,
797
517
                          osutils.safe_unicode,
798
518
                          '\xbb\xbb')
799
519
 
800
520
 
801
 
class TestSafeUtf8(tests.TestCase):
 
521
class TestSafeUtf8(TestCase):
802
522
 
803
523
    def test_from_ascii_string(self):
804
524
        f = 'foobar'
814
534
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
815
535
 
816
536
    def test_bad_utf8_string(self):
817
 
        self.assertRaises(errors.BzrBadParameterNotUnicode,
 
537
        self.assertRaises(BzrBadParameterNotUnicode,
818
538
                          osutils.safe_utf8, '\xbb\xbb')
819
539
 
820
540
 
821
 
class TestSafeRevisionId(tests.TestCase):
 
541
class TestSafeRevisionId(TestCase):
822
542
 
823
543
    def test_from_ascii_string(self):
824
544
        # this shouldn't give a warning because it's getting an ascii string
846
566
        self.assertEqual(None, osutils.safe_revision_id(None))
847
567
 
848
568
 
849
 
class TestSafeFileId(tests.TestCase):
 
569
class TestSafeFileId(TestCase):
850
570
 
851
571
    def test_from_ascii_string(self):
852
572
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
872
592
        self.assertEqual(None, osutils.safe_file_id(None))
873
593
 
874
594
 
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."""
 
595
class TestWin32Funcs(TestCase):
 
596
    """Test that the _win32 versions of os utilities return appropriate paths."""
926
597
 
927
598
    def test_abspath(self):
928
 
        self.requireFeature(features.win32_feature)
929
599
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
930
600
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
931
601
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
936
606
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
937
607
 
938
608
    def test_pathjoin(self):
939
 
        self.assertEqual('path/to/foo',
940
 
                         osutils._win32_pathjoin('path', 'to', 'foo'))
941
 
        self.assertEqual('C:/foo',
942
 
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
943
 
        self.assertEqual('C:/foo',
944
 
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
945
 
        self.assertEqual('path/to/foo',
946
 
                         osutils._win32_pathjoin('path/to/', 'foo'))
947
 
 
948
 
    def test_pathjoin_late_bugfix(self):
949
 
        if sys.version_info < (2, 7, 6):
950
 
            expected = '/foo'
951
 
        else:
952
 
            expected = 'C:/foo'
953
 
        self.assertEqual(expected,
954
 
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
955
 
        self.assertEqual(expected,
956
 
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
609
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
610
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
611
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
612
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
613
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
614
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
957
615
 
958
616
    def test_normpath(self):
959
 
        self.assertEqual('path/to/foo',
960
 
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
961
 
        self.assertEqual('path/to/foo',
962
 
                         osutils._win32_normpath('path//from/../to/./foo'))
 
617
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
618
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
963
619
 
964
620
    def test_getcwd(self):
965
621
        cwd = osutils._win32_getcwd()
978
634
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
979
635
 
980
636
    def test_win98_abspath(self):
981
 
        self.requireFeature(features.win32_feature)
982
637
        # absolute path
983
638
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
984
639
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
987
642
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
988
643
        # relative path
989
644
        cwd = osutils.getcwd().rstrip('/')
990
 
        drive = osutils.ntpath.splitdrive(cwd)[0]
 
645
        drive = osutils._nt_splitdrive(cwd)[0]
991
646
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
992
647
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
993
648
        # unicode path
995
650
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
996
651
 
997
652
 
998
 
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
 
653
class TestWin32FuncsDirs(TestCaseInTempDir):
999
654
    """Test win32 functions that create files."""
 
655
    
 
656
    def test_getcwd(self):
 
657
        if win32utils.winver == 'Windows 98':
 
658
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
659
        # Make sure getcwd can handle unicode filenames
 
660
        try:
 
661
            os.mkdir(u'mu-\xb5')
 
662
        except UnicodeError:
 
663
            raise TestSkipped("Unable to create Unicode filename")
1000
664
 
1001
 
    def test_getcwd(self):
1002
 
        self.requireFeature(features.UnicodeFilenameFeature)
1003
 
        os.mkdir(u'mu-\xb5')
1004
665
        os.chdir(u'mu-\xb5')
1005
666
        # TODO: jam 20060427 This will probably fail on Mac OSX because
1006
667
        #       it will change the normalization of B\xe5gfors
1011
672
    def test_minimum_path_selection(self):
1012
673
        self.assertEqual(set(),
1013
674
            osutils.minimum_path_selection([]))
1014
 
        self.assertEqual(set(['a']),
1015
 
            osutils.minimum_path_selection(['a']))
1016
675
        self.assertEqual(set(['a', 'b']),
1017
676
            osutils.minimum_path_selection(['a', 'b']))
1018
677
        self.assertEqual(set(['a/', 'b']),
1019
678
            osutils.minimum_path_selection(['a/', 'b']))
1020
679
        self.assertEqual(set(['a/', 'b']),
1021
680
            osutils.minimum_path_selection(['a/c', 'a/', 'b']))
1022
 
        self.assertEqual(set(['a-b', 'a', 'a0b']),
1023
 
            osutils.minimum_path_selection(['a-b', 'a/b', 'a0b', 'a']))
1024
681
 
1025
682
    def test_mkdtemp(self):
1026
683
        tmpdir = osutils._win32_mkdtemp(dir='.')
1035
692
        b.close()
1036
693
 
1037
694
        osutils._win32_rename('b', 'a')
1038
 
        self.assertPathExists('a')
1039
 
        self.assertPathDoesNotExist('b')
 
695
        self.failUnlessExists('a')
 
696
        self.failIfExists('b')
1040
697
        self.assertFileEqual('baz\n', 'a')
1041
698
 
1042
699
    def test_rename_missing_file(self):
1082
739
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
1083
740
 
1084
741
 
1085
 
class TestParentDirectories(tests.TestCaseInTempDir):
1086
 
    """Test osutils.parent_directories()"""
1087
 
 
1088
 
    def test_parent_directories(self):
1089
 
        self.assertEqual([], osutils.parent_directories('a'))
1090
 
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
1091
 
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
1092
 
 
1093
 
 
1094
 
class TestMacFuncsDirs(tests.TestCaseInTempDir):
 
742
class TestMacFuncsDirs(TestCaseInTempDir):
1095
743
    """Test mac special functions that require directories."""
1096
744
 
1097
745
    def test_getcwd(self):
1098
 
        self.requireFeature(features.UnicodeFilenameFeature)
1099
 
        os.mkdir(u'B\xe5gfors')
 
746
        # On Mac, this will actually create Ba\u030agfors
 
747
        # but chdir will still work, because it accepts both paths
 
748
        try:
 
749
            os.mkdir(u'B\xe5gfors')
 
750
        except UnicodeError:
 
751
            raise TestSkipped("Unable to create Unicode filename")
 
752
 
1100
753
        os.chdir(u'B\xe5gfors')
1101
754
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1102
755
 
1103
756
    def test_getcwd_nonnorm(self):
1104
 
        self.requireFeature(features.UnicodeFilenameFeature)
1105
757
        # Test that _mac_getcwd() will normalize this path
1106
 
        os.mkdir(u'Ba\u030agfors')
 
758
        try:
 
759
            os.mkdir(u'Ba\u030agfors')
 
760
        except UnicodeError:
 
761
            raise TestSkipped("Unable to create Unicode filename")
 
762
 
1107
763
        os.chdir(u'Ba\u030agfors')
1108
764
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1109
765
 
1110
766
 
1111
 
class TestChunksToLines(tests.TestCase):
1112
 
 
1113
 
    def test_smoketest(self):
1114
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
1115
 
                         osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
1116
 
        self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
1117
 
                         osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
1118
 
 
1119
 
    def test_osutils_binding(self):
1120
 
        from bzrlib.tests import test__chunks_to_lines
1121
 
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
1122
 
            from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1123
 
        else:
1124
 
            from bzrlib._chunks_to_lines_py import chunks_to_lines
1125
 
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
1126
 
 
1127
 
 
1128
 
class TestSplitLines(tests.TestCase):
 
767
class TestSplitLines(TestCase):
1129
768
 
1130
769
    def test_split_unicode(self):
1131
770
        self.assertEqual([u'foo\n', u'bar\xae'],
1138
777
                         osutils.split_lines('foo\rbar\n'))
1139
778
 
1140
779
 
1141
 
class TestWalkDirs(tests.TestCaseInTempDir):
1142
 
 
1143
 
    def assertExpectedBlocks(self, expected, result):
1144
 
        self.assertEqual(expected,
1145
 
                         [(dirinfo, [line[0:3] for line in block])
1146
 
                          for dirinfo, block in result])
1147
 
 
 
780
class TestWalkDirs(TestCaseInTempDir):
 
781
 
 
782
    def test_readdir(self):
 
783
        tree = [
 
784
            '.bzr/',
 
785
            '0file',
 
786
            '1dir/',
 
787
            '1dir/0file',
 
788
            '1dir/1dir/',
 
789
            '2file'
 
790
            ]
 
791
        self.build_tree(tree)
 
792
        expected_names = ['.bzr', '0file', '1dir', '2file']
 
793
        # read_dir returns pairs, which form a table with either None in all
 
794
        # the first columns, or a sort key to get best on-disk-read order, 
 
795
        # and the disk path name in utf-8 encoding in the second column.
 
796
        read_result = self.read_dir('.')
 
797
        # The second column is always the names, and every name except "." and
 
798
        # ".." should be present.
 
799
        names = sorted([row[1] for row in read_result])
 
800
        self.assertEqual(expected_names, names)
 
801
        expected_sort_key = None
 
802
        if read_result[0][0] is None:
 
803
            # No sort key returned - all keys must None
 
804
            operator = self.assertEqual
 
805
        else:
 
806
            # A sort key in the first row implies sort keys in the other rows.
 
807
            operator = self.assertNotEqual
 
808
        for row in read_result:
 
809
            operator(None, row[0])
 
810
 
 
811
    def test_compiled_extension_exists(self):
 
812
        self.requireFeature(ReadDirFeature)
 
813
        
1148
814
    def test_walkdirs(self):
1149
815
        tree = [
1150
816
            '.bzr',
1182
848
            result.append((dirdetail, dirblock))
1183
849
 
1184
850
        self.assertTrue(found_bzrdir)
1185
 
        self.assertExpectedBlocks(expected_dirblocks, result)
 
851
        self.assertEqual(expected_dirblocks,
 
852
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1186
853
        # you can search a subdir only, with a supplied prefix.
1187
854
        result = []
1188
855
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1189
856
            result.append(dirblock)
1190
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1191
 
 
1192
 
    def test_walkdirs_os_error(self):
1193
 
        # <https://bugs.launchpad.net/bzr/+bug/338653>
1194
 
        # Pyrex readdir didn't raise useful messages if it had an error
1195
 
        # reading the directory
1196
 
        if sys.platform == 'win32':
1197
 
            raise tests.TestNotApplicable(
1198
 
                "readdir IOError not tested on win32")
1199
 
        self.requireFeature(features.not_running_as_root)
1200
 
        os.mkdir("test-unreadable")
1201
 
        os.chmod("test-unreadable", 0000)
1202
 
        # must chmod it back so that it can be removed
1203
 
        self.addCleanup(os.chmod, "test-unreadable", 0700)
1204
 
        # The error is not raised until the generator is actually evaluated.
1205
 
        # (It would be ok if it happened earlier but at the moment it
1206
 
        # doesn't.)
1207
 
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
1208
 
        self.assertEqual('./test-unreadable', e.filename)
1209
 
        self.assertEqual(errno.EACCES, e.errno)
1210
 
        # Ensure the message contains the file name
1211
 
        self.assertContainsRe(str(e), "\./test-unreadable")
1212
 
 
1213
 
 
1214
 
    def test_walkdirs_encoding_error(self):
1215
 
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1216
 
        # walkdirs didn't raise a useful message when the filenames
1217
 
        # are not using the filesystem's encoding
1218
 
 
1219
 
        # require a bytestring based filesystem
1220
 
        self.requireFeature(features.ByteStringNamedFilesystem)
1221
 
 
1222
 
        tree = [
1223
 
            '.bzr',
1224
 
            '0file',
1225
 
            '1dir/',
1226
 
            '1dir/0file',
1227
 
            '1dir/1dir/',
1228
 
            '1file'
1229
 
            ]
1230
 
 
1231
 
        self.build_tree(tree)
1232
 
 
1233
 
        # rename the 1file to a latin-1 filename
1234
 
        os.rename("./1file", "\xe8file")
1235
 
        if "\xe8file" not in os.listdir("."):
1236
 
            self.skip("Lack filesystem that preserves arbitrary bytes")
1237
 
 
1238
 
        self._save_platform_info()
1239
 
        win32utils.winver = None # Avoid the win32 detection code
1240
 
        osutils._fs_enc = 'UTF-8'
1241
 
 
1242
 
        # this should raise on error
1243
 
        def attempt():
1244
 
            for dirdetail, dirblock in osutils.walkdirs('.'):
1245
 
                pass
1246
 
 
1247
 
        self.assertRaises(errors.BadFilenameEncoding, attempt)
 
857
        self.assertEqual(expected_dirblocks[1:],
 
858
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1248
859
 
1249
860
    def test__walkdirs_utf8(self):
1250
861
        tree = [
1283
894
            result.append((dirdetail, dirblock))
1284
895
 
1285
896
        self.assertTrue(found_bzrdir)
1286
 
        self.assertExpectedBlocks(expected_dirblocks, result)
1287
 
 
 
897
        self.assertEqual(expected_dirblocks,
 
898
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1288
899
        # you can search a subdir only, with a supplied prefix.
1289
900
        result = []
1290
901
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1291
902
            result.append(dirblock)
1292
 
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
 
903
        self.assertEqual(expected_dirblocks[1:],
 
904
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1293
905
 
1294
906
    def _filter_out_stat(self, result):
1295
907
        """Filter out the stat value from the walkdirs result"""
1300
912
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1301
913
            dirblock[:] = new_dirblock
1302
914
 
 
915
    def test__walkdirs_utf8_selection(self):
 
916
        # Just trigger the function once, to make sure it has selected a real
 
917
        # implementation.
 
918
        list(osutils._walkdirs_utf8('.'))
 
919
        if WalkdirsWin32Feature.available():
 
920
            # If the compiled form is available, make sure it is used
 
921
            from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
922
            self.assertIs(_walkdirs_utf8_win32_find_file,
 
923
                          osutils._real_walkdirs_utf8)
 
924
        elif sys.platform == 'win32':
 
925
            self.assertIs(osutils._walkdirs_unicode_to_utf8,
 
926
                          osutils._real_walkdirs_utf8)
 
927
        elif osutils._fs_enc.upper() in ('UTF-8', 'ASCII', 'ANSI_X3.4-1968'): # ascii
 
928
            self.assertIs(osutils._walkdirs_fs_utf8,
 
929
                          osutils._real_walkdirs_utf8)
 
930
        else:
 
931
            self.assertIs(osutils._walkdirs_unicode_to_utf8,
 
932
                          osutils._real_walkdirs_utf8)
 
933
 
1303
934
    def _save_platform_info(self):
1304
 
        self.overrideAttr(win32utils, 'winver')
1305
 
        self.overrideAttr(osutils, '_fs_enc')
1306
 
        self.overrideAttr(osutils, '_selected_dir_reader')
 
935
        cur_winver = win32utils.winver
 
936
        cur_fs_enc = osutils._fs_enc
 
937
        cur_real_walkdirs_utf8 = osutils._real_walkdirs_utf8
 
938
        def restore():
 
939
            win32utils.winver = cur_winver
 
940
            osutils._fs_enc = cur_fs_enc
 
941
            osutils._real_walkdirs_utf8 = cur_real_walkdirs_utf8
 
942
        self.addCleanup(restore)
1307
943
 
1308
 
    def assertDirReaderIs(self, expected):
 
944
    def assertWalkdirsUtf8Is(self, expected):
1309
945
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1310
946
        # Force it to redetect
1311
 
        osutils._selected_dir_reader = None
 
947
        osutils._real_walkdirs_utf8 = None
1312
948
        # Nothing to list, but should still trigger the selection logic
1313
949
        self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
1314
 
        self.assertIsInstance(osutils._selected_dir_reader, expected)
 
950
        self.assertIs(expected, osutils._real_walkdirs_utf8)
1315
951
 
1316
952
    def test_force_walkdirs_utf8_fs_utf8(self):
1317
 
        self.requireFeature(UTF8DirReaderFeature)
1318
953
        self._save_platform_info()
1319
954
        win32utils.winver = None # Avoid the win32 detection code
1320
 
        osutils._fs_enc = 'utf-8'
1321
 
        self.assertDirReaderIs(
1322
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
955
        osutils._fs_enc = 'UTF-8'
 
956
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1323
957
 
1324
958
    def test_force_walkdirs_utf8_fs_ascii(self):
1325
 
        self.requireFeature(UTF8DirReaderFeature)
1326
 
        self._save_platform_info()
1327
 
        win32utils.winver = None # Avoid the win32 detection code
1328
 
        osutils._fs_enc = 'ascii'
1329
 
        self.assertDirReaderIs(
1330
 
            UTF8DirReaderFeature.module.UTF8DirReader)
 
959
        self._save_platform_info()
 
960
        win32utils.winver = None # Avoid the win32 detection code
 
961
        osutils._fs_enc = 'US-ASCII'
 
962
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
 
963
 
 
964
    def test_force_walkdirs_utf8_fs_ANSI(self):
 
965
        self._save_platform_info()
 
966
        win32utils.winver = None # Avoid the win32 detection code
 
967
        osutils._fs_enc = 'ANSI_X3.4-1968'
 
968
        self.assertWalkdirsUtf8Is(osutils._walkdirs_fs_utf8)
1331
969
 
1332
970
    def test_force_walkdirs_utf8_fs_latin1(self):
1333
971
        self._save_platform_info()
1334
972
        win32utils.winver = None # Avoid the win32 detection code
1335
 
        osutils._fs_enc = 'iso-8859-1'
1336
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
973
        osutils._fs_enc = 'latin1'
 
974
        self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1337
975
 
1338
976
    def test_force_walkdirs_utf8_nt(self):
1339
 
        # Disabled because the thunk of the whole walkdirs api is disabled.
1340
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
977
        self.requireFeature(WalkdirsWin32Feature)
1341
978
        self._save_platform_info()
1342
979
        win32utils.winver = 'Windows NT'
1343
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1344
 
        self.assertDirReaderIs(Win32ReadDir)
 
980
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
981
        self.assertWalkdirsUtf8Is(_walkdirs_utf8_win32_find_file)
1345
982
 
1346
 
    def test_force_walkdirs_utf8_98(self):
1347
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
 
983
    def test_force_walkdirs_utf8_nt(self):
 
984
        self.requireFeature(WalkdirsWin32Feature)
1348
985
        self._save_platform_info()
1349
986
        win32utils.winver = 'Windows 98'
1350
 
        self.assertDirReaderIs(osutils.UnicodeDirReader)
 
987
        self.assertWalkdirsUtf8Is(osutils._walkdirs_unicode_to_utf8)
1351
988
 
1352
989
    def test_unicode_walkdirs(self):
1353
990
        """Walkdirs should always return unicode paths."""
1354
 
        self.requireFeature(features.UnicodeFilenameFeature)
1355
991
        name0 = u'0file-\xb6'
1356
992
        name1 = u'1dir-\u062c\u0648'
1357
993
        name2 = u'2file-\u0633'
1362
998
            name1 + '/' + name1 + '/',
1363
999
            name2,
1364
1000
            ]
1365
 
        self.build_tree(tree)
 
1001
        try:
 
1002
            self.build_tree(tree)
 
1003
        except UnicodeError:
 
1004
            raise TestSkipped('Could not represent Unicode chars'
 
1005
                              ' in current encoding.')
1366
1006
        expected_dirblocks = [
1367
1007
                ((u'', u'.'),
1368
1008
                 [(name0, name0, 'file', './' + name0),
1394
1034
 
1395
1035
        The abspath portion might be in unicode or utf-8
1396
1036
        """
1397
 
        self.requireFeature(features.UnicodeFilenameFeature)
1398
1037
        name0 = u'0file-\xb6'
1399
1038
        name1 = u'1dir-\u062c\u0648'
1400
1039
        name2 = u'2file-\u0633'
1405
1044
            name1 + '/' + name1 + '/',
1406
1045
            name2,
1407
1046
            ]
1408
 
        self.build_tree(tree)
 
1047
        try:
 
1048
            self.build_tree(tree)
 
1049
        except UnicodeError:
 
1050
            raise TestSkipped('Could not represent Unicode chars'
 
1051
                              ' in current encoding.')
1409
1052
        name0 = name0.encode('utf8')
1410
1053
        name1 = name1.encode('utf8')
1411
1054
        name2 = name2.encode('utf8')
1450
1093
            result.append((dirdetail, new_dirblock))
1451
1094
        self.assertEqual(expected_dirblocks, result)
1452
1095
 
1453
 
    def test__walkdirs_utf8_with_unicode_fs(self):
1454
 
        """UnicodeDirReader should be a safe fallback everywhere
 
1096
    def test_unicode__walkdirs_unicode_to_utf8(self):
 
1097
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
1455
1098
 
1456
1099
        The abspath portion should be in unicode
1457
1100
        """
1458
 
        self.requireFeature(features.UnicodeFilenameFeature)
1459
 
        # Use the unicode reader. TODO: split into driver-and-driven unit
1460
 
        # tests.
1461
 
        self._save_platform_info()
1462
 
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
1463
1101
        name0u = u'0file-\xb6'
1464
1102
        name1u = u'1dir-\u062c\u0648'
1465
1103
        name2u = u'2file-\u0633'
1470
1108
            name1u + '/' + name1u + '/',
1471
1109
            name2u,
1472
1110
            ]
1473
 
        self.build_tree(tree)
 
1111
        try:
 
1112
            self.build_tree(tree)
 
1113
        except UnicodeError:
 
1114
            raise TestSkipped('Could not represent Unicode chars'
 
1115
                              ' in current encoding.')
1474
1116
        name0 = name0u.encode('utf8')
1475
1117
        name1 = name1u.encode('utf8')
1476
1118
        name2 = name2u.encode('utf8')
1496
1138
                 ]
1497
1139
                ),
1498
1140
            ]
1499
 
        result = list(osutils._walkdirs_utf8('.'))
 
1141
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
1500
1142
        self._filter_out_stat(result)
1501
1143
        self.assertEqual(expected_dirblocks, result)
1502
1144
 
1503
 
    def test__walkdirs_utf8_win32readdir(self):
1504
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1505
 
        self.requireFeature(features.UnicodeFilenameFeature)
1506
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
1507
 
        self._save_platform_info()
1508
 
        osutils._selected_dir_reader = Win32ReadDir()
 
1145
    def test__walkdirs_utf_win32_find_file(self):
 
1146
        self.requireFeature(WalkdirsWin32Feature)
 
1147
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1148
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1509
1149
        name0u = u'0file-\xb6'
1510
1150
        name1u = u'1dir-\u062c\u0648'
1511
1151
        name2u = u'2file-\u0633'
1542
1182
                 ]
1543
1183
                ),
1544
1184
            ]
1545
 
        result = list(osutils._walkdirs_utf8(u'.'))
 
1185
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
1546
1186
        self._filter_out_stat(result)
1547
1187
        self.assertEqual(expected_dirblocks, result)
1548
1188
 
1558
1198
 
1559
1199
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1560
1200
        """make sure our Stat values are valid"""
1561
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1562
 
        self.requireFeature(features.UnicodeFilenameFeature)
1563
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1201
        self.requireFeature(WalkdirsWin32Feature)
 
1202
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1203
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1564
1204
        name0u = u'0file-\xb6'
1565
1205
        name0 = name0u.encode('utf8')
1566
1206
        self.build_tree([name0u])
1573
1213
        finally:
1574
1214
            f.close()
1575
1215
 
1576
 
        result = Win32ReadDir().read_dir('', u'.')
1577
 
        entry = result[0]
 
1216
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
 
1217
        entry = result[0][1][0]
1578
1218
        self.assertEqual((name0, name0, 'file'), entry[:3])
1579
1219
        self.assertEqual(u'./' + name0u, entry[4])
1580
1220
        self.assertStatIsCorrect(entry[4], entry[3])
1582
1222
 
1583
1223
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1584
1224
        """make sure our Stat values are valid"""
1585
 
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
1586
 
        self.requireFeature(features.UnicodeFilenameFeature)
1587
 
        from bzrlib._walkdirs_win32 import Win32ReadDir
 
1225
        self.requireFeature(WalkdirsWin32Feature)
 
1226
        self.requireFeature(tests.UnicodeFilenameFeature)
 
1227
        from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1588
1228
        name0u = u'0dir-\u062c\u0648'
1589
1229
        name0 = name0u.encode('utf8')
1590
1230
        self.build_tree([name0u + '/'])
1591
1231
 
1592
 
        result = Win32ReadDir().read_dir('', u'.')
1593
 
        entry = result[0]
 
1232
        result = list(_walkdirs_utf8_win32_find_file(u'.'))
 
1233
        entry = result[0][1][0]
1594
1234
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1595
1235
        self.assertEqual(u'./' + name0u, entry[4])
1596
1236
        self.assertStatIsCorrect(entry[4], entry[3])
1673
1313
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1674
1314
 
1675
1315
 
1676
 
class TestCopyTree(tests.TestCaseInTempDir):
1677
 
 
 
1316
class TestCopyTree(TestCaseInTempDir):
 
1317
    
1678
1318
    def test_copy_basic_tree(self):
1679
1319
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1680
1320
        osutils.copy_tree('source', 'target')
1689
1329
        self.assertEqual(['c'], os.listdir('target/b'))
1690
1330
 
1691
1331
    def test_copy_tree_symlinks(self):
1692
 
        self.requireFeature(features.SymlinkFeature)
 
1332
        self.requireFeature(SymlinkFeature)
1693
1333
        self.build_tree(['source/'])
1694
1334
        os.symlink('a/generic/path', 'source/lnk')
1695
1335
        osutils.copy_tree('source', 'target')
1720
1360
                          ('d', 'source/b', 'target/b'),
1721
1361
                          ('f', 'source/b/c', 'target/b/c'),
1722
1362
                         ], processed_files)
1723
 
        self.assertPathDoesNotExist('target')
 
1363
        self.failIfExists('target')
1724
1364
        if osutils.has_symlinks():
1725
1365
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1726
1366
 
1727
1367
 
1728
 
class TestSetUnsetEnv(tests.TestCase):
 
1368
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
1369
# [bialix] 2006/12/26
 
1370
 
 
1371
 
 
1372
class TestSetUnsetEnv(TestCase):
1729
1373
    """Test updating the environment"""
1730
1374
 
1731
1375
    def setUp(self):
1737
1381
        def cleanup():
1738
1382
            if 'BZR_TEST_ENV_VAR' in os.environ:
1739
1383
                del os.environ['BZR_TEST_ENV_VAR']
 
1384
 
1740
1385
        self.addCleanup(cleanup)
1741
1386
 
1742
1387
    def test_set(self):
1754
1399
 
1755
1400
    def test_unicode(self):
1756
1401
        """Environment can only contain plain strings
1757
 
 
 
1402
        
1758
1403
        So Unicode strings must be encoded.
1759
1404
        """
1760
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
 
1405
        uni_val, env_val = probe_unicode_in_user_encoding()
1761
1406
        if uni_val is None:
1762
 
            raise tests.TestSkipped(
1763
 
                'Cannot find a unicode character that works in encoding %s'
1764
 
                % (osutils.get_user_encoding(),))
 
1407
            raise TestSkipped('Cannot find a unicode character that works in'
 
1408
                              ' encoding %s' % (bzrlib.user_encoding,))
1765
1409
 
1766
1410
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1767
1411
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1772
1416
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1773
1417
        self.assertEqual('foo', old)
1774
1418
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1775
 
        self.assertFalse('BZR_TEST_ENV_VAR' in os.environ)
1776
 
 
1777
 
 
1778
 
class TestSizeShaFile(tests.TestCaseInTempDir):
1779
 
 
1780
 
    def test_sha_empty(self):
1781
 
        self.build_tree_contents([('foo', '')])
1782
 
        expected_sha = osutils.sha_string('')
1783
 
        f = open('foo')
1784
 
        self.addCleanup(f.close)
1785
 
        size, sha = osutils.size_sha_file(f)
1786
 
        self.assertEqual(0, size)
1787
 
        self.assertEqual(expected_sha, sha)
1788
 
 
1789
 
    def test_sha_mixed_endings(self):
1790
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1791
 
        self.build_tree_contents([('foo', text)])
1792
 
        expected_sha = osutils.sha_string(text)
1793
 
        f = open('foo', 'rb')
1794
 
        self.addCleanup(f.close)
1795
 
        size, sha = osutils.size_sha_file(f)
1796
 
        self.assertEqual(38, size)
1797
 
        self.assertEqual(expected_sha, sha)
1798
 
 
1799
 
 
1800
 
class TestShaFileByName(tests.TestCaseInTempDir):
1801
 
 
1802
 
    def test_sha_empty(self):
1803
 
        self.build_tree_contents([('foo', '')])
1804
 
        expected_sha = osutils.sha_string('')
1805
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1806
 
 
1807
 
    def test_sha_mixed_endings(self):
1808
 
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
1809
 
        self.build_tree_contents([('foo', text)])
1810
 
        expected_sha = osutils.sha_string(text)
1811
 
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1812
 
 
1813
 
 
1814
 
class TestResourceLoading(tests.TestCaseInTempDir):
 
1419
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
1420
 
 
1421
 
 
1422
class TestLocalTimeOffset(TestCase):
 
1423
 
 
1424
    def test_local_time_offset(self):
 
1425
        """Test that local_time_offset() returns a sane value."""
 
1426
        offset = osutils.local_time_offset()
 
1427
        self.assertTrue(isinstance(offset, int))
 
1428
        # Test that the offset is no more than a eighteen hours in
 
1429
        # either direction.
 
1430
        # Time zone handling is system specific, so it is difficult to
 
1431
        # do more specific tests, but a value outside of this range is
 
1432
        # probably wrong.
 
1433
        eighteen_hours = 18 * 3600
 
1434
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1435
 
 
1436
    def test_local_time_offset_with_timestamp(self):
 
1437
        """Test that local_time_offset() works with a timestamp."""
 
1438
        offset = osutils.local_time_offset(1000000000.1234567)
 
1439
        self.assertTrue(isinstance(offset, int))
 
1440
        eighteen_hours = 18 * 3600
 
1441
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
1442
 
 
1443
 
 
1444
class TestShaFileByName(TestCaseInTempDir):
 
1445
 
 
1446
    def test_sha_empty(self):
 
1447
        self.build_tree_contents([('foo', '')])
 
1448
        expected_sha = osutils.sha_string('')
 
1449
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1450
 
 
1451
    def test_sha_mixed_endings(self):
 
1452
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
1453
        self.build_tree_contents([('foo', text)])
 
1454
        expected_sha = osutils.sha_string(text)
 
1455
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
 
1456
 
 
1457
 
 
1458
_debug_text = \
 
1459
r'''# Copyright (C) 2005, 2006 Canonical Ltd
 
1460
#
 
1461
# This program is free software; you can redistribute it and/or modify
 
1462
# it under the terms of the GNU General Public License as published by
 
1463
# the Free Software Foundation; either version 2 of the License, or
 
1464
# (at your option) any later version.
 
1465
#
 
1466
# This program is distributed in the hope that it will be useful,
 
1467
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
1468
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
1469
# GNU General Public License for more details.
 
1470
#
 
1471
# You should have received a copy of the GNU General Public License
 
1472
# along with this program; if not, write to the Free Software
 
1473
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
1474
 
 
1475
 
 
1476
# NOTE: If update these, please also update the help for global-options in
 
1477
#       bzrlib/help_topics/__init__.py
 
1478
 
 
1479
debug_flags = set()
 
1480
"""Set of flags that enable different debug behaviour.
 
1481
 
 
1482
These are set with eg ``-Dlock`` on the bzr command line.
 
1483
 
 
1484
Options include:
 
1485
 
 
1486
 * auth - show authentication sections used
 
1487
 * error - show stack traces for all top level exceptions
 
1488
 * evil - capture call sites that do expensive or badly-scaling operations.
 
1489
 * fetch - trace history copying between repositories
 
1490
 * graph - trace graph traversal information
 
1491
 * hashcache - log every time a working file is read to determine its hash
 
1492
 * hooks - trace hook execution
 
1493
 * hpss - trace smart protocol requests and responses
 
1494
 * http - trace http connections, requests and responses
 
1495
 * index - trace major index operations
 
1496
 * knit - trace knit operations
 
1497
 * lock - trace when lockdir locks are taken or released
 
1498
 * merge - emit information for debugging merges
 
1499
 * pack - emit information about pack operations
 
1500
 
 
1501
"""
 
1502
'''
 
1503
 
 
1504
 
 
1505
class TestResourceLoading(TestCaseInTempDir):
1815
1506
 
1816
1507
    def test_resource_string(self):
1817
1508
        # test resource in bzrlib
1818
1509
        text = osutils.resource_string('bzrlib', 'debug.py')
1819
 
        self.assertContainsRe(text, "debug_flags = set()")
 
1510
        self.assertEquals(_debug_text, text)
1820
1511
        # test resource under bzrlib
1821
1512
        text = osutils.resource_string('bzrlib.ui', 'text.py')
1822
1513
        self.assertContainsRe(text, "class TextUIFactory")
1825
1516
            'yyy.xx')
1826
1517
        # test unknown resource
1827
1518
        self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1828
 
 
1829
 
 
1830
 
class TestReCompile(tests.TestCase):
1831
 
 
1832
 
    def _deprecated_re_compile_checked(self, *args, **kwargs):
1833
 
        return self.applyDeprecated(symbol_versioning.deprecated_in((2, 2, 0)),
1834
 
            osutils.re_compile_checked, *args, **kwargs)
1835
 
 
1836
 
    def test_re_compile_checked(self):
1837
 
        r = self._deprecated_re_compile_checked(r'A*', re.IGNORECASE)
1838
 
        self.assertTrue(r.match('aaaa'))
1839
 
        self.assertTrue(r.match('aAaA'))
1840
 
 
1841
 
    def test_re_compile_checked_error(self):
1842
 
        # like https://bugs.launchpad.net/bzr/+bug/251352
1843
 
 
1844
 
        # Due to possible test isolation error, re.compile is not lazy at
1845
 
        # this point. We re-install lazy compile.
1846
 
        lazy_regex.install_lazy_compile()
1847
 
        err = self.assertRaises(
1848
 
            errors.BzrCommandError,
1849
 
            self._deprecated_re_compile_checked, '*', re.IGNORECASE, 'test case')
1850
 
        self.assertEqual(
1851
 
            'Invalid regular expression in test case: '
1852
 
            '"*" nothing to repeat',
1853
 
            str(err))
1854
 
 
1855
 
 
1856
 
class TestDirReader(tests.TestCaseInTempDir):
1857
 
 
1858
 
    scenarios = dir_reader_scenarios()
1859
 
 
1860
 
    # Set by load_tests
1861
 
    _dir_reader_class = None
1862
 
    _native_to_unicode = None
1863
 
 
1864
 
    def setUp(self):
1865
 
        super(TestDirReader, self).setUp()
1866
 
        self.overrideAttr(osutils,
1867
 
                          '_selected_dir_reader', self._dir_reader_class())
1868
 
 
1869
 
    def _get_ascii_tree(self):
1870
 
        tree = [
1871
 
            '0file',
1872
 
            '1dir/',
1873
 
            '1dir/0file',
1874
 
            '1dir/1dir/',
1875
 
            '2file'
1876
 
            ]
1877
 
        expected_dirblocks = [
1878
 
                (('', '.'),
1879
 
                 [('0file', '0file', 'file'),
1880
 
                  ('1dir', '1dir', 'directory'),
1881
 
                  ('2file', '2file', 'file'),
1882
 
                 ]
1883
 
                ),
1884
 
                (('1dir', './1dir'),
1885
 
                 [('1dir/0file', '0file', 'file'),
1886
 
                  ('1dir/1dir', '1dir', 'directory'),
1887
 
                 ]
1888
 
                ),
1889
 
                (('1dir/1dir', './1dir/1dir'),
1890
 
                 [
1891
 
                 ]
1892
 
                ),
1893
 
            ]
1894
 
        return tree, expected_dirblocks
1895
 
 
1896
 
    def test_walk_cur_dir(self):
1897
 
        tree, expected_dirblocks = self._get_ascii_tree()
1898
 
        self.build_tree(tree)
1899
 
        result = list(osutils._walkdirs_utf8('.'))
1900
 
        # Filter out stat and abspath
1901
 
        self.assertEqual(expected_dirblocks,
1902
 
                         [(dirinfo, [line[0:3] for line in block])
1903
 
                          for dirinfo, block in result])
1904
 
 
1905
 
    def test_walk_sub_dir(self):
1906
 
        tree, expected_dirblocks = self._get_ascii_tree()
1907
 
        self.build_tree(tree)
1908
 
        # you can search a subdir only, with a supplied prefix.
1909
 
        result = list(osutils._walkdirs_utf8('./1dir', '1dir'))
1910
 
        # Filter out stat and abspath
1911
 
        self.assertEqual(expected_dirblocks[1:],
1912
 
                         [(dirinfo, [line[0:3] for line in block])
1913
 
                          for dirinfo, block in result])
1914
 
 
1915
 
    def _get_unicode_tree(self):
1916
 
        name0u = u'0file-\xb6'
1917
 
        name1u = u'1dir-\u062c\u0648'
1918
 
        name2u = u'2file-\u0633'
1919
 
        tree = [
1920
 
            name0u,
1921
 
            name1u + '/',
1922
 
            name1u + '/' + name0u,
1923
 
            name1u + '/' + name1u + '/',
1924
 
            name2u,
1925
 
            ]
1926
 
        name0 = name0u.encode('UTF-8')
1927
 
        name1 = name1u.encode('UTF-8')
1928
 
        name2 = name2u.encode('UTF-8')
1929
 
        expected_dirblocks = [
1930
 
                (('', '.'),
1931
 
                 [(name0, name0, 'file', './' + name0u),
1932
 
                  (name1, name1, 'directory', './' + name1u),
1933
 
                  (name2, name2, 'file', './' + name2u),
1934
 
                 ]
1935
 
                ),
1936
 
                ((name1, './' + name1u),
1937
 
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
1938
 
                                                        + '/' + name0u),
1939
 
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
1940
 
                                                            + '/' + name1u),
1941
 
                 ]
1942
 
                ),
1943
 
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1944
 
                 [
1945
 
                 ]
1946
 
                ),
1947
 
            ]
1948
 
        return tree, expected_dirblocks
1949
 
 
1950
 
    def _filter_out(self, raw_dirblocks):
1951
 
        """Filter out a walkdirs_utf8 result.
1952
 
 
1953
 
        stat field is removed, all native paths are converted to unicode
1954
 
        """
1955
 
        filtered_dirblocks = []
1956
 
        for dirinfo, block in raw_dirblocks:
1957
 
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1958
 
            details = []
1959
 
            for line in block:
1960
 
                details.append(line[0:3] + (self._native_to_unicode(line[4]), ))
1961
 
            filtered_dirblocks.append((dirinfo, details))
1962
 
        return filtered_dirblocks
1963
 
 
1964
 
    def test_walk_unicode_tree(self):
1965
 
        self.requireFeature(features.UnicodeFilenameFeature)
1966
 
        tree, expected_dirblocks = self._get_unicode_tree()
1967
 
        self.build_tree(tree)
1968
 
        result = list(osutils._walkdirs_utf8('.'))
1969
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1970
 
 
1971
 
    def test_symlink(self):
1972
 
        self.requireFeature(features.SymlinkFeature)
1973
 
        self.requireFeature(features.UnicodeFilenameFeature)
1974
 
        target = u'target\N{Euro Sign}'
1975
 
        link_name = u'l\N{Euro Sign}nk'
1976
 
        os.symlink(target, link_name)
1977
 
        target_utf8 = target.encode('UTF-8')
1978
 
        link_name_utf8 = link_name.encode('UTF-8')
1979
 
        expected_dirblocks = [
1980
 
                (('', '.'),
1981
 
                 [(link_name_utf8, link_name_utf8,
1982
 
                   'symlink', './' + link_name),],
1983
 
                 )]
1984
 
        result = list(osutils._walkdirs_utf8('.'))
1985
 
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1986
 
 
1987
 
 
1988
 
class TestReadLink(tests.TestCaseInTempDir):
1989
 
    """Exposes os.readlink() problems and the osutils solution.
1990
 
 
1991
 
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1992
 
    unicode string will be returned if a unicode string is passed.
1993
 
 
1994
 
    But prior python versions failed to properly encode the passed unicode
1995
 
    string.
1996
 
    """
1997
 
    _test_needs_features = [features.SymlinkFeature, features.UnicodeFilenameFeature]
1998
 
 
1999
 
    def setUp(self):
2000
 
        super(tests.TestCaseInTempDir, self).setUp()
2001
 
        self.link = u'l\N{Euro Sign}ink'
2002
 
        self.target = u'targe\N{Euro Sign}t'
2003
 
        os.symlink(self.target, self.link)
2004
 
 
2005
 
    def test_os_readlink_link_encoding(self):
2006
 
        self.assertEqual(self.target,  os.readlink(self.link))
2007
 
 
2008
 
    def test_os_readlink_link_decoding(self):
2009
 
        self.assertEqual(self.target.encode(osutils._fs_enc),
2010
 
                          os.readlink(self.link.encode(osutils._fs_enc)))
2011
 
 
2012
 
 
2013
 
class TestConcurrency(tests.TestCase):
2014
 
 
2015
 
    def setUp(self):
2016
 
        super(TestConcurrency, self).setUp()
2017
 
        self.overrideAttr(osutils, '_cached_local_concurrency')
2018
 
 
2019
 
    def test_local_concurrency(self):
2020
 
        concurrency = osutils.local_concurrency()
2021
 
        self.assertIsInstance(concurrency, int)
2022
 
 
2023
 
    def test_local_concurrency_environment_variable(self):
2024
 
        self.overrideEnv('BZR_CONCURRENCY', '2')
2025
 
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
2026
 
        self.overrideEnv('BZR_CONCURRENCY', '3')
2027
 
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
2028
 
        self.overrideEnv('BZR_CONCURRENCY', 'foo')
2029
 
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
2030
 
 
2031
 
    def test_option_concurrency(self):
2032
 
        self.overrideEnv('BZR_CONCURRENCY', '1')
2033
 
        self.run_bzr('rocks --concurrency 42')
2034
 
        # Command line overrides environment variable
2035
 
        self.assertEqual('42', os.environ['BZR_CONCURRENCY'])
2036
 
        self.assertEqual(42, osutils.local_concurrency(use_cache=False))
2037
 
 
2038
 
 
2039
 
class TestFailedToLoadExtension(tests.TestCase):
2040
 
 
2041
 
    def _try_loading(self):
2042
 
        try:
2043
 
            import bzrlib._fictional_extension_py
2044
 
        except ImportError, e:
2045
 
            osutils.failed_to_load_extension(e)
2046
 
            return True
2047
 
 
2048
 
    def setUp(self):
2049
 
        super(TestFailedToLoadExtension, self).setUp()
2050
 
        self.overrideAttr(osutils, '_extension_load_failures', [])
2051
 
 
2052
 
    def test_failure_to_load(self):
2053
 
        self._try_loading()
2054
 
        self.assertLength(1, osutils._extension_load_failures)
2055
 
        self.assertEqual(osutils._extension_load_failures[0],
2056
 
            "No module named _fictional_extension_py")
2057
 
 
2058
 
    def test_report_extension_load_failures_no_warning(self):
2059
 
        self.assertTrue(self._try_loading())
2060
 
        warnings, result = self.callCatchWarnings(osutils.report_extension_load_failures)
2061
 
        # it used to give a Python warning; it no longer does
2062
 
        self.assertLength(0, warnings)
2063
 
 
2064
 
    def test_report_extension_load_failures_message(self):
2065
 
        log = StringIO()
2066
 
        trace.push_log_file(log)
2067
 
        self.assertTrue(self._try_loading())
2068
 
        osutils.report_extension_load_failures()
2069
 
        self.assertContainsRe(
2070
 
            log.getvalue(),
2071
 
            r"bzr: warning: some compiled extensions could not be loaded; "
2072
 
            "see <https://answers\.launchpad\.net/bzr/\+faq/703>\n"
2073
 
            )
2074
 
 
2075
 
 
2076
 
class TestTerminalWidth(tests.TestCase):
2077
 
 
2078
 
    def setUp(self):
2079
 
        super(TestTerminalWidth, self).setUp()
2080
 
        self._orig_terminal_size_state = osutils._terminal_size_state
2081
 
        self._orig_first_terminal_size = osutils._first_terminal_size
2082
 
        self.addCleanup(self.restore_osutils_globals)
2083
 
        osutils._terminal_size_state = 'no_data'
2084
 
        osutils._first_terminal_size = None
2085
 
 
2086
 
    def restore_osutils_globals(self):
2087
 
        osutils._terminal_size_state = self._orig_terminal_size_state
2088
 
        osutils._first_terminal_size = self._orig_first_terminal_size
2089
 
 
2090
 
    def replace_stdout(self, new):
2091
 
        self.overrideAttr(sys, 'stdout', new)
2092
 
 
2093
 
    def replace__terminal_size(self, new):
2094
 
        self.overrideAttr(osutils, '_terminal_size', new)
2095
 
 
2096
 
    def set_fake_tty(self):
2097
 
 
2098
 
        class I_am_a_tty(object):
2099
 
            def isatty(self):
2100
 
                return True
2101
 
 
2102
 
        self.replace_stdout(I_am_a_tty())
2103
 
 
2104
 
    def test_default_values(self):
2105
 
        self.assertEqual(80, osutils.default_terminal_width)
2106
 
 
2107
 
    def test_defaults_to_BZR_COLUMNS(self):
2108
 
        # BZR_COLUMNS is set by the test framework
2109
 
        self.assertNotEqual('12', os.environ['BZR_COLUMNS'])
2110
 
        self.overrideEnv('BZR_COLUMNS', '12')
2111
 
        self.assertEqual(12, osutils.terminal_width())
2112
 
 
2113
 
    def test_BZR_COLUMNS_0_no_limit(self):
2114
 
        self.overrideEnv('BZR_COLUMNS', '0')
2115
 
        self.assertEqual(None, osutils.terminal_width())
2116
 
 
2117
 
    def test_falls_back_to_COLUMNS(self):
2118
 
        self.overrideEnv('BZR_COLUMNS', None)
2119
 
        self.assertNotEqual('42', os.environ['COLUMNS'])
2120
 
        self.set_fake_tty()
2121
 
        self.overrideEnv('COLUMNS', '42')
2122
 
        self.assertEqual(42, osutils.terminal_width())
2123
 
 
2124
 
    def test_tty_default_without_columns(self):
2125
 
        self.overrideEnv('BZR_COLUMNS', None)
2126
 
        self.overrideEnv('COLUMNS', None)
2127
 
 
2128
 
        def terminal_size(w, h):
2129
 
            return 42, 42
2130
 
 
2131
 
        self.set_fake_tty()
2132
 
        # We need to override the osutils definition as it depends on the
2133
 
        # running environment that we can't control (PQM running without a
2134
 
        # controlling terminal is one example).
2135
 
        self.replace__terminal_size(terminal_size)
2136
 
        self.assertEqual(42, osutils.terminal_width())
2137
 
 
2138
 
    def test_non_tty_default_without_columns(self):
2139
 
        self.overrideEnv('BZR_COLUMNS', None)
2140
 
        self.overrideEnv('COLUMNS', None)
2141
 
        self.replace_stdout(None)
2142
 
        self.assertEqual(None, osutils.terminal_width())
2143
 
 
2144
 
    def test_no_TIOCGWINSZ(self):
2145
 
        self.requireFeature(term_ios_feature)
2146
 
        termios = term_ios_feature.module
2147
 
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2148
 
        try:
2149
 
            orig = termios.TIOCGWINSZ
2150
 
        except AttributeError:
2151
 
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2152
 
            pass
2153
 
        else:
2154
 
            self.overrideAttr(termios, 'TIOCGWINSZ')
2155
 
            del termios.TIOCGWINSZ
2156
 
        self.overrideEnv('BZR_COLUMNS', None)
2157
 
        self.overrideEnv('COLUMNS', None)
2158
 
        # Whatever the result is, if we don't raise an exception, it's ok.
2159
 
        osutils.terminal_width()
2160
 
 
2161
 
 
2162
 
class TestCreationOps(tests.TestCaseInTempDir):
2163
 
    _test_needs_features = [features.chown_feature]
2164
 
 
2165
 
    def setUp(self):
2166
 
        super(TestCreationOps, self).setUp()
2167
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
2168
 
 
2169
 
        # params set by call to _dummy_chown
2170
 
        self.path = self.uid = self.gid = None
2171
 
 
2172
 
    def _dummy_chown(self, path, uid, gid):
2173
 
        self.path, self.uid, self.gid = path, uid, gid
2174
 
 
2175
 
    def test_copy_ownership_from_path(self):
2176
 
        """copy_ownership_from_path test with specified src."""
2177
 
        ownsrc = '/'
2178
 
        f = open('test_file', 'wt')
2179
 
        osutils.copy_ownership_from_path('test_file', ownsrc)
2180
 
 
2181
 
        s = os.stat(ownsrc)
2182
 
        self.assertEqual(self.path, 'test_file')
2183
 
        self.assertEqual(self.uid, s.st_uid)
2184
 
        self.assertEqual(self.gid, s.st_gid)
2185
 
 
2186
 
    def test_copy_ownership_nonesrc(self):
2187
 
        """copy_ownership_from_path test with src=None."""
2188
 
        f = open('test_file', 'wt')
2189
 
        # should use parent dir for permissions
2190
 
        osutils.copy_ownership_from_path('test_file')
2191
 
 
2192
 
        s = os.stat('..')
2193
 
        self.assertEqual(self.path, 'test_file')
2194
 
        self.assertEqual(self.uid, s.st_uid)
2195
 
        self.assertEqual(self.gid, s.st_gid)
2196
 
 
2197
 
 
2198
 
class TestPathFromEnviron(tests.TestCase):
2199
 
 
2200
 
    def test_is_unicode(self):
2201
 
        self.overrideEnv('BZR_TEST_PATH', './anywhere at all/')
2202
 
        path = osutils.path_from_environ('BZR_TEST_PATH')
2203
 
        self.assertIsInstance(path, unicode)
2204
 
        self.assertEqual(u'./anywhere at all/', path)
2205
 
 
2206
 
    def test_posix_path_env_ascii(self):
2207
 
        self.overrideEnv('BZR_TEST_PATH', '/tmp')
2208
 
        home = osutils._posix_path_from_environ('BZR_TEST_PATH')
2209
 
        self.assertIsInstance(home, unicode)
2210
 
        self.assertEqual(u'/tmp', home)
2211
 
 
2212
 
    def test_posix_path_env_unicode(self):
2213
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2214
 
        self.overrideEnv('BZR_TEST_PATH', '/home/\xa7test')
2215
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2216
 
        self.assertEqual(u'/home/\xa7test',
2217
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2218
 
        osutils._fs_enc = "iso8859-5"
2219
 
        self.assertEqual(u'/home/\u0407test',
2220
 
            osutils._posix_path_from_environ('BZR_TEST_PATH'))
2221
 
        osutils._fs_enc = "utf-8"
2222
 
        self.assertRaises(errors.BadFilenameEncoding,
2223
 
            osutils._posix_path_from_environ, 'BZR_TEST_PATH')
2224
 
 
2225
 
 
2226
 
class TestGetHomeDir(tests.TestCase):
2227
 
 
2228
 
    def test_is_unicode(self):
2229
 
        home = osutils._get_home_dir()
2230
 
        self.assertIsInstance(home, unicode)
2231
 
 
2232
 
    def test_posix_homeless(self):
2233
 
        self.overrideEnv('HOME', None)
2234
 
        home = osutils._get_home_dir()
2235
 
        self.assertIsInstance(home, unicode)
2236
 
 
2237
 
    def test_posix_home_ascii(self):
2238
 
        self.overrideEnv('HOME', '/home/test')
2239
 
        home = osutils._posix_get_home_dir()
2240
 
        self.assertIsInstance(home, unicode)
2241
 
        self.assertEqual(u'/home/test', home)
2242
 
 
2243
 
    def test_posix_home_unicode(self):
2244
 
        self.requireFeature(features.ByteStringNamedFilesystem)
2245
 
        self.overrideEnv('HOME', '/home/\xa7test')
2246
 
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2247
 
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2248
 
        osutils._fs_enc = "iso8859-5"
2249
 
        self.assertEqual(u'/home/\u0407test', osutils._posix_get_home_dir())
2250
 
        osutils._fs_enc = "utf-8"
2251
 
        self.assertRaises(errors.BadFilenameEncoding,
2252
 
            osutils._posix_get_home_dir)
2253
 
 
2254
 
 
2255
 
class TestGetuserUnicode(tests.TestCase):
2256
 
 
2257
 
    def test_is_unicode(self):
2258
 
        user = osutils.getuser_unicode()
2259
 
        self.assertIsInstance(user, unicode)
2260
 
 
2261
 
    def envvar_to_override(self):
2262
 
        if sys.platform == "win32":
2263
 
            # Disable use of platform calls on windows so envvar is used
2264
 
            self.overrideAttr(win32utils, 'has_ctypes', False)
2265
 
            return 'USERNAME' # only variable used on windows
2266
 
        return 'LOGNAME' # first variable checked by getpass.getuser()
2267
 
 
2268
 
    def test_ascii_user(self):
2269
 
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
2270
 
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2271
 
 
2272
 
    def test_unicode_user(self):
2273
 
        ue = osutils.get_user_encoding()
2274
 
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2275
 
        if uni_val is None:
2276
 
            raise tests.TestSkipped(
2277
 
                'Cannot find a unicode character that works in encoding %s'
2278
 
                % (osutils.get_user_encoding(),))
2279
 
        uni_username = u'jrandom' + uni_val
2280
 
        encoded_username = uni_username.encode(ue)
2281
 
        self.overrideEnv(self.envvar_to_override(), encoded_username)
2282
 
        self.assertEqual(uni_username, osutils.getuser_unicode())
2283
 
 
2284
 
 
2285
 
class TestBackupNames(tests.TestCase):
2286
 
 
2287
 
    def setUp(self):
2288
 
        super(TestBackupNames, self).setUp()
2289
 
        self.backups = []
2290
 
 
2291
 
    def backup_exists(self, name):
2292
 
        return name in self.backups
2293
 
 
2294
 
    def available_backup_name(self, name):
2295
 
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2296
 
        self.backups.append(backup_name)
2297
 
        return backup_name
2298
 
 
2299
 
    def assertBackupName(self, expected, name):
2300
 
        self.assertEqual(expected, self.available_backup_name(name))
2301
 
 
2302
 
    def test_empty(self):
2303
 
        self.assertBackupName('file.~1~', 'file')
2304
 
 
2305
 
    def test_existing(self):
2306
 
        self.available_backup_name('file')
2307
 
        self.available_backup_name('file')
2308
 
        self.assertBackupName('file.~3~', 'file')
2309
 
        # Empty slots are found, this is not a strict requirement and may be
2310
 
        # revisited if we test against all implementations.
2311
 
        self.backups.remove('file.~2~')
2312
 
        self.assertBackupName('file.~2~', 'file')
2313
 
 
2314
 
 
2315
 
class TestFindExecutableInPath(tests.TestCase):
2316
 
 
2317
 
    def test_windows(self):
2318
 
        if sys.platform != 'win32':
2319
 
            raise tests.TestSkipped('test requires win32')
2320
 
        self.assertTrue(osutils.find_executable_on_path('explorer') is not None)
2321
 
        self.assertTrue(
2322
 
            osutils.find_executable_on_path('explorer.exe') is not None)
2323
 
        self.assertTrue(
2324
 
            osutils.find_executable_on_path('EXPLORER.EXE') is not None)
2325
 
        self.assertTrue(
2326
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2327
 
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
2328
 
        
2329
 
    def test_windows_app_path(self):
2330
 
        if sys.platform != 'win32':
2331
 
            raise tests.TestSkipped('test requires win32')
2332
 
        # Override PATH env var so that exe can only be found on App Path
2333
 
        self.overrideEnv('PATH', '')
2334
 
        # Internt Explorer is always registered in the App Path
2335
 
        self.assertTrue(osutils.find_executable_on_path('iexplore') is not None)
2336
 
 
2337
 
    def test_other(self):
2338
 
        if sys.platform == 'win32':
2339
 
            raise tests.TestSkipped('test requires non-win32')
2340
 
        self.assertTrue(osutils.find_executable_on_path('sh') is not None)
2341
 
        self.assertTrue(
2342
 
            osutils.find_executable_on_path('THIS SHOULD NOT EXIST') is None)
2343
 
 
2344
 
 
2345
 
class TestEnvironmentErrors(tests.TestCase):
2346
 
    """Test handling of environmental errors"""
2347
 
 
2348
 
    def test_is_oserror(self):
2349
 
        self.assertTrue(osutils.is_environment_error(
2350
 
            OSError(errno.EINVAL, "Invalid parameter")))
2351
 
 
2352
 
    def test_is_ioerror(self):
2353
 
        self.assertTrue(osutils.is_environment_error(
2354
 
            IOError(errno.EINVAL, "Invalid parameter")))
2355
 
 
2356
 
    def test_is_socket_error(self):
2357
 
        self.assertTrue(osutils.is_environment_error(
2358
 
            socket.error(errno.EINVAL, "Invalid parameter")))
2359
 
 
2360
 
    def test_is_select_error(self):
2361
 
        self.assertTrue(osutils.is_environment_error(
2362
 
            select.error(errno.EINVAL, "Invalid parameter")))
2363
 
 
2364
 
    def test_is_pywintypes_error(self):
2365
 
        self.requireFeature(features.pywintypes)
2366
 
        import pywintypes
2367
 
        self.assertTrue(osutils.is_environment_error(
2368
 
            pywintypes.error(errno.EINVAL, "Invalid parameter", "Caller")))