/brz/remove-bazaar

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