/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1
# Copyright (C) 2005, 2006 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
17
"""Tests for the osutils wrapper."""
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
18
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
19
import errno
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
20
import os
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
21
import socket
22
import stat
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
23
import sys
24
25
import bzrlib
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
26
from bzrlib import (
27
    errors,
28
    osutils,
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
29
    win32utils,
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
30
    )
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
31
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
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.
32
from bzrlib.tests import (
33
        StringIOWrapper,
34
        TestCase, 
35
        TestCaseInTempDir, 
36
        TestSkipped,
37
        )
1532 by Robert Collins
Merge in John Meinels integration branch.
38
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
39
40
class TestOSUtils(TestCaseInTempDir):
41
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
42
    def test_contains_whitespace(self):
43
        self.failUnless(osutils.contains_whitespace(u' '))
44
        self.failUnless(osutils.contains_whitespace(u'hello there'))
45
        self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
46
        self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
47
        self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
48
        self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
49
50
        # \xa0 is "Non-breaking-space" which on some python locales thinks it
51
        # is whitespace, but we do not.
52
        self.failIf(osutils.contains_whitespace(u''))
53
        self.failIf(osutils.contains_whitespace(u'hellothere'))
54
        self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
55
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
56
    def test_fancy_rename(self):
57
        # This should work everywhere
58
        def rename(a, b):
59
            osutils.fancy_rename(a, b,
60
                    rename_func=os.rename,
61
                    unlink_func=os.unlink)
62
63
        open('a', 'wb').write('something in a\n')
64
        rename('a', 'b')
65
        self.failIfExists('a')
66
        self.failUnlessExists('b')
67
        self.check_file_contents('b', 'something in a\n')
68
69
        open('a', 'wb').write('new something in a\n')
70
        rename('b', 'a')
71
72
        self.check_file_contents('a', 'something in a\n')
73
74
    def test_rename(self):
75
        # Rename should be semi-atomic on all platforms
76
        open('a', 'wb').write('something in a\n')
77
        osutils.rename('a', 'b')
78
        self.failIfExists('a')
79
        self.failUnlessExists('b')
80
        self.check_file_contents('b', 'something in a\n')
81
82
        open('a', 'wb').write('new something in a\n')
83
        osutils.rename('b', 'a')
84
85
        self.check_file_contents('a', 'something in a\n')
86
87
    # TODO: test fancy_rename using a MemoryTransport
88
1553.5.5 by Martin Pool
New utility routine rand_chars
89
    def test_01_rand_chars_empty(self):
90
        result = osutils.rand_chars(0)
91
        self.assertEqual(result, '')
92
93
    def test_02_rand_chars_100(self):
94
        result = osutils.rand_chars(100)
95
        self.assertEqual(len(result), 100)
96
        self.assertEqual(type(result), str)
97
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
98
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
99
    def test_is_inside(self):
100
        is_inside = osutils.is_inside
101
        self.assertTrue(is_inside('src', 'src/foo.c'))
102
        self.assertFalse(is_inside('src', 'srccontrol'))
103
        self.assertTrue(is_inside('src', 'src/a/a/a/foo.c'))
104
        self.assertTrue(is_inside('foo.c', 'foo.c'))
105
        self.assertFalse(is_inside('foo.c', ''))
106
        self.assertTrue(is_inside('', 'foo.c'))
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
107
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
108
    def test_rmtree(self):
109
        # Check to remove tree with read-only files/dirs
110
        os.mkdir('dir')
111
        f = file('dir/file', 'w')
112
        f.write('spam')
113
        f.close()
114
        # would like to also try making the directory readonly, but at the
115
        # moment python shutil.rmtree doesn't handle that properly - it would
116
        # need to chmod the directory before removing things inside it - deferred
117
        # for now -- mbp 20060505
118
        # osutils.make_readonly('dir')
119
        osutils.make_readonly('dir/file')
120
121
        osutils.rmtree('dir')
122
123
        self.failIfExists('dir/file')
124
        self.failIfExists('dir')
125
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
126
    def test_file_kind(self):
127
        self.build_tree(['file', 'dir/'])
