/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_osutils.py

  • Committer: Jelmer Vernooij
  • Date: 2020-05-24 00:39:50 UTC
  • mto: This revision was merged to the branch mainline in revision 7504.
  • Revision ID: jelmer@jelmer.uk-20200524003950-bbc545r76vc5yajg
Add github action.

Show diffs side-by-side

added added

removed removed

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