~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: John Arbash Meinel
  • Date: 2007-03-05 20:51:42 UTC
  • mfrom: (2298.7.1 87765)
  • mto: This revision was merged to the branch mainline in revision 2315.
  • Revision ID: john@arbash-meinel.com-20070305205142-3xhccyveuakkrj87
(Vincent Ladeuil) invalid proxy vars should not cause a traceback (bug #87765)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
"""Tests for the osutils wrapper.
18
 
"""
 
17
"""Tests for the osutils wrapper."""
19
18
 
 
19
import errno
20
20
import os
 
21
import socket
 
22
import stat
21
23
import sys
22
24
 
23
25
import bzrlib
24
 
from bzrlib.errors import BzrBadParameterNotUnicode
25
 
import bzrlib.osutils as osutils
26
 
from bzrlib.tests import TestCaseInTempDir, TestCase
 
26
from bzrlib import (
 
27
    errors,
 
28
    osutils,
 
29
    win32utils,
 
30
    )
 
31
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
32
from bzrlib.tests import (
 
33
        StringIOWrapper,
 
34
        TestCase, 
 
35
        TestCaseInTempDir, 
 
36
        TestSkipped,
 
37
        )
27
38
 
28
39
 
29
40
class TestOSUtils(TestCaseInTempDir):
30
41
 
 
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
 
31
56
    def test_fancy_rename(self):
32
57
        # This should work everywhere
33
58
        def rename(a, b):
59
84
 
60
85
        self.check_file_contents('a', 'something in a\n')
61
86
 
62
 
 
63
87
    # TODO: test fancy_rename using a MemoryTransport
64
88
 
 
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
 
 
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'))
 
107
 
 
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
 
 
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'))
 
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')
 
159
 
 
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
 
 
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
 
 
184
    def test_format_delta(self):
 
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)
 
208
 
 
209
        # We handle when time steps the wrong direction because computers
 
210
        # don't have synchronized clocks.
 
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)
 
214
 
 
215
    def test_dereference_path(self):
 
216
        if not osutils.has_symlinks():
 
217
            raise TestSkipped('Symlinks are not supported on this platform')
 
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')
 
229
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
 
230
 
 
231
        # Dereferences parent symlinks
 
232
        os.mkdir('bar/baz')
 
233
        baz_path = osutils.pathjoin(bar_path, 'baz')
 
234
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
 
235
 
 
236
        # Dereferences parent symlinks that are the first path element
 
237
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
 
238
 
 
239
        # Dereferences parent symlinks in absolute paths
 
240
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
 
241
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
 
242
 
65
243
 
66
244
class TestSafeUnicode(TestCase):
67
245
 
81
259
        self.assertRaises(BzrBadParameterNotUnicode,
82
260
                          osutils.safe_unicode,
83
261
                          '\xbb\xbb')
 
262
 
 
263
 
 
264
class TestSafeUtf8(TestCase):
 
265
 
 
266
    def test_from_ascii_string(self):
 
267
        f = 'foobar'
 
268
        self.assertEqual('foobar', osutils.safe_utf8(f))
 
269
 
 
270
    def test_from_unicode_string_ascii_contents(self):
 
271
        self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
 
272
 
 
273
    def test_from_unicode_string_unicode_contents(self):
 
274
        self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
 
275
 
 
276
    def test_from_utf8_string(self):
 
277
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
 
278
 
 
279
    def test_bad_utf8_string(self):
 
280
        self.assertRaises(BzrBadParameterNotUnicode,
 
281
                          osutils.safe_utf8, '\xbb\xbb')
 
282
 
 
283
 
 
284
class TestSafeRevisionId(TestCase):
 
285
 
 
286
    def test_from_ascii_string(self):
 
287
        f = 'foobar'
 
288
        self.assertEqual('foobar', osutils.safe_revision_id(f))
 
289
        self.assertIs(osutils.safe_utf8(f), f)
 
290
 
 
291
    def test_from_unicode_string_ascii_contents(self):
 
292
        self.assertEqual('bargam', osutils.safe_revision_id(u'bargam'))
 
293
 
 
294
    def test_from_unicode_string_unicode_contents(self):
 
295
        self.assertEqual('bargam\xc2\xae',
 
296
                         osutils.safe_revision_id(u'bargam\xae'))
 
297
 
 
298
    def test_from_utf8_string(self):
 
299
        self.assertEqual('foo\xc2\xae',
 
300
                         osutils.safe_revision_id('foo\xc2\xae'))
 
