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