~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: 2006-07-30 13:54:37 UTC
  • mto: (1946.2.6 reduce-knit-churn)
  • mto: This revision was merged to the branch mainline in revision 1898.
  • Revision ID: john@arbash-meinel.com-20060730135437-1d722abdb14bff76
(jelmer) Install new intertree tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005 by 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
23
23
import sys
24
24
 
25
25
import bzrlib
26
 
from bzrlib import (
27
 
    errors,
28
 
    osutils,
29
 
    )
30
26
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
27
import bzrlib.osutils as osutils
31
28
from bzrlib.tests import (
32
29
        StringIOWrapper,
33
30
        TestCase, 
81
78
        self.assertEqual(type(result), str)
82
79
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
83
80
 
84
 
    def test_is_inside(self):
85
 
        is_inside = osutils.is_inside
86
 
        self.assertTrue(is_inside('src', 'src/foo.c'))
87
 
        self.assertFalse(is_inside('src', 'srccontrol'))
88
 
        self.assertTrue(is_inside('src', 'src/a/a/a/foo.c'))
89
 
        self.assertTrue(is_inside('foo.c', 'foo.c'))
90
 
        self.assertFalse(is_inside('foo.c', ''))
91
 
        self.assertTrue(is_inside('', 'foo.c'))
92
81
 
93
82
    def test_rmtree(self):
94
83
        # Check to remove tree with read-only files/dirs
142
131
            finally:
143
132
                os.remove('socket')
144
133
 
145
 
    def test_get_umask(self):
146
 
        if sys.platform == 'win32':
147
 
            # umask always returns '0', no way to set it
148
 
            self.assertEqual(0, osutils.get_umask())
149
 
            return
150
 
 
151
 
        orig_umask = osutils.get_umask()
152
 
        try:
153
 
            os.umask(0222)
154
 
            self.assertEqual(0222, osutils.get_umask())
155
 
            os.umask(0022)
156
 
            self.assertEqual(0022, osutils.get_umask())
157
 
            os.umask(0002)
158
 
            self.assertEqual(0002, osutils.get_umask())
159
 
            os.umask(0027)
160
 
            self.assertEqual(0027, osutils.get_umask())
161
 
        finally:
162
 
            os.umask(orig_umask)
163
 
 
164
 
    def assertFormatedDelta(self, expected, seconds):
165
 
        """Assert osutils.format_delta formats as expected"""
166
 
        actual = osutils.format_delta(seconds)
167
 
        self.assertEqual(expected, actual)
168
 
 
169
 
    def test_format_delta(self):
170
 
        self.assertFormatedDelta('0 seconds ago', 0)
171
 
        self.assertFormatedDelta('1 second ago', 1)
172
 
        self.assertFormatedDelta('10 seconds ago', 10)
173
 
        self.assertFormatedDelta('59 seconds ago', 59)
174
 
        self.assertFormatedDelta('89 seconds ago', 89)
175
 
        self.assertFormatedDelta('1 minute, 30 seconds ago', 90)
176
 
        self.assertFormatedDelta('3 minutes, 0 seconds ago', 180)
177
 
        self.assertFormatedDelta('3 minutes, 1 second ago', 181)
178
 
        self.assertFormatedDelta('10 minutes, 15 seconds ago', 615)
179
 
        self.assertFormatedDelta('30 minutes, 59 seconds ago', 1859)
180
 
        self.assertFormatedDelta('31 minutes, 0 seconds ago', 1860)
181
 
        self.assertFormatedDelta('60 minutes, 0 seconds ago', 3600)
182
 
        self.assertFormatedDelta('89 minutes, 59 seconds ago', 5399)
183
 
        self.assertFormatedDelta('1 hour, 30 minutes ago', 5400)
184
 
        self.assertFormatedDelta('2 hours, 30 minutes ago', 9017)
185
 
        self.assertFormatedDelta('10 hours, 0 minutes ago', 36000)
186
 
        self.assertFormatedDelta('24 hours, 0 minutes ago', 86400)
187
 
        self.assertFormatedDelta('35 hours, 59 minutes ago', 129599)
188
 
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129600)
189
 
        self.assertFormatedDelta('36 hours, 0 minutes ago', 129601)
190
 
        self.assertFormatedDelta('36 hours, 1 minute ago', 129660)
191
 
        self.assertFormatedDelta('36 hours, 1 minute ago', 129661)
192
 
        self.assertFormatedDelta('84 hours, 10 minutes ago', 303002)
193
 
 
194
 
        # We handle when time steps the wrong direction because computers
195
 
        # don't have synchronized clocks.
196
 
        self.assertFormatedDelta('84 hours, 10 minutes in the future', -303002)
