~bzr-pqm/bzr/bzr.dev

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