128
        self.assertEquals('file', osutils.file_kind('file'))
129
        self.assertEquals('directory', osutils.file_kind('dir/'))
130
        if osutils.has_symlinks():
131
            os.symlink('symlink', 'symlink')
132
            self.assertEquals('symlink', osutils.file_kind('symlink'))
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
133
        
134
        # TODO: jam 20060529 Test a block device
135
        try:
136
            os.lstat('/dev/null')
137
        except OSError, e:
138
            if e.errno not in (errno.ENOENT,):
139
                raise
140
        else:
141
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
142
143
        mkfifo = getattr(os, 'mkfifo', None)
144
        if mkfifo:
145
            mkfifo('fifo')
146
            try:
147
                self.assertEquals('fifo', osutils.file_kind('fifo'))
148
            finally:
149
                os.remove('fifo')
150
151
        AF_UNIX = getattr(socket, 'AF_UNIX', None)
152
        if AF_UNIX:
153
            s = socket.socket(AF_UNIX)
154
            s.bind('socket')
155
            try:
156
                self.assertEquals('socket', osutils.file_kind('socket'))
157
            finally:
158
                os.remove('socket')
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
159
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
160
    def test_get_umask(self):
161
        if sys.platform == 'win32':
162
            # umask always returns '0', no way to set it
163
            self.assertEqual(0, osutils.get_umask())
164
            return
165
166
        orig_umask = osutils.get_umask()
167
        try:
168
            os.umask(0222)
169
            self.assertEqual(0222, osutils.get_umask())
170
            os.umask(0022)
171
            self.assertEqual(0022, osutils.get_umask())
172
            os.umask(0002)
173
            self.assertEqual(0002, osutils.get_umask())
174
            os.umask(0027)
175
            self.assertEqual(0027, osutils.get_umask())
176
        finally:
177
            os.umask(orig_umask)
178
1957.1.15 by John Arbash Meinel
Review feedback from Robert
179
    def assertFormatedDelta(self, expected, seconds):
180
        """Assert osutils.format_delta formats as expected"""
181
        actual = osutils.format_delta(seconds)
182
        self.assertEqual(expected, actual)
183
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
184
    def test_format_delta(self):
1957.1.15 by John Arbash Meinel
Review feedback from Robert
185
        self.assertFormatedDelta('0 seconds ago', 0)
186
        self.assertFormatedDelta('1 second ago', 1)
187
        self.assertFormatedDelta('10 seconds ago', 10)
188
        self.assertFormatedDelta('59 seconds ago', 59)
189
        self.assertFormatedDelta('89 seconds ago', 89)
190
        self.assertFormatedDelta('1 minute, 30 seconds ago', 90)
191
        self.assertFormatedDelta('3 minutes, 0 seconds ago', 180)
192
        self.assertFormatedDelta('3 minutes, 1 second ago', 181)
193
        self.assertFormatedDelta('10 minutes, 15 seconds ago', 615)
194
        self.assertFormatedDelta('30 minutes, 59 seconds ago', 1859)
195
        self.assertFormatedDelta('31 minutes, 0 seconds ago', 1860)
196
        self.assertFormatedDelta('60 minutes, 0 seconds ago', 3600)
197
        self.assertFormatedDelta('89 minutes, 59 seconds ago', 5399)
198
        self.assertFormatedDelta('1 hour, 30 minutes ago', 5400)
199
        self.assertFormatedDelta('2 hours, 30 minutes ago', 9017)
200
        self.assertFormatedDelta('10 hours, 0 minutes ago', 36000)
201
        self.assertFormatedDelta('24 hours, 0 minutes ago', 86400)
202
        self.assertFormatedDelta('35 hours, 59 minutes ago', 129599)
203
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129600)
204
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129601)
205
        self.assertFormatedDelta('36 hours, 1 minute ago', 129660)
206
        self.assertFormatedDelta('36 hours, 1 minute ago', 129661)
207
        self.assertFormatedDelta('84 hours, 10 minutes ago', 303002)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
208
209
        # We handle when time steps the wrong direction because computers
210
        # don't have synchronized clocks.