197
 
        self.assertFormatedDelta('1 second in the future', -1)
198
 
        self.assertFormatedDelta('2 seconds in the future', -2)
199
 
 
200
 
    def test_dereference_path(self):
201
 
        if not osutils.has_symlinks():
202
 
            raise TestSkipped('Symlinks are not supported on this platform')
203
 
        cwd = osutils.realpath('.')
204
 
        os.mkdir('bar')
205
 
        bar_path = osutils.pathjoin(cwd, 'bar')
206
 
        # Using './' to avoid bug #1213894 (first path component not
207
 
        # dereferenced) in Python 2.4.1 and earlier
208
 
        self.assertEqual(bar_path, osutils.realpath('./bar'))
209
 
        os.symlink('bar', 'foo')
210
 
        self.assertEqual(bar_path, osutils.realpath('./foo'))
211
 
        
212
 
        # Does not dereference terminal symlinks
213
 
        foo_path = osutils.pathjoin(cwd, 'foo')
214
 
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
215
 
 
216
 
        # Dereferences parent symlinks
217
 
        os.mkdir('bar/baz')
218
 
        baz_path = osutils.pathjoin(bar_path, 'baz')
219
 
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
220
 
 
221
 
        # Dereferences parent symlinks that are the first path element
222
 
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
223
 
 
224
 
        # Dereferences parent symlinks in absolute paths
225
 
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
226
 
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
227
 
 
228
134
 
229
135
class TestSafeUnicode(TestCase):
230
136
 
350
256
        except (IOError, OSError), e:
351
257
            self.assertEqual(errno.ENOENT, e.errno)
352
258
 
353
 
    def test_splitpath(self):
354
 
        def check(expected, path):
355
 
            self.assertEqual(expected, osutils.splitpath(path))
356
 
 
357
 
        check(['a'], 'a')
358
 
        check(['a', 'b'], 'a/b')
359
 
        check(['a', 'b'], 'a/./b')
360
 
        check(['a', '.b'], 'a/.b')
361
 
        check(['a', '.b'], 'a\\.b')
362
 
 
363
 
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
364
 
 
365
259
 
366
260
class TestMacFuncsDirs(TestCaseInTempDir):
367
261
    """Test mac special functions that require directories."""
387
281
        os.chdir(u'Ba\u030agfors')
388
282
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
389
283
 
390
 
 
391
284
class TestSplitLines(TestCase):
392
285
 
393
286
    def test_split_unicode(self):
414
307
            ]
415
308
        self.build_tree(tree)
416
309
        expected_dirblocks = [
417
 
                (('', '.'),
418
 
                 [('0file', '0file', 'file'),
419
 
                  ('1dir', '1dir', 'directory'),
420
 
                  ('2file', '2file', 'file'),
421
 
                 ]
422
 
                ),
423
 
                (('1dir', './1dir'),
424
 
                 [('1dir/0file', '0file', 'file'),
425
 
                  ('1dir/1dir', '1dir', 'directory'),
426
 
                 ]
427
 
                ),
428
 
                (('1dir/1dir', './1dir/1dir'),
429
 
                 [
430
 
                 ]
431
 
                ),
 
310
                [
 
311
                    ('0file', '0file', 'file'),
 
312
                    ('1dir', '1dir', 'directory'),
 
313
                    ('2file', '2file', 'file'),
 
314
                ],
 
315
                [
 
316
                    ('1dir/0file', '0file', 'file'),
 
317
                    ('1dir/1dir', '1dir', 'directory'),
 
318
                ],
 
319
                [
 
320
                ],
432
321
            ]
433
322
        result = []
434
323
        found_bzrdir = False
435
 
        for dirdetail, dirblock in osutils.walkdirs('.'):
 
324
        for dirblock in osutils.walkdirs('.'):
436
325
            if len(dirblock) and dirblock[0][1] == '.bzr':
437
326
                # this tests the filtering of selected paths
438
327
                found_bzrdir = True
439
328
                del dirblock[0]
440
 
            result.append((dirdetail, dirblock))
 
329
            result.append(dirblock)
441
330
 
442
331
        self.assertTrue(found_bzrdir)
443
332
        self.assertEqual(expected_dirblocks,
444
 
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
333
            [[line[0:3] for line in block] for block in result])
445
334
        # you can search a subdir only, with a supplied prefix.
446
335
        result = []
447
 
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
336
        for dirblock in osutils.walkdirs('1dir', '1dir'):
448
337
            result.append(dirblock)
449
338
        self.assertEqual(expected_dirblocks[1:],
450
 
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
339
            [[line[0:3] for line in block] for block in result])
451
340
 
