~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Aaron Bentley
  • Date: 2007-03-07 23:15:10 UTC
  • mto: (1551.19.24 Aaron's mergeable stuff)
  • mto: This revision was merged to the branch mainline in revision 2325.
  • Revision ID: abentley@panoramicfeedback.com-20070307231510-jae63zsli83db3eb
Make ChangeReporter private

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):
71
96
        self.assertEqual(type(result), str)
72
97
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
73
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'))
74
107
 
75
108
    def test_rmtree(self):
76
109
        # Check to remove tree with read-only files/dirs
90
123
        self.failIfExists('dir/file')
91
124
        self.failIfExists('dir')
92
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
 
93
243
 
94
244
class TestSafeUnicode(TestCase):
95
245
 
111
261
                          '\xbb\xbb')
112
262
 
113
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
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
 
288
 
 
289
    def test_from_unicode_string_ascii_contents(self):
 
290
        self.assertEqual('bargam',
 
291
                         osutils.safe_revision_id(u'bargam', warn=False))
 
292
 
 
293
    def test_from_unicode_deprecated(self):
 
294
        self.assertEqual('bargam',
 
295
            self.callDeprecated([osutils._revision_id_warning],
 
296
                                osutils.safe_revision_id, u'bargam'))
 
297
 
 
298
    def test_from_unicode_string_unicode_contents(self):
 
299
        self.assertEqual('bargam\xc2\xae',
 
300
                         osutils.safe_revision_id(u'bargam\xae', warn=False))
 
301
 
 
302
    def test_from_utf8_string(self):
 
303
        self.assertEqual('foo\xc2\xae',
 
304
                         osutils.safe_revision_id('foo\xc2\xae'))
 
305
 
 
306
    def test_none(self):
 
307
        """Currently, None is a valid revision_id"""
 
308
        self.assertEqual(None, osutils.safe_revision_id(None))
 
309
 
 
310
 
 
311
class TestSafeFileId(TestCase):
 
312
 
 
313
    def test_from_ascii_string(self):
 
314
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
 
315
 
 
316
    def test_from_unicode_string_ascii_contents(self):
 
317
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
 
318
 
 
319
    def test_from_unicode_deprecated(self):
 
320
        self.assertEqual('bargam',
 
321
            self.callDeprecated([osutils._file_id_warning],
 
322
                                osutils.safe_file_id, u'bargam'))
 
323
 
 
324
    def test_from_unicode_string_unicode_contents(self):
 
325
        self.assertEqual('bargam\xc2\xae',
 
326
                         osutils.safe_file_id(u'bargam\xae', warn=False))
 
327
 
 
328
    def test_from_utf8_string(self):
 
329
        self.assertEqual('foo\xc2\xae',
 
330
                         osutils.safe_file_id('foo\xc2\xae'))
 
331
 
 
332
    def test_none(self):
 
333
        """Currently, None is a valid revision_id"""
 
334
        self.assertEqual(None, osutils.safe_file_id(None))
 
335
 
 
336
 
 
337
class TestWin32Funcs(TestCase):
 
338
    """Test that the _win32 versions of os utilities return appropriate paths."""
 
339
 
 
340
    def test_abspath(self):
 
341
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
 
342
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
 
343
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
 
344
        self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
 
345
 
 
346
    def test_realpath(self):
 
347
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
 
348
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
 
349
 
 
350
    def test_pathjoin(self):
 
351
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
352
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
353
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
354
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
355
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
356
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
357
 
 
358
    def test_normpath(self):
 
359
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
360
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
 
361
 
 
362
    def test_getcwd(self):
 
363
        cwd = osutils._win32_getcwd()
 
364
        os_cwd = os.getcwdu()
 
365
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
 
366
        # win32 is inconsistent whether it returns lower or upper case
 
367
        # and even if it was consistent the user might type the other
 
368
        # so we force it to uppercase
 
369
        # running python.exe under cmd.exe return capital C:\\
 
