/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
6437.73.1 by John Arbash Meinel
Fix bug #1047309. Treat a series of no-bytes-sent as a ECONNRESET failure.
821
class TestSendAll(tests.TestCase):
822
6437.74.4 by John Arbash Meinel
Since the code is in osutils, put the tests in there as well.
823
    def test_send_with_disconnected_socket(self):
824
        class DisconnectedSocket(object):
825
            def __init__(self, err):
826
                self.err = err
7143.15.2 by Jelmer Vernooij
Run autopep8.
827
6437.74.4 by John Arbash Meinel
Since the code is in osutils, put the tests in there as well.
828
            def send(self, content):
829
                raise self.err
7143.15.2 by Jelmer Vernooij
Run autopep8.
830
6437.74.4 by John Arbash Meinel
Since the code is in osutils, put the tests in there as well.
831
            def close(self):
832
                pass
833
        # All of these should be treated as ConnectionReset
834
        errs = []
835
        for err_cls in (IOError, socket.error):
836
            for errnum in osutils._end_of_stream_errors:
837
                errs.append(err_cls(errnum))
838
        for err in errs:
839
            sock = DisconnectedSocket(err)
840
            self.assertRaises(errors.ConnectionReset,
7143.15.2 by Jelmer Vernooij
Run autopep8.
841
                              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.
842
6437.73.1 by John Arbash Meinel
Fix bug #1047309. Treat a series of no-bytes-sent as a ECONNRESET failure.
843
    def test_send_with_no_progress(self):
844
        # See https://bugs.launchpad.net/bzr/+bug/1047309
845
        # It seems that paramiko can get into a state where it doesn't error,
846
        # but it returns 0 bytes sent for requests over and over again.
847
        class NoSendingSocket(object):
848
            def __init__(self):
849
                self.call_count = 0
7143.15.2 by Jelmer Vernooij
Run autopep8.
850
6437.73.1 by John Arbash Meinel
Fix bug #1047309. Treat a series of no-bytes-sent as a ECONNRESET failure.
851
            def send(self, bytes):
852
                self.call_count += 1
853
                if self.call_count > 100:
854
                    # Prevent the test suite from hanging
855
                    raise RuntimeError('too many calls')
856
                return 0
857
        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.
858
        self.assertRaises(errors.ConnectionReset,
6632.1.2 by Martin
Fix tests for pump and send_all on Python 3
859
                          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.
860
        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.
861
862
6015.39.1 by Florian Vichot
Add failing test to test normpath behaviour given a path starting with two leading slashes
863
class TestPosixFuncs(tests.TestCase):
864
    """Test that the posix version of normpath returns an appropriate path
865
       when used with 2 leading slashes."""
866
867
    def test_normpath(self):
6015.39.2 by Florian Vichot
Fixed an infinite loop when creating a repo at the root of the filesystem,
868
        self.assertEqual('/etc/shadow', osutils._posix_normpath('/etc/shadow'))
7143.15.2 by Jelmer Vernooij
Run autopep8.
869
        self.assertEqual(
870
            '/etc/shadow', osutils._posix_normpath('//etc/shadow'))
871
        self.assertEqual(
872
            '/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
873
874
4241.14.3 by Vincent Ladeuil
Cleanup imports.
875
class TestWin32Funcs(tests.TestCase):
876
    """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.
877
878
    def test_abspath(self):
6603.1.2 by Vincent Ladeuil
Skip the windows tests when not running on windows.
879
        self.requireFeature(features.win32_feature)
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
880
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
881
        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
882
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
883
        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.
884
885
    def test_realpath(self):
886
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
887
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
888
889
    def test_pathjoin(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
890
        self.assertEqual('path/to/foo',
891
                         osutils._win32_pathjoin('path', 'to', 'foo'))
892
        self.assertEqual('C:/foo',
893
                         osutils._win32_pathjoin('path\\to', 'C:\\foo'))
894
        self.assertEqual('C:/foo',
895
                         osutils._win32_pathjoin('path/to', 'C:/foo'))
896
        self.assertEqual('path/to/foo',
897
                         osutils._win32_pathjoin('path/to/', 'foo'))
6592.1.2 by Vincent Ladeuil
Late bugfix in python 2.7.6, only tests are affected.
898
899
    def test_pathjoin_late_bugfix(self):
7479.2.1 by Jelmer Vernooij
Drop python2 support.
900
        expected = 'C:/foo'
6592.1.2 by Vincent Ladeuil
Late bugfix in python 2.7.6, only tests are affected.
901
        self.assertEqual(expected,
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
902
                         osutils._win32_pathjoin('C:/path/to/', '/foo'))
6592.1.2 by Vincent Ladeuil
Late bugfix in python 2.7.6, only tests are affected.
903
        self.assertEqual(expected,
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
904
                         osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
905
906
    def test_normpath(self):
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
907
        self.assertEqual('path/to/foo',
908
                         osutils._win32_normpath(r'path\\from\..\to\.\foo'))
909
        self.assertEqual('path/to/foo',
910
                         osutils._win32_normpath('path//from/../to/./foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
911
912
    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
913
        cwd = osutils._win32_getcwd()
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
914
        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
915
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
916
        # win32 is inconsistent whether it returns lower or upper case
917
        # and even if it was consistent the user might type the other
918
        # so we force it to uppercase
919
        # running python.exe under cmd.exe return capital C:\\
920
        # running win32 python inside a cygwin shell returns lowercase
921
        self.assertEqual(os_cwd[0].upper(), cwd[0])
922
923
    def test_fixdrive(self):
924
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
925
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
926
        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.
927
928
4241.14.3 by Vincent Ladeuil
Cleanup imports.
929
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
930
    """Test win32 functions that create files."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
931
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
932
    def test_getcwd(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
933
        self.requireFeature(features.UnicodeFilenameFeature)
4241.14.5 by Vincent Ladeuil
Some more cleanup (without typo).
934
        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.
935
        os.chdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
936
        # TODO: jam 20060427 This will probably fail on Mac OSX because
937
        #       it will change the normalization of B\xe5gfors
938
        #       Consider using a different unicode character, or make
939
        #       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.
940
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
941
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
942
    def test_minimum_path_selection(self):
943
        self.assertEqual(set(),
7143.15.2 by Jelmer Vernooij
Run autopep8.
944
                         osutils.minimum_path_selection([]))
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
945
        self.assertEqual({'a'},
7143.15.2 by Jelmer Vernooij
Run autopep8.
946
                         osutils.minimum_path_selection(['a']))
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
947
        self.assertEqual({'a', 'b'},
7143.15.2 by Jelmer Vernooij
Run autopep8.
948
                         osutils.minimum_path_selection(['a', 'b']))
949
        self.assertEqual({'a/', 'b'},
950
                         osutils.minimum_path_selection(['a/', 'b']))
951
        self.assertEqual({'a/', 'b'},
952
                         osutils.minimum_path_selection(['a/c', 'a/', 'b']))
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
953
        self.assertEqual({'a-b', 'a', 'a0b'},
7143.15.2 by Jelmer Vernooij
Run autopep8.
954
                         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
955
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
956
    def test_mkdtemp(self):
957
        tmpdir = osutils._win32_mkdtemp(dir='.')
958
        self.assertFalse('\\' in tmpdir)
959
960
    def test_rename(self):
6973.7.5 by Jelmer Vernooij
s/file/open.
961
        with open('a', 'wb') as a:
962
            a.write(b'foo\n')
963
        with open('b', 'wb') as b:
964
            b.write(b'baz\n')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
965
966
        osutils._win32_rename('b', 'a')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
967
        self.assertPathExists('a')
968
        self.assertPathDoesNotExist('b')
6973.7.5 by Jelmer Vernooij
s/file/open.
969
        self.assertFileEqual(b'baz\n', 'a')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
970
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
971
    def test_rename_missing_file(self):
6973.7.5 by Jelmer Vernooij
s/file/open.
972
        with open('a', 'wb') as a:
973
            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.
974
975
        try:
976
            osutils._win32_rename('b', 'a')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
977
        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.
978
            self.assertEqual(errno.ENOENT, e.errno)
6973.11.10 by Jelmer Vernooij
Fix tests.
979
        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.
980
981
    def test_rename_missing_dir(self):
982
        os.mkdir('a')
983
        try:
984
            osutils._win32_rename('b', 'a')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
985
        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.
986
            self.assertEqual(errno.ENOENT, e.errno)
987
988
    def test_rename_current_dir(self):
989
        os.mkdir('a')
990
        os.chdir('a')
991
        # You can't rename the working directory
992
        # doing rename non-existant . usually
993
        # just raises ENOENT, since non-existant
994
        # doesn't exist.
995
        try:
996
            osutils._win32_rename('b', '.')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
997
        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.
998
            self.assertEqual(errno.ENOENT, e.errno)
999
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1000
    def test_splitpath(self):
1001
        def check(expected, path):
1002
            self.assertEqual(expected, osutils.splitpath(path))
1003
1004
        check(['a'], 'a')
1005
        check(['a', 'b'], 'a/b')
1006
        check(['a', 'b'], 'a/./b')
1007
        check(['a', '.b'], 'a/.b')
7121.2.1 by Jelmer Vernooij
Support adding/removing files with a name that consists of just
1008
        if os.path.sep == '\\':
1009
            check(['a', '.b'], 'a\\.b')
1010
        else:
1011
            check(['a\\.b'], 'a\\.b')
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1012
1013
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
1014
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
1015
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
1016
class TestParentDirectories(tests.TestCaseInTempDir):
1017
    """Test osutils.parent_directories()"""
1018
1019
    def test_parent_directories(self):
1020
        self.assertEqual([], osutils.parent_directories('a'))
1021
        self.assertEqual(['a'], osutils.parent_directories('a/b'))
1022
        self.assertEqual(['a/b', 'a'], osutils.parent_directories('a/b/c'))
1023
1024
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1025
class TestMacFuncsDirs(tests.TestCaseInTempDir):
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
1026
    """Test mac special functions that require directories."""
1027
1028
    def test_getcwd(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1029
        self.requireFeature(features.UnicodeFilenameFeature)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1030
        os.mkdir(u'B\xe5gfors')
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
1031
        os.chdir(u'B\xe5gfors')
1032
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1033
1034
    def test_getcwd_nonnorm(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1035
        self.requireFeature(features.UnicodeFilenameFeature)
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
1036
        # Test that _mac_getcwd() will normalize this path
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1037
        os.mkdir(u'Ba\u030agfors')
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
1038
        os.chdir(u'Ba\u030agfors')
1039
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
1040
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1041
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1042
class TestChunksToLines(tests.TestCase):
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
1043
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
1044
    def test_smoketest(self):
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1045
        self.assertEqual([b'foo\n', b'bar\n', b'baz\n'],
1046
                         osutils.chunks_to_lines([b'foo\nbar', b'\nbaz\n']))
1047
        self.assertEqual([b'foo\n', b'bar\n', b'baz\n'],
1048
                         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.
1049
3734.2.21 by Vincent Ladeuil
Give test a better name.
1050
    def test_osutils_binding(self):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1051
        from . import test__chunks_to_lines
4913.2.26 by John Arbash Meinel
A bunch of osutils tests depended on features being available.
1052
        if test__chunks_to_lines.compiled_chunkstolines_feature.available():
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1053
            from .._chunks_to_lines_pyx import chunks_to_lines
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
1054
        else:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1055
            from .._chunks_to_lines_py import chunks_to_lines
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
1056
        self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
3890.2.5 by John Arbash Meinel
More tests for edge cases.
1057
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
1058
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1059
class TestSplitLines(tests.TestCase):
1666.1.6 by Robert Collins
Make knit the default format.
1060
1061
    def test_split_unicode(self):
1062
        self.assertEqual([u'foo\n', u'bar\xae'],
1063
                         osutils.split_lines(u'foo\nbar\xae'))
1064
        self.assertEqual([u'foo\n', u'bar\xae\n'],
1065
                         osutils.split_lines(u'foo\nbar\xae\n'))
1066
1067
    def test_split_with_carriage_returns(self):
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1068
        self.assertEqual([b'foo\rbar\n'],
1069
                         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.
1070
1071
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1072
class TestWalkDirs(tests.TestCaseInTempDir):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1073
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1074
    def assertExpectedBlocks(self, expected, result):
1075
        self.assertEqual(expected,
1076
                         [(dirinfo, [line[0:3] for line in block])
1077
                          for dirinfo, block in result])
1078
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1079
    def test_walkdirs(self):
1080
        tree = [
1081
            '.bzr',
1082
            '0file',
1083
            '1dir/',
1084
            '1dir/0file',
1085
            '1dir/1dir/',
1086
            '2file'
1087
            ]
1088
        self.build_tree(tree)
1089
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1090
            (('', '.'),
1091
             [('0file', '0file', 'file'),
1092
              ('1dir', '1dir', 'directory'),
1093
              ('2file', '2file', 'file'),
1094
              ]
1095
             ),
1096
            (('1dir', './1dir'),
1097
             [('1dir/0file', '0file', 'file'),
1098
              ('1dir/1dir', '1dir', 'directory'),
1099
              ]
1100
             ),
1101
            (('1dir/1dir', './1dir/1dir'),
1102
             [
1103
                ]
1104
             ),
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1105
            ]
1106
        result = []
1107
        found_bzrdir = False
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1108
        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.
1109
            if len(dirblock) and dirblock[0][1] == '.bzr':
1110
                # this tests the filtering of selected paths
1111
                found_bzrdir = True
1112
                del dirblock[0]
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1113
            result.append((dirdetail, dirblock))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1114
1115
        self.assertTrue(found_bzrdir)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1116
        self.assertExpectedBlocks(expected_dirblocks, result)
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1117
        # you can search a subdir only, with a supplied prefix.
1118
        result = []
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1119
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1120
            result.append(dirblock)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1121
        self.assertExpectedBlocks(expected_dirblocks[1:], result)
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1122
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1123
    def test_walkdirs_os_error(self):
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
1124
        # <https://bugs.launchpad.net/bzr/+bug/338653>
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1125
        # Pyrex readdir didn't raise useful messages if it had an error
1126
        # reading the directory
1127
        if sys.platform == 'win32':
1128
            raise tests.TestNotApplicable(
1129
                "readdir IOError not tested on win32")
4797.70.1 by Vincent Ladeuil
Skip chmodbits dependent tests when running as root
1130
        self.requireFeature(features.not_running_as_root)
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1131
        os.mkdir("test-unreadable")
1132
        os.chmod("test-unreadable", 0000)
1133
        # must chmod it back so that it can be removed
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
1134
        self.addCleanup(os.chmod, "test-unreadable", 0o700)
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1135
        # The error is not raised until the generator is actually evaluated.
1136
        # (It would be ok if it happened earlier but at the moment it
1137
        # doesn't.)
4133.1.1 by Vincent Ladeuil
Fix bzrlib.tests.test_osutils.TestWalkDirs.test_walkdirs_os_error
1138
        e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
7067.16.4 by Jelmer Vernooij
Fix noncython case.
1139
        self.assertEqual('./test-unreadable', osutils.safe_unicode(e.filename))
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1140
        self.assertEqual(errno.EACCES, e.errno)
4133.1.2 by Vincent Ladeuil
Fixed as per Martin's remark about the intent of the test :-}
1141
        # Ensure the message contains the file name
6798.1.1 by Jelmer Vernooij
Properly escape backslashes.
1142
        self.assertContainsRe(str(e), "\\./test-unreadable")
4095.1.3 by Martin Pool
Add test for failures inside pyrex readdir
1143
5279.2.5 by Eric Moritz
added a test to make sure that BadFilenameEncoding is thrown
1144
    def test_walkdirs_encoding_error(self):
1145
        # <https://bugs.launchpad.net/bzr/+bug/488519>
1146
        # walkdirs didn't raise a useful message when the filenames
5279.2.8 by Eric Moritz
1. used os.rename instead of shutil.move
1147
        # are not using the filesystem's encoding
1148
5279.2.11 by Eric Moritz
Utilized the ByteStringNamedFilesystem per Martin Pool's request
1149
        # require a bytestring based filesystem
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1150
        self.requireFeature(features.ByteStringNamedFilesystem)
5279.2.8 by Eric Moritz
1. used os.rename instead of shutil.move
1151
5279.2.5 by Eric Moritz
added a test to make sure that BadFilenameEncoding is thrown
1152
        tree = [
1153
            '.bzr',
1154
            '0file',
1155
            '1dir/',
1156
            '1dir/0file',
1157
            '1dir/1dir/',
1158
            '1file'
1159
            ]
1160
1161
        self.build_tree(tree)
1162
1163
        # rename the 1file to a latin-1 filename
7065.3.6 by Jelmer Vernooij
Fix some more tests.
1164
        os.rename(b"./1file", b"\xe8file")
1165
        if b"\xe8file" not in os.listdir("."):
6622.4.1 by Martin
Use skipTest rather than deprecated skip method
1166
            self.skipTest("Lack filesystem that preserves arbitrary bytes")
5279.2.5 by Eric Moritz
added a test to make sure that BadFilenameEncoding is thrown
1167
1168
        self._save_platform_info()
1169
        osutils._fs_enc = 'UTF-8'
1170
1171
        # this should raise on error
1172
        def attempt():
7065.3.6 by Jelmer Vernooij
Fix some more tests.
1173
            for dirdetail, dirblock in osutils.walkdirs(b'.'):
5279.2.5 by Eric Moritz
added a test to make sure that BadFilenameEncoding is thrown
1174
                pass
1175
1176
        self.assertRaises(errors.BadFilenameEncoding, attempt)
1177
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
1178
    def test__walkdirs_utf8(self):
1179
        tree = [
1180
            '.bzr',
1181
            '0file',
1182
            '1dir/',
1183
            '1dir/0file',
1184
            '1dir/1dir/',
1185
            '2file'
1186
            ]
1187
        self.build_tree(tree)
1188
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1189
            (('', '.'),
1190
             [('0file', '0file', 'file'),
1191
              ('1dir', '1dir', 'directory'),
1192
              ('2file', '2file', 'file'),
1193
              ]
1194
             ),
1195
            (('1dir', './1dir'),
1196
             [('1dir/0file', '0file', 'file'),
1197
              ('1dir/1dir', '1dir', 'directory'),
1198
              ]
1199
             ),
1200
            (('1dir/1dir', './1dir/1dir'),
1201
             [
1202
                ]
1203
             ),
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
1204
            ]
1205
        result = []
1206
        found_bzrdir = False
7065.3.6 by Jelmer Vernooij
Fix some more tests.
1207
        for dirdetail, dirblock in osutils._walkdirs_utf8(b'.'):
1208
            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
1209
                # this tests the filtering of selected paths
1210
                found_bzrdir = True
1211
                del dirblock[0]
7143.15.2 by Jelmer Vernooij
Run autopep8.
1212
            dirdetail = (dirdetail[0].decode('utf-8'),
1213
                         osutils.safe_unicode(dirdetail[1]))
7065.3.6 by Jelmer Vernooij
Fix some more tests.
1214
            dirblock = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1215
                (entry[0].decode('utf-8'), entry[1].decode('utf-8'), entry[2])
1216
                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
1217
            result.append((dirdetail, dirblock))
1218
1219
        self.assertTrue(found_bzrdir)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1220
        self.assertExpectedBlocks(expected_dirblocks, result)
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
        # you can search a subdir only, with a supplied prefix.
1223
        result = []
1224
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1225
            result.append(dirblock)
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1226
        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
1227
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1228
    def _filter_out_stat(self, result):
1229
        """Filter out the stat value from the walkdirs result"""
1230
        for dirdetail, dirblock in result:
1231
            new_dirblock = []
1232
            for info in dirblock:
1233
                # Ignore info[3] which is the stat
1234
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1235
            dirblock[:] = new_dirblock
1236
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1237
    def _save_platform_info(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1238
        self.overrideAttr(osutils, '_fs_enc')
1239
        self.overrideAttr(osutils, '_selected_dir_reader')
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1240
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1241
    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'
1242
        """Assert the right implementation for _walkdirs_utf8 is chosen."""
1243
        # Force it to redetect
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1244
        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'
1245
        # Nothing to list, but should still trigger the selection logic
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1246
        self.assertEqual([((b'', top), [])], list(osutils._walkdirs_utf8('.')))
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1247
        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'
1248
1249
    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)
1250
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1251
        self._save_platform_info()
6352.3.9 by Martin Packman
Fix TestWalkDirs tests now value of _fs_enc is stricter
1252
        osutils._fs_enc = 'utf-8'
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1253
        self.assertDirReaderIs(UTF8DirReaderFeature.module.UTF8DirReader, b".")
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1254
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'
1255
    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)
1256
        self.requireFeature(UTF8DirReaderFeature)
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1257
        self._save_platform_info()
6352.3.9 by Martin Packman
Fix TestWalkDirs tests now value of _fs_enc is stricter
1258
        osutils._fs_enc = 'ascii'
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1259
        self.assertDirReaderIs(
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1260
            UTF8DirReaderFeature.module.UTF8DirReader, b".")
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1261
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'
1262
    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,
1263
        self._save_platform_info()
6352.3.9 by Martin Packman
Fix TestWalkDirs tests now value of _fs_enc is stricter
1264
        osutils._fs_enc = 'iso-8859-1'
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1265
        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'
1266
1267
    def test_force_walkdirs_utf8_nt(self):
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1268
        # 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.
1269
        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'
1270
        self._save_platform_info()
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1271
        from .._walkdirs_win32 import Win32ReadDir
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1272
        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'
1273
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1274
    def test_unicode_walkdirs(self):
1275
        """Walkdirs should always return unicode paths."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1276
        self.requireFeature(features.UnicodeFilenameFeature)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1277
        name0 = u'0file-\xb6'
1278
        name1 = u'1dir-\u062c\u0648'
1279
        name2 = u'2file-\u0633'
1280
        tree = [
1281
            name0,
1282
            name1 + '/',
1283
            name1 + '/' + name0,
1284
            name1 + '/' + name1 + '/',
1285
            name2,
1286
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1287
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1288
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1289
            ((u'', u'.'),
1290
             [(name0, name0, 'file', './' + name0),
1291
              (name1, name1, 'directory', './' + name1),
1292
              (name2, name2, 'file', './' + name2),
1293
              ]
1294
             ),
1295
            ((name1, './' + name1),
1296
             [(name1 + '/' + name0, name0, 'file', './' + name1
1297
               + '/' + name0),
1298
              (name1 + '/' + name1, name1, 'directory', './' + name1
1299
               + '/' + name1),
1300
              ]
1301
             ),
1302
            ((name1 + '/' + name1, './' + name1 + '/' + name1),
1303
             [
1304
                ]
1305
             ),
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1306
            ]
1307
        result = list(osutils.walkdirs('.'))
1308
        self._filter_out_stat(result)
1309
        self.assertEqual(expected_dirblocks, result)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1310
        result = list(osutils.walkdirs(u'./' + name1, name1))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1311
        self._filter_out_stat(result)
1312
        self.assertEqual(expected_dirblocks[1:], result)
1313
1314
    def test_unicode__walkdirs_utf8(self):
1315
        """Walkdirs_utf8 should always return utf8 paths.
1316
1317
        The abspath portion might be in unicode or utf-8
1318
        """
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1319
        self.requireFeature(features.UnicodeFilenameFeature)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1320
        name0 = u'0file-\xb6'
1321
        name1 = u'1dir-\u062c\u0648'
1322
        name2 = u'2file-\u0633'
1323
        tree = [
1324
            name0,
1325
            name1 + '/',
1326
            name1 + '/' + name0,
1327
            name1 + '/' + name1 + '/',
1328
            name2,
1329
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1330
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1331
        name0 = name0.encode('utf8')
1332
        name1 = name1.encode('utf8')
1333
        name2 = name2.encode('utf8')
1334
1335
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1336
            ((b'', b'.'),
1337
             [(name0, name0, 'file', b'./' + name0),
1338
              (name1, name1, 'directory', b'./' + name1),
1339
              (name2, name2, 'file', b'./' + name2),
1340
              ]
1341
             ),
1342
            ((name1, b'./' + name1),
1343
             [(name1 + b'/' + name0, name0, 'file', b'./' + name1
1344
               + b'/' + name0),
1345
              (name1 + b'/' + name1, name1, 'directory', b'./' + name1
1346
               + b'/' + name1),
1347
              ]
1348
             ),
1349
            ((name1 + b'/' + name1, b'./' + name1 + b'/' + name1),
1350
             [
1351
                ]
1352
             ),
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1353
            ]
1354
        result = []
1355
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1356
        # all abspaths are Unicode, and encode them back into utf8.
1357
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1358
            self.assertIsInstance(dirdetail[0], bytes)
7479.2.1 by Jelmer Vernooij
Drop python2 support.
1359
            if isinstance(dirdetail[1], str):
2324.2.4 by Dmitry Vasiliev
Fixed test_unicode__walkdirs_utf8 test
1360
                dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1361
                dirblock = [list(info) for info in dirblock]
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1362
                for info in dirblock:
7479.2.1 by Jelmer Vernooij
Drop python2 support.
1363
                    self.assertIsInstance(info[4], str)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1364
                    info[4] = info[4].encode('utf8')
1365
            new_dirblock = []
1366
            for info in dirblock:
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1367
                self.assertIsInstance(info[0], bytes)
1368
                self.assertIsInstance(info[1], bytes)
1369
                self.assertIsInstance(info[4], bytes)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1370
                # Remove the stat information
1371
                new_dirblock.append((info[0], info[1], info[2], info[4]))
1372
            result.append((dirdetail, new_dirblock))
1373
        self.assertEqual(expected_dirblocks, result)
1374
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1375
    def test__walkdirs_utf8_with_unicode_fs(self):
1376
        """UnicodeDirReader should be a safe fallback everywhere
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1377
1378
        The abspath portion should be in unicode
1379
        """
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1380
        self.requireFeature(features.UnicodeFilenameFeature)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1381
        # Use the unicode reader. TODO: split into driver-and-driven unit
1382
        # tests.
1383
        self._save_platform_info()
1384
        osutils._selected_dir_reader = osutils.UnicodeDirReader()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1385
        name0u = u'0file-\xb6'
1386
        name1u = u'1dir-\u062c\u0648'
1387
        name2u = u'2file-\u0633'
1388
        tree = [
1389
            name0u,
1390
            name1u + '/',
1391
            name1u + '/' + name0u,
1392
            name1u + '/' + name1u + '/',
1393
            name2u,
1394
            ]
4241.14.4 by Vincent Ladeuil
Clean up test_osutils.py.
1395
        self.build_tree(tree)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1396
        name0 = name0u.encode('utf8')
1397
        name1 = name1u.encode('utf8')
1398
        name2 = name2u.encode('utf8')
1399
1400
        # All of the abspaths should be in unicode, all of the relative paths
1401
        # should be in utf8
1402
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1403
            ((b'', '.'),
1404
             [(name0, name0, 'file', './' + name0u),
1405
              (name1, name1, 'directory', './' + name1u),
1406
              (name2, name2, 'file', './' + name2u),
1407
              ]
1408
             ),
1409
            ((name1, './' + name1u),
1410
             [(name1 + b'/' + name0, name0, 'file', './' + name1u
1411
               + '/' + name0u),
1412
              (name1 + b'/' + name1, name1, 'directory', './' + name1u
1413
               + '/' + name1u),
1414
              ]
1415
             ),
1416
            ((name1 + b'/' + name1, './' + name1u + '/' + name1u),
1417
             [
1418
                ]
1419
             ),
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1420
            ]
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1421
        result = list(osutils._walkdirs_utf8('.'))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1422
        self._filter_out_stat(result)
1423
        self.assertEqual(expected_dirblocks, result)
1424
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1425
    def test__walkdirs_utf8_win32readdir(self):
4913.2.26 by John Arbash Meinel
A bunch of osutils tests depended on features being available.
1426
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1427
        self.requireFeature(features.UnicodeFilenameFeature)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1428
        from .._walkdirs_win32 import Win32ReadDir
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1429
        self._save_platform_info()
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1430
        osutils._selected_dir_reader = Win32ReadDir()
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1431
        name0u = u'0file-\xb6'
1432
        name1u = u'1dir-\u062c\u0648'
1433
        name2u = u'2file-\u0633'
1434
        tree = [
1435
            name0u,
1436
            name1u + '/',
1437
            name1u + '/' + name0u,
1438
            name1u + '/' + name1u + '/',
1439
            name2u,
1440
            ]
1441
        self.build_tree(tree)
1442
        name0 = name0u.encode('utf8')
1443
        name1 = name1u.encode('utf8')
1444
        name2 = name2u.encode('utf8')
1445
1446
        # All of the abspaths should be in unicode, all of the relative paths
1447
        # should be in utf8
1448
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1449
            (('', '.'),
1450
             [(name0, name0, 'file', './' + name0u),
1451
              (name1, name1, 'directory', './' + name1u),
1452
              (name2, name2, 'file', './' + name2u),
1453
              ]
1454
             ),
1455
            ((name1, './' + name1u),
1456
             [(name1 + '/' + name0, name0, 'file', './' + name1u
1457
               + '/' + name0u),
1458
              (name1 + '/' + name1, name1, 'directory', './' + name1u
1459
               + '/' + name1u),
1460
              ]
1461
             ),
1462
            ((name1 + '/' + name1, './' + name1u + '/' + name1u),
1463
             [
1464
                ]
1465
             ),
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1466
            ]
3696.3.4 by John Arbash Meinel
Update the osutils test to find the objects in the right locations.
1467
        result = list(osutils._walkdirs_utf8(u'.'))
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
1468
        self._filter_out_stat(result)
1469
        self.assertEqual(expected_dirblocks, result)
1470
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1471
    def assertStatIsCorrect(self, path, win32stat):
1472
        os_stat = os.stat(path)
1473
        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.
1474
        self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
1475
        self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
1476
        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.
1477
        self.assertEqual(os_stat.st_dev, win32stat.st_dev)
1478
        self.assertEqual(os_stat.st_ino, win32stat.st_ino)
1479
        self.assertEqual(os_stat.st_mode, win32stat.st_mode)
1480
1481
    def test__walkdirs_utf_win32_find_file_stat_file(self):
1482
        """make sure our Stat values are valid"""
4913.2.26 by John Arbash Meinel
A bunch of osutils tests depended on features being available.
1483
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1484
        self.requireFeature(features.UnicodeFilenameFeature)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1485
        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.
1486
        name0u = u'0file-\xb6'
1487
        name0 = name0u.encode('utf8')
1488
        self.build_tree([name0u])
1489
        # I hate to sleep() here, but I'm trying to make the ctime different
1490
        # from the mtime
1491
        time.sleep(2)
6973.7.5 by Jelmer Vernooij
s/file/open.
1492
        with open(name0u, 'ab') as f:
1493
            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.
1494
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1495
        result = Win32ReadDir().read_dir('', u'.')
1496
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1497
        self.assertEqual((name0, name0, 'file'), entry[:3])
1498
        self.assertEqual(u'./' + name0u, entry[4])
1499
        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.
1500
        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.
1501
1502
    def test__walkdirs_utf_win32_find_file_stat_directory(self):
1503
        """make sure our Stat values are valid"""
4913.2.26 by John Arbash Meinel
A bunch of osutils tests depended on features being available.
1504
        self.requireFeature(test__walkdirs_win32.win32_readdir_feature)
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1505
        self.requireFeature(features.UnicodeFilenameFeature)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1506
        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.
1507
        name0u = u'0dir-\u062c\u0648'
1508
        name0 = name0u.encode('utf8')
1509
        self.build_tree([name0u + '/'])
1510
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1511
        result = Win32ReadDir().read_dir('', u'.')
1512
        entry = result[0]
3504.4.2 by John Arbash Meinel
Add a test case that shows the mtime is not being returned correctly.
1513
        self.assertEqual((name0, name0, 'directory'), entry[:3])
1514
        self.assertEqual(u'./' + name0u, entry[4])
1515
        self.assertStatIsCorrect(entry[4], entry[3])
1516
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1517
    def assertPathCompare(self, path_less, path_greater):
1518
        """check that path_less and path_greater compare correctly."""
1519
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1520
            path_less, path_less))
1521
        self.assertEqual(0, osutils.compare_paths_prefix_order(
1522
            path_greater, path_greater))
1523
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
1524
            path_less, path_greater))
1525
        self.assertEqual(1, osutils.compare_paths_prefix_order(
1526
            path_greater, path_less))
1527
1528
    def test_compare_paths_prefix_order(self):
1529
        # root before all else
1530
        self.assertPathCompare("/", "/a")
1531
        # alpha within a dir
1532
        self.assertPathCompare("/a", "/b")
1533
        self.assertPathCompare("/b", "/z")
1534
        # high dirs before lower.
1535
        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.
1536
        # except if the deeper dir should be output first
1537
        self.assertPathCompare("/a/b/c", "/d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1538
        # lexical betwen dirs of the same height
1539
        self.assertPathCompare("/a/z", "/z/z")
1540
        self.assertPathCompare("/a/c/z", "/a/d/e")
1541
1542
        # this should also be consistent for no leading / paths
1543
        # root before all else
1544
        self.assertPathCompare("", "a")
1545
        # alpha within a dir
1546
        self.assertPathCompare("a", "b")
1547
        self.assertPathCompare("b", "z")
1548
        # high dirs before lower.
1549
        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.
1550
        # except if the deeper dir should be output first
1551
        self.assertPathCompare("a/b/c", "d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1552
        # lexical betwen dirs of the same height
1553
        self.assertPathCompare("a/z", "z/z")
1554
        self.assertPathCompare("a/c/z", "a/d/e")
1555
1773.3.3 by Robert Collins
Add new tests John Meinel asked for.
1556
    def test_path_prefix_sorting(self):
1557
        """Doing a sort on path prefix should match our sample data."""
1558
        original_paths = [
1559
            'a',
1560
            'a/b',
1561
            'a/b/c',
1562
            'b',
1563
            'b/c',
1564
            'd',
1565
            'd/e',
1566
            'd/e/f',
1567
            'd/f',
1568
            'd/g',
1569
            'g',
1570
            ]
1571
1572
        dir_sorted_paths = [
1573
            'a',
1574
            'b',
1575
            'd',
1576
            'g',
1577
            'a/b',
1578
            'a/b/c',
1579
            'b/c',
1580
            'd/e',
1581
            'd/f',
1582
            'd/g',
1583
            'd/e/f',
1584
            ]
1585
1586
        self.assertEqual(
1587
            dir_sorted_paths,
1588
            sorted(original_paths, key=osutils.path_prefix_key))
1589
        # using the comparison routine shoudl work too:
1590
        self.assertEqual(
1591
            dir_sorted_paths,
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
1592
            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.
1593
1594
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1595
class TestCopyTree(tests.TestCaseInTempDir):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1596
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1597
    def test_copy_basic_tree(self):
1598
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1599
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1600
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1601
        self.assertEqual(['c'], os.listdir('target/b'))
1602
1603
    def test_copy_tree_target_exists(self):
1604
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
1605
                         'target/'])
1606
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1607
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1608
        self.assertEqual(['c'], os.listdir('target/b'))
1609
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1610
    def test_copy_tree_symlinks(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1611
        self.requireFeature(features.SymlinkFeature)
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1612
        self.build_tree(['source/'])
1613
        os.symlink('a/generic/path', 'source/lnk')
1614
        osutils.copy_tree('source', 'target')
1615
        self.assertEqual(['lnk'], os.listdir('target'))
1616
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
1617
1618
    def test_copy_tree_handlers(self):
1619
        processed_files = []
1620
        processed_links = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
1621
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1622
        def file_handler(from_path, to_path):
1623
            processed_files.append(('f', from_path, to_path))
7143.15.2 by Jelmer Vernooij
Run autopep8.
1624
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1625
        def dir_handler(from_path, to_path):
1626
            processed_files.append(('d', from_path, to_path))
7143.15.2 by Jelmer Vernooij
Run autopep8.
1627
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1628
        def link_handler(from_path, to_path):
1629
            processed_links.append((from_path, to_path))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1630
        handlers = {'file': file_handler,
1631
                    'directory': dir_handler,
1632
                    'symlink': link_handler,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1633
                    }
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1634
1635
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1636
        if osutils.has_symlinks():
1637
            os.symlink('a/generic/path', 'source/lnk')
1638
        osutils.copy_tree('source', 'target', handlers=handlers)
1639
1640
        self.assertEqual([('d', 'source', 'target'),
1641
                          ('f', 'source/a', 'target/a'),
1642
                          ('d', 'source/b', 'target/b'),
1643
                          ('f', 'source/b/c', 'target/b/c'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
1644
                          ], processed_files)
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1645
        self.assertPathDoesNotExist('target')
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1646
        if osutils.has_symlinks():
1647
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1648
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1649
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1650
class TestSetUnsetEnv(tests.TestCase):
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1651
    """Test updating the environment"""
1652
1653
    def setUp(self):
1654
        super(TestSetUnsetEnv, self).setUp()
1655
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1656
        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
1657
                         'Environment was not cleaned up properly.'
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1658
                         ' Variable BRZ_TEST_ENV_VAR should not exist.')
7143.15.2 by Jelmer Vernooij
Run autopep8.
1659
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1660
        def cleanup():
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1661
            if 'BRZ_TEST_ENV_VAR' in os.environ:
1662
                del os.environ['BRZ_TEST_ENV_VAR']
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1663
        self.addCleanup(cleanup)
1664
1665
    def test_set(self):
1666
        """Test that we can set an env variable"""
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1667
        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
1668
        self.assertEqual(None, old)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1669
        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
1670
1671
    def test_double_set(self):
1672
        """Test that we get the old value out"""
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1673
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1674
        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
1675
        self.assertEqual('foo', old)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1676
        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
1677
1678
    def test_unicode(self):
1679
        """Environment can only contain plain strings
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1680
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1681
        So Unicode strings must be encoded.
1682
        """
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1683
        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()
1684
        if uni_val is None:
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1685
            raise tests.TestSkipped(
1686
                'Cannot find a unicode character that works in encoding %s'
1687
                % (osutils.get_user_encoding(),))
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1688
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1689
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', uni_val)
7479.2.1 by Jelmer Vernooij
Drop python2 support.
1690
        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
1691
1692
    def test_unset(self):
1693
        """Test that passing None will remove the env var"""
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1694
        osutils.set_or_unset_env('BRZ_TEST_ENV_VAR', 'foo')
1695
        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
1696
        self.assertEqual('foo', old)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1697
        self.assertEqual(None, os.environ.get('BRZ_TEST_ENV_VAR'))
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1698
        self.assertNotIn('BRZ_TEST_ENV_VAR', os.environ)
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1699
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
1700
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1701
class TestSizeShaFile(tests.TestCaseInTempDir):
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1702
1703
    def test_sha_empty(self):
6855.4.1 by Jelmer Vernooij
Yet more bees.
1704
        self.build_tree_contents([('foo', b'')])
7045.1.1 by Jelmer Vernooij
Fix another 300 tests.
1705
        expected_sha = osutils.sha_string(b'')
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1706
        f = open('foo')
1707
        self.addCleanup(f.close)
1708
        size, sha = osutils.size_sha_file(f)
1709
        self.assertEqual(0, size)
1710
        self.assertEqual(expected_sha, sha)
1711
1712
    def test_sha_mixed_endings(self):
6855.4.1 by Jelmer Vernooij
Yet more bees.
1713
        text = b'test\r\nwith\nall\rpossible line endings\r\n'
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1714
        self.build_tree_contents([('foo', text)])
1715
        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.
1716
        f = open('foo', 'rb')
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
1717
        self.addCleanup(f.close)
1718
        size, sha = osutils.size_sha_file(f)
1719
        self.assertEqual(38, size)
1720
        self.assertEqual(expected_sha, sha)
1721
1722
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1723
class TestShaFileByName(tests.TestCaseInTempDir):
2922.1.2 by John Arbash Meinel
Add tests for sha_file_by_name.
1724
1725
    def test_sha_empty(self):
6855.4.1 by Jelmer Vernooij
Yet more bees.
1726
        self.build_tree_contents([('foo', b'')])
7045.1.1 by Jelmer Vernooij
Fix another 300 tests.
1727
        expected_sha = osutils.sha_string(b'')
2922.1.2 by John Arbash Meinel
Add tests for sha_file_by_name.
1728
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1729
1730
    def test_sha_mixed_endings(self):
6855.4.1 by Jelmer Vernooij
Yet more bees.
1731
        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.
1732
        self.build_tree_contents([('foo', text)])
1733
        expected_sha = osutils.sha_string(text)
1734
        self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
3089.3.9 by Ian Clatworthy
add test for resource loading
1735
1736
4241.14.3 by Vincent Ladeuil
Cleanup imports.
1737
class TestResourceLoading(tests.TestCaseInTempDir):
3089.3.9 by Ian Clatworthy
add test for resource loading
1738
1739
    def test_resource_string(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1740
        # test resource in breezy
1741
        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
1742
        self.assertContainsRe(text, "debug_flags = set()")
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1743
        # test resource under breezy
1744
        text = osutils.resource_string('breezy.ui', 'text.py')
3089.3.9 by Ian Clatworthy
add test for resource loading
1745
        self.assertContainsRe(text, "class TextUIFactory")
1746
        # test unsupported package
1747
        self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1748
                          'yyy.xx')
3089.3.9 by Ian Clatworthy
add test for resource loading
1749
        # test unknown resource
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1750
        self.assertRaises(IOError, osutils.resource_string, 'breezy', 'yyy.xx')
4183.6.4 by Martin Pool
Separate out re_compile_checked
1751
1752
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1753
class TestDirReader(tests.TestCaseInTempDir):
1754
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1755
    scenarios = dir_reader_scenarios()
1756
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1757
    # Set by load_tests
1758
    _dir_reader_class = None
1759
    _native_to_unicode = None
1760
1761
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
1762
        super(TestDirReader, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1763
        self.overrideAttr(osutils,
1764
                          '_selected_dir_reader', self._dir_reader_class())
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1765
1766
    def _get_ascii_tree(self):
1767
        tree = [
1768
            '0file',
1769
            '1dir/',
1770
            '1dir/0file',
1771
            '1dir/1dir/',
1772
            '2file'
1773
            ]
1774
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1775
            ((b'', '.'),
1776
             [(b'0file', b'0file', 'file', './0file'),
1777
              (b'1dir', b'1dir', 'directory', './1dir'),
1778
              (b'2file', b'2file', 'file', './2file'),
1779
              ]
1780
             ),
1781
            ((b'1dir', './1dir'),
1782
             [(b'1dir/0file', b'0file', 'file', './1dir/0file'),
1783
              (b'1dir/1dir', b'1dir', 'directory', './1dir/1dir'),
1784
              ]
1785
             ),
1786
            ((b'1dir/1dir', './1dir/1dir'),
1787
             [
1788
                ]
1789
             ),
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1790
            ]
1791
        return tree, expected_dirblocks
1792
1793
    def test_walk_cur_dir(self):
1794
        tree, expected_dirblocks = self._get_ascii_tree()
1795
        self.build_tree(tree)
1796
        result = list(osutils._walkdirs_utf8('.'))
1797
        # Filter out stat and abspath
1798
        self.assertEqual(expected_dirblocks,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1799
                         self._filter_out(result))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1800
1801
    def test_walk_sub_dir(self):
1802
        tree, expected_dirblocks = self._get_ascii_tree()
1803
        self.build_tree(tree)
1804
        # you can search a subdir only, with a supplied prefix.
7067.16.3 by Jelmer Vernooij
Some more walkdir fixes.
1805
        result = list(osutils._walkdirs_utf8(b'./1dir', b'1dir'))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1806
        # Filter out stat and abspath
1807
        self.assertEqual(expected_dirblocks[1:],
7143.15.2 by Jelmer Vernooij
Run autopep8.
1808
                         self._filter_out(result))
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1809
1810
    def _get_unicode_tree(self):
1811
        name0u = u'0file-\xb6'
1812
        name1u = u'1dir-\u062c\u0648'
1813
        name2u = u'2file-\u0633'
1814
        tree = [
1815
            name0u,
1816
            name1u + '/',
1817
            name1u + '/' + name0u,
1818
            name1u + '/' + name1u + '/',
1819
            name2u,
1820
            ]
1821
        name0 = name0u.encode('UTF-8')
1822
        name1 = name1u.encode('UTF-8')
1823
        name2 = name2u.encode('UTF-8')
1824
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1825
            ((b'', '.'),
1826
             [(name0, name0, 'file', './' + name0u),
1827
              (name1, name1, 'directory', './' + name1u),
1828
              (name2, name2, 'file', './' + name2u),
1829
              ]
1830
             ),
1831
            ((name1, './' + name1u),
1832
             [(name1 + b'/' + name0, name0, 'file', './' + name1u
1833
               + '/' + name0u),
1834
              (name1 + b'/' + name1, name1, 'directory', './' + name1u
1835
               + '/' + name1u),
1836
              ]
1837
             ),
1838
            ((name1 + b'/' + name1, './' + name1u + '/' + name1u),
1839
             [
1840
                ]
1841
             ),
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1842
            ]
1843
        return tree, expected_dirblocks
1844
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1845
    def _filter_out(self, raw_dirblocks):
1846
        """Filter out a walkdirs_utf8 result.
1847
1848
        stat field is removed, all native paths are converted to unicode
1849
        """
1850
        filtered_dirblocks = []
1851
        for dirinfo, block in raw_dirblocks:
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1852
            dirinfo = (dirinfo[0], self._native_to_unicode(dirinfo[1]))
1853
            details = []
1854
            for line in block:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1855
                details.append(
1856
                    line[0:3] + (self._native_to_unicode(line[4]), ))
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1857
            filtered_dirblocks.append((dirinfo, details))
1858
        return filtered_dirblocks
1859
1860
    def test_walk_unicode_tree(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1861
        self.requireFeature(features.UnicodeFilenameFeature)
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1862
        tree, expected_dirblocks = self._get_unicode_tree()
1863
        self.build_tree(tree)
1864
        result = list(osutils._walkdirs_utf8('.'))
1865
        self.assertEqual(expected_dirblocks, self._filter_out(result))
1866
1867
    def test_symlink(self):
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1868
        self.requireFeature(features.SymlinkFeature)
1869
        self.requireFeature(features.UnicodeFilenameFeature)
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1870
        target = u'target\N{Euro Sign}'
1871
        link_name = u'l\N{Euro Sign}nk'
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1872
        os.symlink(target, link_name)
1873
        link_name_utf8 = link_name.encode('UTF-8')
1874
        expected_dirblocks = [
7143.15.2 by Jelmer Vernooij
Run autopep8.
1875
            ((b'', '.'),
1876
             [(link_name_utf8, link_name_utf8,
1877
               'symlink', './' + link_name), ],
1878
             )]
4241.14.7 by Vincent Ladeuil
Add a test for symlinks name handling.
1879
        result = list(osutils._walkdirs_utf8('.'))
1880
        self.assertEqual(expected_dirblocks, self._filter_out(result))
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1881
1882
1883
class TestReadLink(tests.TestCaseInTempDir):
1884
    """Exposes os.readlink() problems and the osutils solution.
1885
1886
    The only guarantee offered by os.readlink(), starting with 2.6, is that a
1887
    unicode string will be returned if a unicode string is passed.
1888
4241.14.25 by Vincent Ladeuil
Fix PQM failures.
1889
    But prior python versions failed to properly encode the passed unicode
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1890
    string.
1891
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
1892
    _test_needs_features = [features.SymlinkFeature,
1893
                            features.UnicodeFilenameFeature]
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1894
1895
    def setUp(self):
1896
        super(tests.TestCaseInTempDir, self).setUp()
1897
        self.link = u'l\N{Euro Sign}ink'
1898
        self.target = u'targe\N{Euro Sign}t'
1899
        os.symlink(self.target, self.link)
1900
1901
    def test_os_readlink_link_encoding(self):
7143.15.2 by Jelmer Vernooij
Run autopep8.
1902
        self.assertEqual(self.target, os.readlink(self.link))
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1903
1904
    def test_os_readlink_link_decoding(self):
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1905
        self.assertEqual(self.target.encode(osutils._fs_enc),
7143.15.2 by Jelmer Vernooij
Run autopep8.
1906
                         os.readlink(self.link.encode(osutils._fs_enc)))
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1907
1908
1909
class TestConcurrency(tests.TestCase):
1910
4766.3.4 by Matt Nordhoff
Change the environment variable to a global option.
1911
    def setUp(self):
1912
        super(TestConcurrency, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1913
        self.overrideAttr(osutils, '_cached_local_concurrency')
4766.3.4 by Matt Nordhoff
Change the environment variable to a global option.
1914
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1915
    def test_local_concurrency(self):
1916
        concurrency = osutils.local_concurrency()
1917
        self.assertIsInstance(concurrency, int)
4574.3.3 by Martin Pool
Add test for failure to load extensions
1918
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1919
    def test_local_concurrency_environment_variable(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1920
        self.overrideEnv('BRZ_CONCURRENCY', '2')
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1921
        self.assertEqual(2, osutils.local_concurrency(use_cache=False))
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1922
        self.overrideEnv('BRZ_CONCURRENCY', '3')
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1923
        self.assertEqual(3, osutils.local_concurrency(use_cache=False))
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1924
        self.overrideEnv('BRZ_CONCURRENCY', 'foo')
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1925
        self.assertEqual(1, osutils.local_concurrency(use_cache=False))
1926
1927
    def test_option_concurrency(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1928
        self.overrideEnv('BRZ_CONCURRENCY', '1')
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1929
        self.run_bzr('rocks --concurrency 42')
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1930
        # Command line overrides environment variable
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1931
        self.assertEqual('42', os.environ['BRZ_CONCURRENCY'])
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1932
        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()
1933
4574.3.3 by Martin Pool
Add test for failure to load extensions
1934
1935
class TestFailedToLoadExtension(tests.TestCase):
1936
1937
    def _try_loading(self):
1938
        try:
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1939
            import breezy._fictional_extension_py  # noqa: F401
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1940
        except ImportError as e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1941
            osutils.failed_to_load_extension(e)
4574.3.3 by Martin Pool
Add test for failure to load extensions
1942
            return True
1943
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1944
    def setUp(self):
1945
        super(TestFailedToLoadExtension, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1946
        self.overrideAttr(osutils, '_extension_load_failures', [])
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1947
4574.3.3 by Martin Pool
Add test for failure to load extensions
1948
    def test_failure_to_load(self):
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1949
        self._try_loading()
1950
        self.assertLength(1, osutils._extension_load_failures)
7479.2.1 by Jelmer Vernooij
Drop python2 support.
1951
        self.assertEqual(
1952
            osutils._extension_load_failures[0],
1953
            "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
1954
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1955
    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
1956
        self.assertTrue(self._try_loading())
7143.15.2 by Jelmer Vernooij
Run autopep8.
1957
        warnings, result = self.callCatchWarnings(
1958
            osutils.report_extension_load_failures)
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1959
        # it used to give a Python warning; it no longer does
1960
        self.assertLength(0, warnings)
1961
1962
    def test_report_extension_load_failures_message(self):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1963
        log = BytesIO()
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1964
        trace.push_log_file(log)
1965
        self.assertTrue(self._try_loading())
1966
        osutils.report_extension_load_failures()
1967
        self.assertContainsRe(
1968
            log.getvalue(),
7045.4.16 by Jelmer Vernooij
Fix some osutils tests.
1969
            br"brz: warning: some compiled extensions could not be loaded; "
1970
            b"see ``brz help missing-extensions``\n"
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1971
            )
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
1972
1973
1974
class TestTerminalWidth(tests.TestCase):
1975
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.
1976
    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.
1977
        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.
1978
        self._orig_terminal_size_state = osutils._terminal_size_state
1979
        self._orig_first_terminal_size = osutils._first_terminal_size
1980
        self.addCleanup(self.restore_osutils_globals)
1981
        osutils._terminal_size_state = 'no_data'
1982
        osutils._first_terminal_size = None
1983
1984
    def restore_osutils_globals(self):
1985
        osutils._terminal_size_state = self._orig_terminal_size_state
1986
        osutils._first_terminal_size = self._orig_first_terminal_size
5279.2.9 by Eric Moritz
Deleted trailing whitespace
1987
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1988
    def replace_stdout(self, new):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1989
        self.overrideAttr(sys, 'stdout', new)
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1990
1991
    def replace__terminal_size(self, new):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1992
        self.overrideAttr(osutils, '_terminal_size', new)
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1993
4747.4.7 by Vincent Ladeuil
Fix broken test (fail on windows).
1994
    def set_fake_tty(self):
1995
1996
        class I_am_a_tty(object):
1997
            def isatty(self):
1998
                return True
1999
2000
        self.replace_stdout(I_am_a_tty())
2001
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2002
    def test_default_values(self):
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2003
        self.assertEqual(80, osutils.default_terminal_width)
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2004
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2005
    def test_defaults_to_BRZ_COLUMNS(self):
2006
        # BRZ_COLUMNS is set by the test framework
2007
        self.assertNotEqual('12', os.environ['BRZ_COLUMNS'])
2008
        self.overrideEnv('BRZ_COLUMNS', '12')
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2009
        self.assertEqual(12, osutils.terminal_width())
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2010
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2011
    def test_BRZ_COLUMNS_0_no_limit(self):
2012
        self.overrideEnv('BRZ_COLUMNS', '0')
5582.7.1 by Neil Martinsen-Burrell
allow BZR_COLUMNS to be 0
2013
        self.assertEqual(None, osutils.terminal_width())
2014
4747.4.3 by Vincent Ladeuil
Re-fix the priority order since there is a known valid case.
2015
    def test_falls_back_to_COLUMNS(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2016
        self.overrideEnv('BRZ_COLUMNS', None)
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2017
        self.assertNotEqual('42', os.environ['COLUMNS'])
4747.4.7 by Vincent Ladeuil
Fix broken test (fail on windows).
2018
        self.set_fake_tty()
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
2019
        self.overrideEnv('COLUMNS', '42')
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2020
        self.assertEqual(42, osutils.terminal_width())
4747.4.3 by Vincent Ladeuil
Re-fix the priority order since there is a known valid case.
2021
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2022
    def test_tty_default_without_columns(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2023
        self.overrideEnv('BRZ_COLUMNS', None)
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
2024
        self.overrideEnv('COLUMNS', None)
4747.3.5 by Vincent Ladeuil
More precise test.
2025
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2026
        def terminal_size(w, h):
2027
            return 42, 42
2028
4747.4.7 by Vincent Ladeuil
Fix broken test (fail on windows).
2029
        self.set_fake_tty()
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2030
        # We need to override the osutils definition as it depends on the
2031
        # running environment that we can't control (PQM running without a
2032
        # controlling terminal is one example).
2033
        self.replace__terminal_size(terminal_size)
2034
        self.assertEqual(42, osutils.terminal_width())
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2035
2036
    def test_non_tty_default_without_columns(self):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2037
        self.overrideEnv('BRZ_COLUMNS', None)
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
2038
        self.overrideEnv('COLUMNS', None)
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2039
        self.replace_stdout(None)
2040
        self.assertEqual(None, osutils.terminal_width())
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2041
4873.2.2 by John Arbash Meinel
Change the TIOCGWINSZ test to use a _ModuleFeature. (fixes bug #492561)
2042
    def test_no_TIOCGWINSZ(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
2043
        self.requireFeature(term_ios_feature)
2044
        termios = term_ios_feature.module
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2045
        # bug 63539 is about a termios without TIOCGWINSZ attribute
2046
        try:
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2047
            termios.TIOCGWINSZ
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
2048
        except AttributeError:
4873.2.2 by John Arbash Meinel
Change the TIOCGWINSZ test to use a _ModuleFeature. (fixes bug #492561)
2049
            # We won't remove TIOCGWINSZ, because it doesn't exist anyway :)
2050
            pass
2051
        else:
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2052
            self.overrideAttr(termios, 'TIOCGWINSZ')
4873.2.2 by John Arbash Meinel
Change the TIOCGWINSZ test to use a _ModuleFeature. (fixes bug #492561)
2053
            del termios.TIOCGWINSZ
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2054
        self.overrideEnv('BRZ_COLUMNS', None)
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
2055
        self.overrideEnv('COLUMNS', None)
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
2056
        # Whatever the result is, if we don't raise an exception, it's ok.
2057
        osutils.terminal_width()
5051.4.3 by Parth Malwankar
added tests for osutils.{parent_dir, mkdir, open}
2058
5609.47.2 by Alexander Belchenko
getuser_unicode: catch "ImportError: No module named pwd" on Windows when bzr is running as a service.
2059
5051.4.3 by Parth Malwankar
added tests for osutils.{parent_dir, mkdir, open}
2060
class TestCreationOps(tests.TestCaseInTempDir):
5051.4.11 by Parth Malwankar
closed Martins review comments.
2061
    _test_needs_features = [features.chown_feature]
5051.4.3 by Parth Malwankar
added tests for osutils.{parent_dir, mkdir, open}
2062
2063
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
2064
        super(TestCreationOps, self).setUp()
5051.4.9 by Parth Malwankar
removed parent_dir.
2065
        self.overrideAttr(os, 'chown', self._dummy_chown)
5051.4.3 by Parth Malwankar
added tests for osutils.{parent_dir, mkdir, open}
2066
2067
        # params set by call to _dummy_chown
2068
        self.path = self.uid = self.gid = None
2069
2070
    def _dummy_chown(self, path, uid, gid):
2071
        self.path, self.uid, self.gid = path, uid, gid
2072
5116.2.6 by Parth Malwankar
renamed copy_ownership to copy_ownership_from_path.
2073
    def test_copy_ownership_from_path(self):
5116.2.11 by Vincent Ladeuil
Fix typos.
2074
        """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]
2075
        ownsrc = '/'
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2076
        open('test_file', 'wt').close()
5116.2.11 by Vincent Ladeuil
Fix typos.
2077
        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]
2078
2079
        s = os.stat(ownsrc)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2080
        self.assertEqual(self.path, 'test_file')
2081
        self.assertEqual(self.uid, s.st_uid)
2082
        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]
2083
2084
    def test_copy_ownership_nonesrc(self):
5116.2.11 by Vincent Ladeuil
Fix typos.
2085
        """copy_ownership_from_path test with src=None."""
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2086
        open('test_file', 'wt').close()
5116.2.3 by Parth Malwankar
updated log file creation to avoid race based on implementation by Martin [gz]
2087
        # should use parent dir for permissions
5116.2.11 by Vincent Ladeuil
Fix typos.
2088
        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]
2089
2090
        s = os.stat('..')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2091
        self.assertEqual(self.path, 'test_file')
2092
        self.assertEqual(self.uid, s.st_uid)
2093
        self.assertEqual(self.gid, s.st_gid)
5187.2.8 by Parth Malwankar
added tests for getuser_unicode
2094
5609.47.2 by Alexander Belchenko
getuser_unicode: catch "ImportError: No module named pwd" on Windows when bzr is running as a service.
2095
6437.26.1 by Martin Packman
Add and test osutils._get_home_dir for unicode access to home location across platforms
2096
class TestGetHomeDir(tests.TestCase):
2097
2098
    def test_is_unicode(self):
2099
        home = osutils._get_home_dir()
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2100
        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
2101
2102
    def test_posix_homeless(self):
2103
        self.overrideEnv('HOME', None)
2104
        home = osutils._get_home_dir()
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2105
        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
2106
2107
    def test_posix_home_ascii(self):
2108
        self.overrideEnv('HOME', '/home/test')
2109
        home = osutils._posix_get_home_dir()
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2110
        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
2111
        self.assertEqual(u'/home/test', home)
2112
2113
    def test_posix_home_unicode(self):
2114
        self.requireFeature(features.ByteStringNamedFilesystem)
2115
        self.overrideEnv('HOME', '/home/\xa7test')
2116
        self.overrideAttr(osutils, "_fs_enc", "iso8859-1")
2117
        self.assertEqual(u'/home/\xa7test', osutils._posix_get_home_dir())
2118
        osutils._fs_enc = "iso8859-5"
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2119
        # In python 3, os.environ returns unicode
2120
        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
2121
2122
5187.2.8 by Parth Malwankar
added tests for getuser_unicode
2123
class TestGetuserUnicode(tests.TestCase):
2124
6421.1.2 by Martin Packman
Fix tests for osutils.getuser_unicode now it uses the existing win32utils function
2125
    def test_is_unicode(self):
2126
        user = osutils.getuser_unicode()
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2127
        self.assertIsInstance(user, str)
6421.1.2 by Martin Packman
Fix tests for osutils.getuser_unicode now it uses the existing win32utils function
2128
6421.1.3 by Martin Packman
Factor out to test helper details on platform username retrieval
2129
    def envvar_to_override(self):
2130
        if sys.platform == "win32":
2131
            # Disable use of platform calls on windows so envvar is used
2132
            self.overrideAttr(win32utils, 'has_ctypes', False)
7143.15.2 by Jelmer Vernooij
Run autopep8.
2133
            return 'USERNAME'  # only variable used on windows
2134
        return 'LOGNAME'  # first variable checked by getpass.getuser()
6421.1.3 by Martin Packman
Factor out to test helper details on platform username retrieval
2135
5187.2.8 by Parth Malwankar
added tests for getuser_unicode
2136
    def test_ascii_user(self):
6421.1.3 by Martin Packman
Factor out to test helper details on platform username retrieval
2137
        self.overrideEnv(self.envvar_to_override(), 'jrandom')
5187.2.8 by Parth Malwankar
added tests for getuser_unicode
2138
        self.assertEqual(u'jrandom', osutils.getuser_unicode())
2139
2140
    def test_unicode_user(self):
2141
        ue = osutils.get_user_encoding()
5050.37.1 by Andrew Bennetts
Some fixes for tests that did not cope with LANG=C.
2142
        uni_val, env_val = tests.probe_unicode_in_user_encoding()
2143
        if uni_val is None:
2144
            raise tests.TestSkipped(
2145
                'Cannot find a unicode character that works in encoding %s'
2146
                % (osutils.get_user_encoding(),))
2147
        uni_username = u'jrandom' + uni_val
2148
        encoded_username = uni_username.encode(ue)
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2149
        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.
2150
        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.
2151
2152
5409.5.3 by Vincent Ladeuil
Implement osutils.available_backup_name.
2153
class TestBackupNames(tests.TestCase):
2154
2155
    def setUp(self):
2156
        super(TestBackupNames, self).setUp()
2157
        self.backups = []
2158
2159
    def backup_exists(self, name):
2160
        return name in self.backups
2161
2162
    def available_backup_name(self, name):
2163
        backup_name = osutils.available_backup_name(name, self.backup_exists)
2164
        self.backups.append(backup_name)
2165
        return backup_name
2166
2167
    def assertBackupName(self, expected, name):
2168
        self.assertEqual(expected, self.available_backup_name(name))
2169
2170
    def test_empty(self):
2171
        self.assertBackupName('file.~1~', 'file')
2172
2173
    def test_existing(self):
2174
        self.available_backup_name('file')
2175
        self.available_backup_name('file')
2176
        self.assertBackupName('file.~3~', 'file')
2177
        # Empty slots are found, this is not a strict requirement and may be
2178
        # revisited if we test against all implementations.
2179
        self.backups.remove('file.~2~')
2180
        self.assertBackupName('file.~2~', 'file')
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2181
2182
5321.1.80 by Gordon Tyler
Changed is_executable_on_path to find_executable_on_path to make it more useful.
2183
class TestFindExecutableInPath(tests.TestCase):
5321.2.1 by Vincent Ladeuil
Fix style issues, including vertical spaces, lines too long and multi lines imports.
2184
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2185
    def test_windows(self):
2186
        if sys.platform != 'win32':
2187
            raise tests.TestSkipped('test requires win32')
7143.15.2 by Jelmer Vernooij
Run autopep8.
2188
        self.assertTrue(osutils.find_executable_on_path(
2189
            '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.
2190
        self.assertTrue(
2191
            osutils.find_executable_on_path('explorer.exe') is not None)
2192
        self.assertTrue(
2193
            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.
2194
        self.assertTrue(
2195
            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.
2196
        self.assertTrue(osutils.find_executable_on_path('file.txt') is None)
7122.7.2 by Jelmer Vernooij
Add tests.
2197
6437.44.1 by Gordon Tyler
Backport of fix for bug 939605 to bzr 2.5 series.
2198
    def test_windows_app_path(self):
2199
        if sys.platform != 'win32':
2200
            raise tests.TestSkipped('test requires win32')
2201
        # Override PATH env var so that exe can only be found on App Path
2202
        self.overrideEnv('PATH', '')
2203
        # Internt Explorer is always registered in the App Path
7143.15.2 by Jelmer Vernooij
Run autopep8.
2204
        self.assertTrue(osutils.find_executable_on_path(
2205
            'iexplore') is not None)
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2206
2207
    def test_other(self):
2208
        if sys.platform == 'win32':
2209
            raise tests.TestSkipped('test requires non-win32')
5321.2.2 by Vincent Ladeuil
Fix failing test.
2210
        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.
2211
        self.assertTrue(
5321.2.2 by Vincent Ladeuil
Fix failing test.
2212
            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
2213
2214
7122.7.2 by Jelmer Vernooij
Add tests.
2215
class SupportsExecutableTests(tests.TestCaseInTempDir):
2216
2217
    def test_returns_bool(self):
2218
        self.assertIsInstance(osutils.supports_executable(self.test_dir), bool)
2219
2220
7122.7.8 by Jelmer Vernooij
Add osutils.supports_symlinks.
2221
class SupportsSymlinksTests(tests.TestCaseInTempDir):
2222
2223
    def test_returns_bool(self):
2224
        self.assertIsInstance(osutils.supports_symlinks(self.test_dir), bool)
2225
2226
7340.2.1 by Jelmer Vernooij
Read filesystem metadata from mtab directly rather than going via psutil.
2227
class MtabReader(tests.TestCaseInTempDir):
2228
2229
    def test_read_mtab(self):
2230
        self.build_tree_contents([('mtab', """\
2231
/dev/mapper/blah--vg-root / ext4 rw,relatime,errors=remount-ro 0 0
2232
/dev/mapper/blah--vg-home /home vfat rw,relatime 0 0
2233
# comment
2234
2235
iminvalid
2236
""")])
2237
        self.assertEqual(
2238
            list(osutils.read_mtab('mtab')),
2239
            [(b'/', 'ext4'),
2240
             (b'/home', 'vfat')])
2241
2242
7122.7.2 by Jelmer Vernooij
Add tests.
2243
class GetFsTypeTests(tests.TestCaseInTempDir):
2244
7340.2.1 by Jelmer Vernooij
Read filesystem metadata from mtab directly rather than going via psutil.
2245
    def test_returns_string_or_none(self):
2246
        ret = osutils.get_fs_type(self.test_dir)
7479.2.1 by Jelmer Vernooij
Drop python2 support.
2247
        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.
2248
2249
    def test_returns_most_specific(self):
2250
        self.overrideAttr(
2251
            osutils, '_FILESYSTEM_FINDER',
2252
            osutils.FilesystemFinder(
7340.2.4 by Jelmer Vernooij
Fix tests.
2253
                [(b'/', 'ext4'), (b'/home', 'vfat'),
2254
                 (b'/home/jelmer', 'ext2')]))
2255
        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.
2256
        self.assertEqual(osutils.get_fs_type('/home/jelmer/blah'), 'ext2')
7340.2.4 by Jelmer Vernooij
Fix tests.
2257
        self.assertEqual(osutils.get_fs_type(b'/home/jelmer'), 'ext2')
2258
        self.assertEqual(osutils.get_fs_type(b'/home/martin'), 'vfat')
2259
        self.assertEqual(osutils.get_fs_type(b'/home'), 'vfat')
2260
        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.
2261
2262
    def test_returns_none(self):
2263
        self.overrideAttr(
2264
            osutils, '_FILESYSTEM_FINDER',
2265
            osutils.FilesystemFinder([]))
2266
        self.assertIs(osutils.get_fs_type('/home/jelmer/blah'), None)
7340.2.4 by Jelmer Vernooij
Fix tests.
2267
        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.
2268
        self.assertIs(osutils.get_fs_type('/home/jelmer'), None)