452
341
    def assertPathCompare(self, path_less, path_greater):
453
342
        """check that path_less and path_greater compare correctly."""
527
416
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
528
417
 
529
418
 
530
 
class TestCopyTree(TestCaseInTempDir):
531
 
    
532
 
    def test_copy_basic_tree(self):
533
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
534
 
        osutils.copy_tree('source', 'target')
535
 
        self.assertEqual(['a', 'b'], os.listdir('target'))
536
 
        self.assertEqual(['c'], os.listdir('target/b'))
537
 
 
538
 
    def test_copy_tree_target_exists(self):
539
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
540
 
                         'target/'])
541
 
        osutils.copy_tree('source', 'target')
542
 
        self.assertEqual(['a', 'b'], os.listdir('target'))
543
 
        self.assertEqual(['c'], os.listdir('target/b'))
544
 
 
545
 
    def test_copy_tree_symlinks(self):
546
 
        if not osutils.has_symlinks():
547
 
            return
548
 
        self.build_tree(['source/'])
549
 
        os.symlink('a/generic/path', 'source/lnk')
550
 
        osutils.copy_tree('source', 'target')
551
 
        self.assertEqual(['lnk'], os.listdir('target'))
552
 
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
553
 
 
554
 
    def test_copy_tree_handlers(self):
555
 
        processed_files = []
556
 
        processed_links = []
557
 
        def file_handler(from_path, to_path):
558
 
            processed_files.append(('f', from_path, to_path))
559
 
        def dir_handler(from_path, to_path):
560
 
            processed_files.append(('d', from_path, to_path))
561
 
        def link_handler(from_path, to_path):
562
 
            processed_links.append((from_path, to_path))
563
 
        handlers = {'file':file_handler,
564
 
                    'directory':dir_handler,
565
 
                    'symlink':link_handler,
566
 
                   }
567
 
 
568
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
569
 
        if osutils.has_symlinks():
570
 
            os.symlink('a/generic/path', 'source/lnk')
571
 
        osutils.copy_tree('source', 'target', handlers=handlers)
572
 
 
573
 
        self.assertEqual([('d', 'source', 'target'),
574
 
                          ('f', 'source/a', 'target/a'),
575
 
                          ('d', 'source/b', 'target/b'),
576
 
                          ('f', 'source/b/c', 'target/b/c'),
577
 
                         ], processed_files)
578
 
        self.failIfExists('target')
579
 
        if osutils.has_symlinks():
580
 
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
581
 
 
582
 
 
583
419
class TestTerminalEncoding(TestCase):
584
420
    """Test the auto-detection of proper terminal encoding."""
585
421
 
617
453
        # and in the worst case, use bzrlib.user_encoding
618
454
        self.assertEqual('user_encoding', osutils.get_terminal_encoding())
619
455
 
620
 
 
621
 
class TestSetUnsetEnv(TestCase):
622
 
    """Test updating the environment"""
623
 
 
624
 
    def setUp(self):
625
 
        super(TestSetUnsetEnv, self).setUp()
626
 
 
627
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
628
 
                         'Environment was not cleaned up properly.'
629
 
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
630
 
        def cleanup():
631
 
            if 'BZR_TEST_ENV_VAR' in os.environ:
632
 
                del os.environ['BZR_TEST_ENV_VAR']
633
 
 
634
 
        self.addCleanup(cleanup)
635
 
 
636
 
    def test_set(self):
637
 
        """Test that we can set an env variable"""
638
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
639
 
        self.assertEqual(None, old)
640
 
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
641
 
 
642
 
    def test_double_set(self):
643
 
        """Test that we get the old value out"""
644
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
645
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
646
 
        self.assertEqual('foo', old)
647
 
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
648
 
 
649
 
    def test_unicode(self):
650
 
        """Environment can only contain plain strings
651
 
        
652
 
        So Unicode strings must be encoded.
653
 
        """
654
 
        # Try a few different characters, to see if we can get
655
 
        # one that will be valid in the user_encoding
656
 
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
657
 
        for uni_val in possible_vals:
658
 
            try:
659
 
                env_val = uni_val.encode(bzrlib.user_encoding)
660
 
            except UnicodeEncodeError:
661
 
                # Try a different character
662
 
                pass
663
 
            else:
664
 
                break
665
 
        else:
666
 
            raise TestSkipped('Cannot find a unicode character that works in'
667
 
                              ' encoding %s' % (bzrlib.user_encoding,))
668
 
 
669
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
670
 
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
671
 
 
672
 
    def test_unset(self):
673
 
        """Test that passing None will remove the env var"""
674
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
675
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
676
 
        self.assertEqual('foo', old)
677
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
678
 
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
679