370
        # running win32 python inside a cygwin shell returns lowercase
 
371
        self.assertEqual(os_cwd[0].upper(), cwd[0])
 
372
 
 
373
    def test_fixdrive(self):
 
374
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
 
375
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
 
376
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
 
377
 
 
378
    def test_win98_abspath(self):
 
379
        # absolute path
 
380
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
 
381
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
 
382
        # UNC path
 
383
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
 
384
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
 
385
        # relative path
 
386
        cwd = osutils.getcwd().rstrip('/')
 
387
        drive = osutils._nt_splitdrive(cwd)[0]
 
388
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
 
389
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
 
390
        # unicode path
 
391
        u = u'\u1234'
 
392
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
 
393
 
 
394
 
 
395
class TestWin32FuncsDirs(TestCaseInTempDir):
 
396
    """Test win32 functions that create files."""
 
397
    
 
398
    def test_getcwd(self):
 
399
        if win32utils.winver == 'Windows 98':
 
400
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
 
401
        # Make sure getcwd can handle unicode filenames
 
402
        try:
 
403
            os.mkdir(u'mu-\xb5')
 
404
        except UnicodeError:
 
405
            raise TestSkipped("Unable to create Unicode filename")
 
406
 
 
407
        os.chdir(u'mu-\xb5')
 
408
        # TODO: jam 20060427 This will probably fail on Mac OSX because
 
409
        #       it will change the normalization of B\xe5gfors
 
410
        #       Consider using a different unicode character, or make
 
411
        #       osutils.getcwd() renormalize the path.
 
412
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
 
413
 
 
414
    def test_mkdtemp(self):
 
415
        tmpdir = osutils._win32_mkdtemp(dir='.')
 
416
        self.assertFalse('\\' in tmpdir)
 
417
 
 
418
    def test_rename(self):
 
419
        a = open('a', 'wb')
 
420
        a.write('foo\n')
 
421
        a.close()
 
422
        b = open('b', 'wb')
 
423
        b.write('baz\n')
 
424
        b.close()
 
425
 
 
426
        osutils._win32_rename('b', 'a')
 
427
        self.failUnlessExists('a')
 
428
        self.failIfExists('b')
 
429
        self.assertFileEqual('baz\n', 'a')
 
430
 
 
431
    def test_rename_missing_file(self):
 
432
        a = open('a', 'wb')
 
433
        a.write('foo\n')
 
434
        a.close()
 
435
 
 
436
        try:
 
437
            osutils._win32_rename('b', 'a')
 
438
        except (IOError, OSError), e:
 
439
            self.assertEqual(errno.ENOENT, e.errno)
 
440
        self.assertFileEqual('foo\n', 'a')
 
441
 
 
442
    def test_rename_missing_dir(self):
 
443
        os.mkdir('a')
 
444
        try:
 
445
            osutils._win32_rename('b', 'a')
 
446
        except (IOError, OSError), e:
 
447
            self.assertEqual(errno.ENOENT, e.errno)
 
448
 
 
449
    def test_rename_current_dir(self):
 
450
        os.mkdir('a')
 
451
        os.chdir('a')
 
452
        # You can't rename the working directory
 
453
        # doing rename non-existant . usually
 
454
        # just raises ENOENT, since non-existant
 
455
        # doesn't exist.
 
456
        try:
 
457
            osutils._win32_rename('b', '.')
 
458
        except (IOError, OSError), e:
 
459
            self.assertEqual(errno.ENOENT, e.errno)
 
460
 
 
461
    def test_splitpath(self):
 
462
        def check(expected, path):
 
463
            self.assertEqual(expected, osutils.splitpath(path))
 
464
 
 
465
        check(['a'], 'a')
 
466
        check(['a', 'b'], 'a/b')
 
467
        check(['a', 'b'], 'a/./b')
 
468
        check(['a', '.b'], 'a/.b')
 
469
        check(['a', '.b'], 'a\\.b')
 