301
 
 
302
    def test_bad_utf8_string(self):
 
303
        # This check may eventually go away
 
304
        self.assertRaises(BzrBadParameterNotUnicode,
 
305
                          osutils.safe_revision_id, '\xbb\xbb')
 
306
 
 
307
    def test_none(self):
 
308
        """Currently, None is a valid revision_id"""
 
309
        self.assertEqual(None, osutils.safe_revision_id(None))
 
310
 
 
311
 
 
312
class TestSafeFileId(TestCase):
 
313
 
 
314
    def test_from_ascii_string(self):
 
315
        f = 'foobar'
 
316
        self.assertEqual('foobar', osutils.safe_file_id(f))
 
317
 
 
318
    def test_from_unicode_string_ascii_contents(self):
 
319
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam'))
 
320
 
 
321
    def test_from_unicode_string_unicode_contents(self):
 
322
        self.assertEqual('bargam\xc2\xae',
 
323
                         osutils.safe_file_id(u'bargam\xae'))
 
324
 
 
325
    def test_from_utf8_string(self):
 
326
        self.assertEqual('foo\xc2\xae',
 
327
                         osutils.safe_file_id('foo\xc2\xae'))
 
328
 
 
329
    def test_bad_utf8_string(self):
 
330
        # This check may eventually go away
 
331
        self.assertRaises(BzrBadParameterNotUnicode,
 
332
                          osutils.safe_file_id, '\xbb\xbb')
 
333
 
 
334
    def test_none(self):
 
335
        """Currently, None is a valid revision_id"""
 
336
        self.assertEqual(None, osutils.safe_file_id(None))
 
337
 
 
338
 
 
339
class TestWin32Funcs(TestCase):
 
340
    """Test that the _win32 versions of os utilities return appropriate paths."""
 
341
 
 
342
    def test_abspath(self):
 
343
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
 
344
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
 
345
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
 
346
        self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
 
347
 
 
348
    def test_realpath(self):
 
349
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
 
350
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
 
351
 
 
352
    def test_pathjoin(self):
 
353
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
354
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
355
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
356
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
357
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
358
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
359
 
 
360
    def test_normpath(self):
 
361
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
362
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
 
363
 
 
364
    def test_getcwd(self):
 
365
        cwd = osutils._win32_getcwd()
 
366
        os_cwd = os.getcwdu()
 
367
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
 
368
        # win32 is inconsistent whether it returns lower or upper case
 
369
        # and even if it was consistent the user might type the other
 
370
        # so we force it to uppercase
 
371
        # running python.exe under cmd.exe return capital C:\\
 
372
        # running win32 python inside a cygwin shell returns lowercase
 
373
        self.assertEqual(os_cwd[0].upper(), cwd[0])
 
374
 
 
375
    def test_fixdrive(self):
 
376
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
 
377
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
 
378
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
 
379
 
 
380
    def test_win98_abspath(self):
 
381
        # absolute path
 
382
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
 
383
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
 
384
        # UNC path
 
385
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
 
386
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
 
387
        # relative path
 
388
        cwd = osutils.getcwd().rstrip('/')
 
389
        drive = osutils._nt_splitdrive(cwd)[0]
 
390
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
 
391
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
 
392
        # unicode path
 
393
        u = u'\u1234'
 
394
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
 
395
 
 
396
 
 
397
class TestWin32FuncsDirs(TestCaseInTempDir):
 
398
    """Test win32 functions that create files."""
 
399
    
 
400
    def test_getcwd(self):
 
401
        if win32utils.winver == 'Windows 98':
 
402
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
403
        # Make sure getcwd can handle unicode filenames
 
404
        try:
 
405
            os.mkdir(u'mu-\xb5')
 
406
        except UnicodeError:
 
407
            raise TestSkipped("Unable to create Unicode filename")
 
408
 
 
409
        os.chdir(u'mu-\xb5')
 
410
        # TODO: jam 20060427 This will probably fail on Mac OSX because
 
411
        #       it will change the normalization of B\xe5gfors
 
412
        #       Consider using a different unicode character, or make
 
413
        #       osutils.getcwd() renormalize the path.
 
414
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
 
415
 
 
416
    def test_mkdtemp(self):
 
417
        tmpdir = osutils._win32_mkdtemp(dir='.')
 
418
        self.assertFalse('\\' in tmpdir)
 
419
 
 
420
    def test_rename(self):
 
421
        a = open('a', 'wb')
 
422
        a.write('foo\n')
 
423
        a.close()
 
424
        b = open('b', 'wb')
 
