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