470
 
 
471
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
 
472
 
 
473
 
 
474
class TestMacFuncsDirs(TestCaseInTempDir):
 
475
    """Test mac special functions that require directories."""
 
476
 
 
477
    def test_getcwd(self):
 
478
        # On Mac, this will actually create Ba\u030agfors
 
479
        # but chdir will still work, because it accepts both paths
 
480
        try:
 
481
            os.mkdir(u'B\xe5gfors')
 
482
        except UnicodeError:
 
483
            raise TestSkipped("Unable to create Unicode filename")
 
484
 
 
485
        os.chdir(u'B\xe5gfors')
 
486
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
487
 
 
488
    def test_getcwd_nonnorm(self):
 
489
        # Test that _mac_getcwd() will normalize this path
 
490
        try:
 
491
            os.mkdir(u'Ba\u030agfors')
 
492
        except UnicodeError:
 
493
            raise TestSkipped("Unable to create Unicode filename")
 
494
 
 
495
        os.chdir(u'Ba\u030agfors')
 
496
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
 
497
 
 
498
 
114
499
class TestSplitLines(TestCase):
115
500
 
116
501
    def test_split_unicode(self):
122
507
    def test_split_with_carriage_returns(self):
123
508
        self.assertEqual(['foo\rbar\n'],
124
509
                         osutils.split_lines('foo\rbar\n'))
 
510
 
 
511
 
 
512
class TestWalkDirs(TestCaseInTempDir):
 
513
 
 
514
    def test_walkdirs(self):
 
515
        tree = [
 
516
            '.bzr',
 
517
            '0file',
 
518
            '1dir/',
 
519
            '1dir/0file',
 
520
            '1dir/1dir/',
 
521
            '2file'
 
522
            ]
 
523
        self.build_tree(tree)
 
524
        expected_dirblocks = [
 
525
                (('', '.'),
 
526
                 [('0file', '0file', 'file'),
 
527
                  ('1dir', '1dir', 'directory'),
 
528
                  ('2file', '2file', 'file'),
 
529
                 ]
 
530
                ),
 
531
                (('1dir', './1dir'),
 
532
                 [('1dir/0file', '0file', 'file'),
 
533
                  ('1dir/1dir', '1dir', 'directory'),
 
534
                 ]
 
535
                ),
 
536
                (('1dir/1dir', './1dir/1dir'),
 
537
                 [
 
538
                 ]
 
539
                ),
 
540
            ]
 
541
        result = []
 
542
        found_bzrdir = False
 
543
        for dirdetail, dirblock in osutils.walkdirs('.'):
 
544
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
545
                # this tests the filtering of selected paths
 
546
                found_bzrdir = True
 
547
                del dirblock[0]
 
548
            result.append((dirdetail, dirblock))
 
549
 
 
550
        self.assertTrue(found_bzrdir)
 