425
        b.write('baz\n')
 
426
        b.close()
 
427
 
 
428
        osutils._win32_rename('b', 'a')
 
429
        self.failUnlessExists('a')
 
430
        self.failIfExists('b')
 
431
        self.assertFileEqual('baz\n', 'a')
 
432
 
 
433
    def test_rename_missing_file(self):
 
434
        a = open('a', 'wb')
 
435
        a.write('foo\n')
 
436
        a.close()
 
437
 
 
438
        try:
 
439
            osutils._win32_rename('b', 'a')
 
440
        except (IOError, OSError), e:
 
441
            self.assertEqual(errno.ENOENT, e.errno)
 
442
        self.assertFileEqual('foo\n', 'a')
 
443
 
 
444
    def test_rename_missing_dir(self):
 
445
        os.mkdir('a')
 
446
        try:
 
447
            osutils._win32_rename('b', 'a')
 
448
        except (IOError, OSError), e:
 
449
            self.assertEqual(errno.ENOENT, e.errno)
 
450
 
 
451
    def test_rename_current_dir(self):
 
452
        os.mkdir('a')
 
453
        os.chdir('a')
 
454
        # You can't rename the working directory
 
455
        # doing rename non-existant . usually
 
456
        # just raises ENOENT, since non-existant
 
457
        # doesn't exist.
 
458
        try:
 
459
            osutils._win32_rename('b', '.')
 
460
        except (IOError, OSError), e:
 
461
            self.assertEqual(errno.ENOENT, e.errno)
 
462
 
 
463
    def test_splitpath(self):
 
464
        def check(expected, path):
 
465
            self.assertEqual(expected, osutils.splitpath(path))
 
466
 
 
467
        check(['a'], 'a')
 
468
        check(['a', 'b'], 'a/b')
 
469
        check(['a', 'b'], 'a/./b')
 
470
        check(['a', '.b'], 'a/.b')
 
471
        check(['a', '.b'], 'a\\.b')
 
472
 
 
473
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
 
474
 
 
475
 
 
476
class TestMacFuncsDirs(TestCaseInTempDir):
 
477
    """Test mac special functions that require directories."""
 
478
 
 
479
    def test_getcwd(self):
 
480
        # On Mac, this will actually create Ba\u030agfors
 
481
        # but chdir will still work, because it accepts both paths
 
482
        try:
 
483
            os.mkdir(u'B\xe5gfors')
 
484
        except UnicodeError:
 
485
            raise TestSkipped("Unable to create Unicode filename")
 
486
 
 
487
        os.chdir(u'B\xe5gfors')
 
488
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
489
 
 
490
    def test_getcwd_nonnorm(self):
 
491
        # Test that _mac_getcwd() will normalize this path
 
492
        try:
 
493
            os.mkdir(u'Ba\u030agfors')
 
494
        except UnicodeError:
 
495
            raise TestSkipped("Unable to create Unicode filename")
 
496
 
 
497
        os.chdir(u'Ba\u030agfors')
 
498
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
499
 
 
500
 
 
501
class TestSplitLines(TestCase):
 
502
 
 
503
    def test_split_unicode(self):
 
504
        self.assertEqual([u'foo\n', u'bar\xae'],
 
505
                         osutils.split_lines(u'foo\nbar\xae'))
 
506
        self.assertEqual([u'foo\n', u'bar\xae\n'],
 
507
                         osutils.split_lines(u'foo\nbar\xae\n'))
 
508
 
 
509
    def test_split_with_carriage_returns(self):
 
510
        self.assertEqual(['foo\rbar\n'],
 
511
                         osutils.split_lines('foo\rbar\n'))
 
512
 
 
513
 
 
514
class TestWalkDirs(TestCaseInTempDir):
 
515
 
 
516
    def test_walkdirs(self):
 
517
        tree = [
 
518
            '.bzr',
 
519
            '0file',
 
520
            '1dir/',
 
521
            '1dir/0file',
 
522
            '1dir/1dir/',
 
523
            '2file'
 
524
            ]
 
525
        self.build_tree(tree)
 
526
        expected_dirblocks = [
 
527
                (('', '.'),
 
528
                 [('0file', '0file', 'file'),
 
529
                  ('1dir', '1dir', 'directory'),
 
530
                  ('2file', '2file', 'file'),
 
531
                 ]
 
532
                ),
 
533
                (('1dir', './1dir'),
 
534
                 [('1dir/0file', '0file', 'file'),
 
535
                  ('1dir/1dir', '1dir', 'directory'),
 
536
                 ]
 
537
                ),
 
538
                (('1dir/1dir', './1dir/1dir'),
 
539
                 [
 
540
                 ]
 
541
                ),
 
542
            ]
 
