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