1957.1.15 by John Arbash Meinel
Review feedback from Robert
211
        self.assertFormatedDelta('84 hours, 10 minutes in the future', -303002)
212
        self.assertFormatedDelta('1 second in the future', -1)
213
        self.assertFormatedDelta('2 seconds in the future', -2)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
214
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
215
    def test_dereference_path(self):
2091.3.6 by Aaron Bentley
Add symlink test guards
216
        if not osutils.has_symlinks():
217
            raise TestSkipped('Symlinks are not supported on this platform')
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
218
        cwd = osutils.realpath('.')
219
        os.mkdir('bar')
220
        bar_path = osutils.pathjoin(cwd, 'bar')
221
        # Using './' to avoid bug #1213894 (first path component not
222
        # dereferenced) in Python 2.4.1 and earlier
223
        self.assertEqual(bar_path, osutils.realpath('./bar'))
224
        os.symlink('bar', 'foo')
225
        self.assertEqual(bar_path, osutils.realpath('./foo'))
226
        
227
        # Does not dereference terminal symlinks
228
        foo_path = osutils.pathjoin(cwd, 'foo')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
229
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
230
231
        # Dereferences parent symlinks
232
        os.mkdir('bar/baz')
233
        baz_path = osutils.pathjoin(bar_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
234
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
235
236
        # Dereferences parent symlinks that are the first path element
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
237
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
238
239
        # Dereferences parent symlinks in absolute paths
240
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
241
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
242
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
243
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
244
class TestSafeUnicode(TestCase):
245
246
    def test_from_ascii_string(self):
247
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
248
1534.3.2 by Robert Collins
An extra test for John.
249
    def test_from_unicode_string_ascii_contents(self):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
250
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
251
1534.3.2 by Robert Collins
An extra test for John.
252
    def test_from_unicode_string_unicode_contents(self):
253
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
254
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
255
    def test_from_utf8_string(self):
256
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
257
258
    def test_bad_utf8_string(self):
1185.65.29 by Robert Collins
Implement final review suggestions.
259
        self.assertRaises(BzrBadParameterNotUnicode,
260
                          osutils.safe_unicode,
261
                          '\xbb\xbb')
1666.1.6 by Robert Collins
Make knit the default format.
262
263
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
264
class TestWin32Funcs(TestCase):
265
    """Test that the _win32 versions of os utilities return appropriate paths."""
266
267
    def test_abspath(self):
268
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
269
        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
270
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
271
        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.
272
273
    def test_realpath(self):
274
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
275
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
276
277
    def test_pathjoin(self):
278
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
279
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
280
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
281
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
282
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
283
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
284
285
    def test_normpath(self):
286
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
287
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
288
289
    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
290
        cwd = osutils._win32_getcwd()
291
        os_cwd = os.getcwdu()
292
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
293
        # win32 is inconsistent whether it returns lower or upper case
294
        # and even if it was consistent the user might type the other
295
        # so we force it to uppercase
296
        # running python.exe under cmd.exe return capital C:\\
297
        # running win32 python inside a cygwin shell returns lowercase
298
        self.assertEqual(os_cwd[0].upper(), cwd[0])
299
300
    def test_fixdrive(self):
301
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
302
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
303
        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.
304
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
305
    def test_win98_abspath(self):
306
        # absolute path
307
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
308
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
309
        # UNC path
310
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
311
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
312
        # relative path
313
        cwd = osutils.getcwd().rstrip('/')
314
        drive = osutils._nt_splitdrive(cwd)[0]
315
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
316
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
317
        # unicode path
318
        u = u'\u1234'
319
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
320
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
321
322
class TestWin32FuncsDirs(TestCaseInTempDir):
323
    """Test win32 functions that create files."""
324
    
325
    def test_getcwd(self):
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
326
        if win32utils.winver == 'Windows 98':
327
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
328
        # Make sure getcwd can handle unicode filenames
329
        try:
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
330
            os.mkdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
331
        except UnicodeError:
332
            raise TestSkipped("Unable to create Unicode filename")
333
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
334
        os.chdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
335
        # TODO: jam 20060427 This will probably fail on Mac OSX because
336
        #       it will change the normalization of B\xe5gfors
337
        #       Consider using a different unicode character, or make
338
        #       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.
339
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
340
341
    def test_mkdtemp(self):
342
        tmpdir = osutils._win32_mkdtemp(dir='.')
343
        self.assertFalse('\\' in tmpdir)
344
345
    def test_rename(self):
346
        a = open('a', 'wb')
347
        a.write('foo\n')
348
        a.close()
349
        b = open('b', 'wb')
350
        b.write('baz\n')
351
        b.close()
352
353
        osutils._win32_rename('b', 'a')
354
        self.failUnlessExists('a')
355
        self.failIfExists('b')
356
        self.assertFileEqual('baz\n', 'a')
357
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
358
    def test_rename_missing_file(self):
359
        a = open('a', 'wb')
360
        a.write('foo\n')
361
        a.close()
362
363
        try:
364
            osutils._win32_rename('b', 'a')
365
        except (IOError, OSError), e:
366
            self.assertEqual(errno.ENOENT, e.errno)
367
        self.assertFileEqual('foo\n', 'a')
368
369
    def test_rename_missing_dir(self):
370
        os.mkdir('a')
371
        try:
372
            osutils._win32_rename('b', 'a')
373
        except (IOError, OSError), e:
374
            self.assertEqual(errno.ENOENT, e.errno)
375
376
    def test_rename_current_dir(self):
377
        os.mkdir('a')
378
        os.chdir('a')
379
        # You can't rename the working directory
380
        # doing rename non-existant . usually
381
        # just raises ENOENT, since non-existant
382
        # doesn't exist.
383
        try:
384
            osutils._win32_rename('b', '.')
385
        except (IOError, OSError), e:
386
            self.assertEqual(errno.ENOENT, e.errno)
387
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
388
    def test_splitpath(self):
389
        def check(expected, path):
390
            self.assertEqual(expected, osutils.splitpath(path))
391
392
        check(['a'], 'a')
393
        check(['a', 'b'], 'a/b')
394
        check(['a', 'b'], 'a/./b')
395
        check(['a', '.b'], 'a/.b')
396
        check(['a', '.b'], 'a\\.b')
397
398
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
399
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
400
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
401
class TestMacFuncsDirs(TestCaseInTempDir):
402
    """Test mac special functions that require directories."""
403
404
    def test_getcwd(self):
405
        # On Mac, this will actually create Ba\u030agfors
406
        # but chdir will still work, because it accepts both paths
407
        try:
408
            os.mkdir(u'B\xe5gfors')
409
        except UnicodeError:
410
            raise TestSkipped("Unable to create Unicode filename")
411
412
        os.chdir(u'B\xe5gfors')
413
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
414
415
    def test_getcwd_nonnorm(self):
416
        # Test that _mac_getcwd() will normalize this path
417
        try:
418
            os.mkdir(u'Ba\u030agfors')
419
        except UnicodeError:
420
            raise TestSkipped("Unable to create Unicode filename")
421
422
        os.chdir(u'Ba\u030agfors')
423
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
424
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
425
1666.1.6 by Robert Collins
Make knit the default format.
426
class TestSplitLines(TestCase):
427
428
    def test_split_unicode(self):
429
        self.assertEqual([u'foo\n', u'bar\xae'],
430
                         osutils.split_lines(u'foo\nbar\xae'))
431
        self.assertEqual([u'foo\n', u'bar\xae\n'],
432
                         osutils.split_lines(u'foo\nbar\xae\n'))
433
434
    def test_split_with_carriage_returns(self):
435
        self.assertEqual(['foo\rbar\n'],
436
                         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.
437
438
439
class TestWalkDirs(TestCaseInTempDir):
440
441
    def test_walkdirs(self):
442
        tree = [
443
            '.bzr',
444
            '0file',
445
            '1dir/',
446
            '1dir/0file',
447
            '1dir/1dir/',
448
            '2file'
449
            ]
450
        self.build_tree(tree)
451
        expected_dirblocks = [
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
452
                (('', '.'),
453
                 [('0file', '0file', 'file'),
454
                  ('1dir', '1dir', 'directory'),
455
                  ('2file', '2file', 'file'),
456
                 ]
457
                ),
458
                (('1dir', './1dir'),
459
                 [('1dir/0file', '0file', 'file'),
460
                  ('1dir/1dir', '1dir', 'directory'),
461
                 ]
462
                ),
463
                (('1dir/1dir', './1dir/1dir'),
464
                 [
465
                 ]
466
                ),
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
467
            ]
468
        result = []
469
        found_bzrdir = False
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
470
        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.
471
            if len(dirblock) and dirblock[0][1] == '.bzr':
472
                # this tests the filtering of selected paths
473
                found_bzrdir = True
474
                del dirblock[0]
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
475
            result.append((dirdetail, dirblock))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
476
477
        self.assertTrue(found_bzrdir)
478
        self.assertEqual(expected_dirblocks,
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
479
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
480
        # you can search a subdir only, with a supplied prefix.
481
        result = []
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
482
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
483
            result.append(dirblock)
484
        self.assertEqual(expected_dirblocks[1:],
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
485
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
486
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
487
    def assertPathCompare(self, path_less, path_greater):
488
        """check that path_less and path_greater compare correctly."""
489
        self.assertEqual(0, osutils.compare_paths_prefix_order(
490
            path_less, path_less))
491
        self.assertEqual(0, osutils.compare_paths_prefix_order(
492
            path_greater, path_greater))
493
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
494
            path_less, path_greater))
495
        self.assertEqual(1, osutils.compare_paths_prefix_order(
496
            path_greater, path_less))
497
498
    def test_compare_paths_prefix_order(self):
499
        # root before all else
500
        self.assertPathCompare("/", "/a")
501
        # alpha within a dir
502
        self.assertPathCompare("/a", "/b")
503
        self.assertPathCompare("/b", "/z")
504
        # high dirs before lower.
505
        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.
506
        # except if the deeper dir should be output first
507
        self.assertPathCompare("/a/b/c", "/d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
508
        # lexical betwen dirs of the same height
509
        self.assertPathCompare("/a/z", "/z/z")
510
        self.assertPathCompare("/a/c/z", "/a/d/e")
511
512
        # this should also be consistent for no leading / paths
513
        # root before all else
514
        self.assertPathCompare("", "a")
515
        # alpha within a dir
516
        self.assertPathCompare("a", "b")
517
        self.assertPathCompare("b", "z")
518
        # high dirs before lower.
519
        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.
520
        # except if the deeper dir should be output first
521
        self.assertPathCompare("a/b/c", "d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
522
        # lexical betwen dirs of the same height
523
        self.assertPathCompare("a/z", "z/z")
524
        self.assertPathCompare("a/c/z", "a/d/e")
525
1773.3.3 by Robert Collins
Add new tests John Meinel asked for.
526
    def test_path_prefix_sorting(self):
527
        """Doing a sort on path prefix should match our sample data."""
528
        original_paths = [
529
            'a',
530
            'a/b',
531
            'a/b/c',
532
            'b',
533
            'b/c',
534
            'd',
535
            'd/e',
536
            'd/e/f',
537
            'd/f',
538
            'd/g',
539
            'g',
540
            ]
541
542
        dir_sorted_paths = [
543
            'a',
544
            'b',
545
            'd',
546
            'g',
547
            'a/b',
548
            'a/b/c',
549
            'b/c',
550
            'd/e',
551
            'd/f',
552
            'd/g',
553
            'd/e/f',
554
            ]
555
556
        self.assertEqual(
557
            dir_sorted_paths,
558
            sorted(original_paths, key=osutils.path_prefix_key))
559
        # using the comparison routine shoudl work too:
560
        self.assertEqual(
561
            dir_sorted_paths,
562
            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.
563
564
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
565
class TestCopyTree(TestCaseInTempDir):
566
    
567
    def test_copy_basic_tree(self):
568
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
569
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
570
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
571
        self.assertEqual(['c'], os.listdir('target/b'))
572
573
    def test_copy_tree_target_exists(self):
574
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
575
                         'target/'])
576
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
577
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
578
        self.assertEqual(['c'], os.listdir('target/b'))
579
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
580
    def test_copy_tree_symlinks(self):
581
        if not osutils.has_symlinks():
582
            return
583
        self.build_tree(['source/'])
584
        os.symlink('a/generic/path', 'source/lnk')
585
        osutils.copy_tree('source', 'target')
586
        self.assertEqual(['lnk'], os.listdir('target'))
587
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
588
589
    def test_copy_tree_handlers(self):
590
        processed_files = []
591
        processed_links = []
592
        def file_handler(from_path, to_path):
593
            processed_files.append(('f', from_path, to_path))
594
        def dir_handler(from_path, to_path):
595
            processed_files.append(('d', from_path, to_path))
596
        def link_handler(from_path, to_path):
597
            processed_links.append((from_path, to_path))
598
        handlers = {'file':file_handler,
599
                    'directory':dir_handler,
600
                    'symlink':link_handler,
601
                   }
602
603
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
604
        if osutils.has_symlinks():
605
            os.symlink('a/generic/path', 'source/lnk')
606
        osutils.copy_tree('source', 'target', handlers=handlers)
607
608
        self.assertEqual([('d', 'source', 'target'),
609
                          ('f', 'source/a', 'target/a'),
610
                          ('d', 'source/b', 'target/b'),
611
                          ('f', 'source/b/c', 'target/b/c'),
612
                         ], processed_files)
613
        self.failIfExists('target')
614
        if osutils.has_symlinks():
615
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
616
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
617
2192.1.2 by Alexander Belchenko
Tests for osutils.get_terminal_encoding()
618
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
619
# [bialix] 2006/12/26
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.
620
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
621
622
class TestSetUnsetEnv(TestCase):
623
    """Test updating the environment"""
624
625
    def setUp(self):
626
        super(TestSetUnsetEnv, self).setUp()
627
628
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
629
                         'Environment was not cleaned up properly.'
630
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
631
        def cleanup():
632
            if 'BZR_TEST_ENV_VAR' in os.environ:
633
                del os.environ['BZR_TEST_ENV_VAR']
634
635
        self.addCleanup(cleanup)
636
637
    def test_set(self):
638
        """Test that we can set an env variable"""
639
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
640
        self.assertEqual(None, old)
641
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
642
643
    def test_double_set(self):
644
        """Test that we get the old value out"""
645
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
646
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
647
        self.assertEqual('foo', old)
648
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
649
650
    def test_unicode(self):
651
        """Environment can only contain plain strings
652
        
653
        So Unicode strings must be encoded.
654
        """
655
        # Try a few different characters, to see if we can get
656
        # one that will be valid in the user_encoding
657
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
658
        for uni_val in possible_vals:
659
            try:
660
                env_val = uni_val.encode(bzrlib.user_encoding)
661
            except UnicodeEncodeError:
662
                # Try a different character
663
                pass
664
            else:
665
                break
666
        else:
667
            raise TestSkipped('Cannot find a unicode character that works in'
668
                              ' encoding %s' % (bzrlib.user_encoding,))
669
670
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
671
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
672
673
    def test_unset(self):
674
        """Test that passing None will remove the env var"""
675
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
676
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
677
        self.assertEqual('foo', old)
678
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
679
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
680
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
681
682
class TestLocalTimeOffset(TestCase):
683
684
    def test_local_time_offset(self):
685
        """Test that local_time_offset() returns a sane value."""
686
        offset = osutils.local_time_offset()
687
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
688
        # Test that the offset is no more than a eighteen hours in
689
        # either direction.
690
        # Time zone handling is system specific, so it is difficult to
691
        # do more specific tests, but a value outside of this range is
692
        # probably wrong.
693
        eighteen_hours = 18 * 3600
694
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
695
696
    def test_local_time_offset_with_timestamp(self):
697
        """Test that local_time_offset() works with a timestamp."""
698
        offset = osutils.local_time_offset(1000000000.1234567)
699
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
700
        eighteen_hours = 18 * 3600
701
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)