543
        result = []
 
544
        found_bzrdir = False
 
545
        for dirdetail, dirblock in osutils.walkdirs('.'):
 
546
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
547
                # this tests the filtering of selected paths
 
548
                found_bzrdir = True
 
549
                del dirblock[0]
 
550
            result.append((dirdetail, dirblock))
 
551
 
 
552
        self.assertTrue(found_bzrdir)
 
553
        self.assertEqual(expected_dirblocks,
 
554
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
555
        # you can search a subdir only, with a supplied prefix.
 
556
        result = []
 
557
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
558
            result.append(dirblock)
 
559
        self.assertEqual(expected_dirblocks[1:],
 
560
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
561
 
 
562
    def assertPathCompare(self, path_less, path_greater):
 
563
        """check that path_less and path_greater compare correctly."""
 
564
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
565
            path_less, path_less))
 
566
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
567
            path_greater, path_greater))
 
568
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
 
569
            path_less, path_greater))
 
570
        self.assertEqual(1, osutils.compare_paths_prefix_order(
 
571
            path_greater, path_less))
 
572
 
 
573
    def test_compare_paths_prefix_order(self):
 
574
        # root before all else
 
575
        self.assertPathCompare("/", "/a")
 
576
        # alpha within a dir
 
577
        self.assertPathCompare("/a", "/b")
 
578
        self.assertPathCompare("/b", "/z")
 
579
        # high dirs before lower.
 
580
        self.assertPathCompare("/z", "/a/a")
 
581
        # except if the deeper dir should be output first
 
582
        self.assertPathCompare("/a/b/c", "/d/g")
 
583
        # lexical betwen dirs of the same height
 
584
        self.assertPathCompare("/a/z", "/z/z")
 
585
        self.assertPathCompare("/a/c/z", "/a/d/e")
 
586
 
 
587
        # this should also be consistent for no leading / paths
 
588
        # root before all else
 
589
        self.assertPathCompare("", "a")
 
590
        # alpha within a dir
 
591
        self.assertPathCompare("a", "b")
 
592
        self.assertPathCompare("b", "z")
 
593
        # high dirs before lower.
 
594
        self.assertPathCompare("z", "a/a")
 
595
        # except if the deeper dir should be output first
 
596
        self.assertPathCompare("a/b/c", "d/g")
 
597
        # lexical betwen dirs of the same height
 
598
        self.assertPathCompare("a/z", "z/z")
 
599
        self.assertPathCompare("a/c/z", "a/d/e")
 
600
 
 
601
    def test_path_prefix_sorting(self):
 
602
        """Doing a sort on path prefix should match our sample data."""
 
603
        original_paths = [
 
604
            'a',
 
605
            'a/b',
 
606
            'a/b/c',
 
607
            'b',
 
608
            'b/c',
 
609
            'd',
 
610
            'd/e',
 
611
            'd/e/f',
 
612
            'd/f',
 
613
            'd/g',
 
614
            'g',
 
615
            ]
 
616
 
 
617
        dir_sorted_paths = [
 
618
            'a',
 
619
            'b',
 
620
            'd',
 
621
            'g',
 
622
            'a/b',
 
623
            'a/b/c',
 
624
            'b/c',
 
625
            'd/e',
 
626
            'd/f',
 
627
            'd/g',
 
628
            'd/e/f',
 
629
            ]
 
630
 
 
631
        self.assertEqual(
 
632
            dir_sorted_paths,
 
633
            sorted(original_paths, key=osutils.path_prefix_key))
 
634
        # using the comparison routine shoudl work too:
 
635
        self.assertEqual(
 
636
            dir_sorted_paths,
 
637
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
 
638
 
 
639
 
 
640
class TestCopyTree(TestCaseInTempDir):
 
641
    
 
642
    def test_copy_basic_tree(self):
 
643
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
644
        osutils.copy_tree('source', 'target')
 
645
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
646
        self.assertEqual(['c'], os.listdir('target/b'))
 
647
 
 
648
    def test_copy_tree_target_exists(self):
 
649
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
 
650
                         'target/'])
 
651
        osutils.copy_tree('source', 'target')
 
652
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
653
        self.assertEqual(['c'], os.listdir('target/b'))
 
654
 
 
655
    def test_copy_tree_symlinks(self):
 