551
        self.assertEqual(expected_dirblocks,
 
552
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
553
        # you can search a subdir only, with a supplied prefix.
 
554
        result = []
 
555
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
556
            result.append(dirblock)
 
557
        self.assertEqual(expected_dirblocks[1:],
 
558
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
559
 
 
560
    def test__walkdirs_utf8(self):
 
561
        tree = [
 
562
            '.bzr',
 
563
            '0file',
 
564
            '1dir/',
 
565
            '1dir/0file',
 
566
            '1dir/1dir/',
 
567
            '2file'
 
568
            ]
 
569
        self.build_tree(tree)
 
570
        expected_dirblocks = [
 
571
                (('', '.'),
 
572
                 [('0file', '0file', 'file'),
 
573
                  ('1dir', '1dir', 'directory'),
 
574
                  ('2file', '2file', 'file'),
 
575
                 ]
 
576
                ),
 
577
                (('1dir', './1dir'),
 
578
                 [('1dir/0file', '0file', 'file'),
 
579
                  ('1dir/1dir', '1dir', 'directory'),
 
580
                 ]
 
581
                ),
 
582
                (('1dir/1dir', './1dir/1dir'),
 
583
                 [
 
584
                 ]
 
585
                ),
 
586
            ]
 
587
        result = []
 
588
        found_bzrdir = False
 
589
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
 
590
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
591
                # this tests the filtering of selected paths
 
592
                found_bzrdir = True
 
593
                del dirblock[0]
 
594
            result.append((dirdetail, dirblock))
 
595
 
 
596
        self.assertTrue(found_bzrdir)
 
597
        self.assertEqual(expected_dirblocks,
 
598
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
599
        # you can search a subdir only, with a supplied prefix.
 
600
        result = []
 
601
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
602
            result.append(dirblock)
 
603
        self.assertEqual(expected_dirblocks[1:],
 
604
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
605
 
 
606
    def _filter_out_stat(self, result):
 
607
        """Filter out the stat value from the walkdirs result"""
 
608
        for dirdetail, dirblock in result:
 
609
            new_dirblock = []
 
610
            for info in dirblock:
 
611
                # Ignore info[3] which is the stat
 
612
                new_dirblock.append((info[0], info[1], info[2], info[4]))
 
613
            dirblock[:] = new_dirblock
 
614
 
 
615
    def test_unicode_walkdirs(self):
 
616
        """Walkdirs should always return unicode paths."""
 
617
        name0 = u'0file-\xb6'
 
618
        name1 = u'1dir-\u062c\u0648'
 
619
        name2 = u'2file-\u0633'
 
620
        tree = [
 
621
            name0,
 
622
            name1 + '/',
 
623
            name1 + '/' + name0,
 
624
            name1 + '/' + name1 + '/',
 
625
            name2,
 
626
            ]
 
627
        try:
 
628
            self.build_tree(tree)
 
629
        except UnicodeError:
 
630
            raise TestSkipped('Could not represent Unicode chars'
 
631
                              ' in current encoding.')
 
632
        expected_dirblocks = [
 
633
                ((u'', u'.'),
 
634
                 [(name0, name0, 'file', './' + name0),
 
635
                  (name1, name1, 'directory', './' + name1),
 
636
                  (name2, name2, 'file', './' + name2),
 
637
                 ]
 
638
                ),
 
639
                ((name1, './' + name1),
 
640
                 [(name1 + '/' + name0, name0, 'file', './' + name1
 
641
                                                        + '/' + name0),
 
642
                  (name1 + '/' + name1, name1, 'directory', './' + name1
 
643
                                                            + '/' + name1),
 
644
                 ]
 
645
                ),
 
646
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
 
647
                 [
 
648
                 ]
 
649
                ),
 
650
            ]
 
651
        result = list(osutils.walkdirs('.'))
 
652
        self._filter_out_stat(result)
 
653
        self.assertEqual(expected_dirblocks, result)
 
654
        result = list(osutils.walkdirs(u'./'+name1, name1))
 
655
        self._filter_out_stat(result)
 
656
        self.assertEqual(expected_dirblocks[1:], result)
 
657
 
 
658
    def test_unicode__walkdirs_utf8(self):
 
659
        """Walkdirs_utf8 should always return utf8 paths.
 
660
 
 
661
        The abspath portion might be in unicode or utf-8
 
662
        """
 
663
        name0 = u'0file-\xb6'
 
664
        name1 = u'1dir-\u062c\u0648'
 
665
        name2 = u'2file-\u0633'
 
666
        tree = [
 
667
            name0,
 
668
            name1 + '/',
 
669
            name1 + '/' + name0,
 
670
            name1 + '/' + name1 + '/',
 
671
            name2,
 
672
            ]
 
673
        try:
 
674
            self.build_tree(tree)
 
675
        except UnicodeError:
 
676
            raise TestSkipped('Could not represent Unicode chars'
 
677
                              ' in current encoding.')
 
678
        name0 = name0.encode('utf8')
 
679
        name1 = name1.encode('utf8')
 
680
        name2 = name2.encode('utf8')
 
681
 
 
682
        expected_dirblocks = [
 
683
                (('', '.'),
 
684
                 [(name0, name0, 'file', './' + name0),
 
685
                  (name1, name1, 'directory', './' + name1),
 
686
                  (name2, name2, 'file', './' + name2),
 
687
                 ]
 
688
                ),
 
689
                ((name1, './' + name1),
 
690
                 [(name1 + '/' + name0, name0, 'file', './' + name1
 
691
                                                        + '/' + name0),
 
692
                  (name1 + '/' + name1, name1, 'directory', './' + name1
 
693
                                                            + '/' + name1),
 
694
                 ]
 
695
                ),
 
696
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
 
697
                 [
 
698
                 ]
 
699
                ),
 
700
            ]
 
701
        result = []
 
702
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
 
703
        # all abspaths are Unicode, and encode them back into utf8.
 
704
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
 
705
            self.assertIsInstance(dirdetail[0], str)
 
706
            if isinstance(dirdetail[1], unicode):
 
707
                dirdetail[1] = dirdetail[1].encode('utf8')
 
708
                for info in dirblock:
 
709
                    self.assertIsInstance(info[4], unicode)
 
710
                    info[4] = info[4].encode('utf8')
 
711
            new_dirblock = []
 
712
            for info in dirblock:
 
713
                self.assertIsInstance(info[0], str)
 
714
                self.assertIsInstance(info[1], str)
 
715
                self.assertIsInstance(info[4], str)
 
716
                # Remove the stat information
 
717
                new_dirblock.append((info[0], info[1], info[2], info[4]))
 
718
            result.append((dirdetail, new_dirblock))
 
719
        self.assertEqual(expected_dirblocks, result)
 
720
 
 
721
    def test_unicode__walkdirs_unicode_to_utf8(self):
 
722
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
 
723
 
 
724
        The abspath portion should be in unicode
 
725
        """
 
726
        name0u = u'0file-\xb6'
 
727
        name1u = u'1dir-\u062c\u0648'
 
728
        name2u = u'2file-\u0633'
 
729
        tree = [
 
730
            name0u,
 
731
            name1u + '/',
 
732
            name1u + '/' + name0u,
 
733
            name1u + '/' + name1u + '/',
 
734
            name2u,
 
735
            ]
 
736
        try:
 
737
            self.build_tree(tree)
 
738
        except UnicodeError:
 
739
            raise TestSkipped('Could not represent Unicode chars'
 
740
                              ' in current encoding.')
 
741
        name0 = name0u.encode('utf8')
 
742
        name1 = name1u.encode('utf8')
 
743
        name2 = name2u.encode('utf8')
 
744
 
 
745
        # All of the abspaths should be in unicode, all of the relative paths
 
746
        # should be in utf8
 
747
        expected_dirblocks = [
 
748
                (('', '.'),
 
749
                 [(name0, name0, 'file', './' + name0u),
 
750
                  (name1, name1, 'directory', './' + name1u),
 
751
                  (name2, name2, 'file', './' + name2u),
 
752
                 ]
 
753
                ),
 
754
                ((name1, './' + name1u),
 
755
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
 
756
                                                        + '/' + name0u),
 
757
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
 
758
                                                            + '/' + name1u),
 
759
                 ]
 
760
                ),
 
761
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
 
762
                 [
 
763
                 ]
 
764
                ),
 
765
            ]
 
766
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
 
767
        self._filter_out_stat(result)
 
768
        self.assertEqual(expected_dirblocks, result)
 
769
 
 
770
    def assertPathCompare(self, path_less, path_greater):
 
771
        """check that path_less and path_greater compare correctly."""
 
772
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
773
            path_less, path_less))
 
774
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
775
            path_greater, path_greater))
 
776
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
 
777
            path_less, path_greater))
 
778
        self.assertEqual(1, osutils.compare_paths_prefix_order(
 
779
            path_greater, path_less))
 
780
 
 
781
    def test_compare_paths_prefix_order(self):
 
782
        # root before all else
 
783
        self.assertPathCompare("/", "/a")
 
784
        # alpha within a dir
 
785
        self.assertPathCompare("/a", "/b")
 
786
        self.assertPathCompare("/b", "/z")
 
787
        # high dirs before lower.
 
788
        self.assertPathCompare("/z", "/a/a")
 
789
        # except if the deeper dir should be output first
 
790
        self.assertPathCompare("/a/b/c", "/d/g")
 
791
        # lexical betwen dirs of the same height
 
792
        self.assertPathCompare("/a/z", "/z/z")
 
793
        self.assertPathCompare("/a/c/z", "/a/d/e")
 
794
 
 
795
        # this should also be consistent for no leading / paths
 
796
        # root before all else
 
797
        self.assertPathCompare("", "a")
 
798
        # alpha within a dir
 
799
        self.assertPathCompare("a", "b")
 
800
        self.assertPathCompare("b", "z")
 
801
        # high dirs before lower.
 
802
        self.assertPathCompare("z", "a/a")
 
803
        # except if the deeper dir should be output first
 
804
        self.assertPathCompare("a/b/c", "d/g")
 
805
        # lexical betwen dirs of the same height
 
806
        self.assertPathCompare("a/z", "z/z")
 
807
        self.assertPathCompare("a/c/z", "a/d/e")
 
808
 
 
809
    def test_path_prefix_sorting(self):
 
810
        """Doing a sort on path prefix should match our sample data."""
 
811
        original_paths = [
 
812
            'a',
 
813
            'a/b',
 
814
            'a/b/c',
 
815
            'b',
 
816
            'b/c',
 
817
            'd',
 
818
            'd/e',
 
819
            'd/e/f',
 
820
            'd/f',
 
821
            'd/g',
 
822
            'g',
 
823
            ]
 
824
 
 
825
        dir_sorted_paths = [
 
826
            'a',
 
827
            'b',
 
828
            'd',
 
829
            'g',
 
830
            'a/b',
 
831
            'a/b/c',
 
832
            'b/c',
 
833
            'd/e',
 
834
            'd/f',
 
835
            'd/g',
 
836
            'd/e/f',
 
837
            ]
 
838
 
 
839
        self.assertEqual(
 
840
            dir_sorted_paths,
 
841
            sorted(original_paths, key=osutils.path_prefix_key))
 
842
        # using the comparison routine shoudl work too:
 
843
        self.assertEqual(
 
844
            dir_sorted_paths,
 
845
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
 
846
 
 
847
 
 
848
class TestCopyTree(TestCaseInTempDir):
 
849
    
 
850
    def test_copy_basic_tree(self):
 
851
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
852
        osutils.copy_tree('source', 'target')
 
853
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
854
        self.assertEqual(['c'], os.listdir('target/b'))
 
855
 
 
856
    def test_copy_tree_target_exists(self):
 
857
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
 
858
                         'target/'])
 
859
        osutils.copy_tree('source', 'target')
 
860
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
 
861
        self.assertEqual(['c'], os.listdir('target/b'))
 
862
 
 
863
    def test_copy_tree_symlinks(self):
 
864
        if not osutils.has_symlinks():
 
865
            return
 
866
        self.build_tree(['source/'])
 
867
        os.symlink('a/generic/path', 'source/lnk')
 
868
        osutils.copy_tree('source', 'target')
 
869
        self.assertEqual(['lnk'], os.listdir('target'))
 
870
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
 
871
 
 
872
    def test_copy_tree_handlers(self):
 
873
        processed_files = []
 
874
        processed_links = []
 
875
        def file_handler(from_path, to_path):
 
876
            processed_files.append(('f', from_path, to_path))
 
877
        def dir_handler(from_path, to_path):
 
878
            processed_files.append(('d', from_path, to_path))
 
879
        def link_handler(from_path, to_path):
 
880
            processed_links.append((from_path, to_path))
 
881
        handlers = {'file':file_handler,
 
882
                    'directory':dir_handler,
 
883
                    'symlink':link_handler,
 
884
                   }
 
885
 
 
886
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
 
887
        if osutils.has_symlinks():
 
888
            os.symlink('a/generic/path', 'source/lnk')
 
889
        osutils.copy_tree('source', 'target', handlers=handlers)
 
890
 
 
891
        self.assertEqual([('d', 'source', 'target'),
 
892
                          ('f', 'source/a', 'target/a'),
 
893
                          ('d', 'source/b', 'target/b'),
 
894
                          ('f', 'source/b/c', 'target/b/c'),
 
895
                         ], processed_files)
 
896
        self.failIfExists('target')
 
897
        if osutils.has_symlinks():
 
898
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
 
899
 
 
900
 
 
901
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
 
902
# [bialix] 2006/12/26
 
903
 
 
904
 
 
905
class TestSetUnsetEnv(TestCase):
 
906
    """Test updating the environment"""
 
907
 
 
908
    def setUp(self):
 
909
        super(TestSetUnsetEnv, self).setUp()
 
910
 
 
911
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
 
912
                         'Environment was not cleaned up properly.'
 
913
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
 
914
        def cleanup():
 
915
            if 'BZR_TEST_ENV_VAR' in os.environ:
 
916
                del os.environ['BZR_TEST_ENV_VAR']
 
917
 
 
918
        self.addCleanup(cleanup)
 
919
 
 
920
    def test_set(self):
 
921
        """Test that we can set an env variable"""
 
922
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
923
        self.assertEqual(None, old)
 
924
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
 
925
 
 
926
    def test_double_set(self):
 
927
        """Test that we get the old value out"""
 
928
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
929
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
 
930
        self.assertEqual('foo', old)
 
931
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
 
932
 
 
933
    def test_unicode(self):
 
934
        """Environment can only contain plain strings
 
935
        
 
936
        So Unicode strings must be encoded.
 
937
        """
 
938
        # Try a few different characters, to see if we can get
 
939
        # one that will be valid in the user_encoding
 
940
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
 
941
        for uni_val in possible_vals:
 
942
            try:
 
943
                env_val = uni_val.encode(bzrlib.user_encoding)
 
944
            except UnicodeEncodeError:
 
945
                # Try a different character
 
946
                pass
 
947
            else:
 
948
                break
 
949
        else:
 
950
            raise TestSkipped('Cannot find a unicode character that works in'
 
951
                              ' encoding %s' % (bzrlib.user_encoding,))
 
952
 
 
953
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
 
954
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
 
955
 
 
956
    def test_unset(self):
 
957
        """Test that passing None will remove the env var"""
 
958
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
 
959
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
 
960
        self.assertEqual('foo', old)
 
961
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
 
962
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
 
963
 
 
964
 
 
965
class TestLocalTimeOffset(TestCase):
 
966
 
 
967
    def test_local_time_offset(self):
 
968
        """Test that local_time_offset() returns a sane value."""
 
969
        offset = osutils.local_time_offset()
 
970
        self.assertTrue(isinstance(offset, int))
 
971
        # Test that the offset is no more than a eighteen hours in
 
972
        # either direction.
 
973
        # Time zone handling is system specific, so it is difficult to
 
974
        # do more specific tests, but a value outside of this range is
 
975
        # probably wrong.
 
976
        eighteen_hours = 18 * 3600
 
977
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
 
978
 
 
979
    def test_local_time_offset_with_timestamp(self):
 
980
        """Test that local_time_offset() works with a timestamp."""
 
981
        offset = osutils.local_time_offset(1000000000.1234567)
 
982
        self.assertTrue(isinstance(offset, int))
 
983
        eighteen_hours = 18 * 3600
 
984
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)