656
        if not osutils.has_symlinks():
 
657
            return
 
658
        self.build_tree(['source/'])
 
659
        os.symlink('a/generic/path', 'source/lnk')
 
660
        osutils.copy_tree('source', 'target')
 
661
        self.assertEqual(['lnk'], os.listdir('target'))
 
662
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
 
663
 
 
664
    def test_copy_tree_handlers(self):
 
665
        processed_files = []
 
666
        processed_links = []
 
667
        def file_handler(from_path, to_path):
 
668
            processed_files.append(('f', from_path, to_path))
 
669
        def dir_handler(from_path, to_path):
 
670
            processed_files.append(('d', from_path, to_path))
 
671
        def link_handler(from_path, to_path):
 
672
            processed_links.append((from_path, to_path))
 
673
        handlers = {'file':file_handler,
 
674
                    'directory':dir_handler,
 
675
                    'symlink':link_handler,
 
676
                   }
 
677
 
 
678
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
679
        if osutils.has_symlinks():
 
680
            os.symlink('a/generic/path', 'source/lnk')
 
681
        osutils.copy_tree('source', 'target', handlers=handlers)
 
682
 
 
683
        self.assertEqual([('d', 'source', 'target'),
 
684
                          ('f', 'source/a', 'target/a'),
 
685
                          ('d', 'source/b', 'target/b'),
 
686
                          ('f', 'source/b/c', 'target/b/c'),
 
687
                         ], processed_files)
 
688
        self.failIfExists('target')
 
689
        if osutils.has_symlinks():
 
690
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
 
691
 
 
692
 
 
693
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
694
# [bialix] 2006/12/26
 
695
 
 
696
 
 
697
class TestSetUnsetEnv(TestCase):
 
698
    """Test updating the environment"""
 
699
 
 
700
    def setUp(self):
 
701
        super(TestSetUnsetEnv, self).setUp()
 
702
 
 
703
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
 
704
                         'Environment was not cleaned up properly.'
 
705
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
 
706
        def cleanup():
 
707
            if 'BZR_TEST_ENV_VAR' in os.environ:
 
708
                del os.environ['BZR_TEST_ENV_VAR']
 
709
 
 
710
        self.addCleanup(cleanup)
 
711
 
 
712
    def test_set(self):
 
713
        """Test that we can set an env variable"""
 
714
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
715
        self.assertEqual(None, old)
 
716
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
 
717
 
 
718
    def test_double_set(self):
 
719
        """Test that we get the old value out"""
 
720
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
721
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
 
722
        self.assertEqual('foo', old)
 
723
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
 
724
 
 
725
    def test_unicode(self):
 
726
        """Environment can only contain plain strings
 
727
        
 
728
        So Unicode strings must be encoded.
 
729
        """
 
730
        # Try a few different characters, to see if we can get
 
731
        # one that will be valid in the user_encoding
 
732
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
 
733
        for uni_val in possible_vals:
 
734
            try:
 
735
                env_val = uni_val.encode(bzrlib.user_encoding)
 
736
            except UnicodeEncodeError:
 
737
                # Try a different character
 
738
                pass
 
739
            else:
 
740
                break
 
741
        else:
 
742
            raise TestSkipped('Cannot find a unicode character that works in'
 
743
                              ' encoding %s' % (bzrlib.user_encoding,))
 
744
 
 
745
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
 
746
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
 
747
 
 
748
    def test_unset(self):
 
749
        """Test that passing None will remove the env var"""
 
750
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
751
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
 
752
        self.assertEqual('foo', old)
 
753
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
 
754
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
755
 
 
756
 
 
757
class TestLocalTimeOffset(TestCase):
 
758
 
 
759
    def test_local_time_offset(self):
 
760
        """Test that local_time_offset() returns a sane value."""
 
761
        offset = osutils.local_time_offset()
 
762
        self.assertTrue(isinstance(offset, int))
 
763
        # Test that the offset is no more than a eighteen hours in
 
764
        # either direction.
 
765
        # Time zone handling is system specific, so it is difficult to
 
766
        # do more specific tests, but a value outside of this range is
 
767
        # probably wrong.
 
768
        eighteen_hours = 18 * 3600
 
769
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
770
 
 
771
    def test_local_time_offset_with_timestamp(self):
 
772
        """Test that local_time_offset() works with a timestamp."""
 
773
        offset = osutils.local_time_offset(1000000000.1234567)
 
774
        self.assertTrue(isinstance(offset, int))
 
775
        eighteen_hours = 18 * 3600
 
776
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)