~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-06-29 18:21:57 UTC
  • mfrom: (1711.2.72 jam-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060629182157-cdc39b5f9e4fac85
(jam) add run_bzr_error, clean up remerge tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
131
131
            finally:
132
132
                os.remove('socket')
133
133
 
134
 
    def test_get_umask(self):
135
 
        if sys.platform == 'win32':
136
 
            # umask always returns '0', no way to set it
137
 
            self.assertEqual(0, osutils.get_umask())
138
 
            return
139
 
 
140
 
        orig_umask = osutils.get_umask()
141
 
        try:
142
 
            os.umask(0222)
143
 
            self.assertEqual(0222, osutils.get_umask())
144
 
            os.umask(0022)
145
 
            self.assertEqual(0022, osutils.get_umask())
146
 
            os.umask(0002)
147
 
            self.assertEqual(0002, osutils.get_umask())
148
 
            os.umask(0027)
149
 
            self.assertEqual(0027, osutils.get_umask())
150
 
        finally:
151
 
            os.umask(orig_umask)
152
 
 
153
134
 
154
135
class TestSafeUnicode(TestCase):
155
136
 
195
176
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
196
177
 
197
178
    def test_getcwd(self):
198
 
        cwd = osutils._win32_getcwd()
199
 
        os_cwd = os.getcwdu()
200
 
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
201
 
        # win32 is inconsistent whether it returns lower or upper case
202
 
        # and even if it was consistent the user might type the other
203
 
        # so we force it to uppercase
204
 
        # running python.exe under cmd.exe return capital C:\\
205
 
        # running win32 python inside a cygwin shell returns lowercase
206
 
        self.assertEqual(os_cwd[0].upper(), cwd[0])
207
 
 
208
 
    def test_fixdrive(self):
209
 
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
210
 
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
211
 
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
 
179
        self.assertEqual(os.getcwdu().replace('\\', '/'), osutils._win32_getcwd())
212
180
 
213
181
 
214
182
class TestWin32FuncsDirs(TestCaseInTempDir):
217
185
    def test_getcwd(self):
218
186
        # Make sure getcwd can handle unicode filenames
219
187
        try:
220
 
            os.mkdir(u'mu-\xb5')
 
188
            os.mkdir(u'B\xe5gfors')
221
189
        except UnicodeError:
222
190
            raise TestSkipped("Unable to create Unicode filename")
223
191
 
224
 
        os.chdir(u'mu-\xb5')
 
192
        os.chdir(u'B\xe5gfors')
225
193
        # TODO: jam 20060427 This will probably fail on Mac OSX because
226
194
        #       it will change the normalization of B\xe5gfors
227
195
        #       Consider using a different unicode character, or make
228
196
        #       osutils.getcwd() renormalize the path.
229
 
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
 
197
        self.assertTrue(osutils._win32_getcwd().endswith(u'/B\xe5gfors'))
230
198
 
231
199
    def test_mkdtemp(self):
232
200
        tmpdir = osutils._win32_mkdtemp(dir='.')
245
213
        self.failIfExists('b')
246
214
        self.assertFileEqual('baz\n', 'a')
247
215
 
248
 
    def test_rename_missing_file(self):
249
 
        a = open('a', 'wb')
250
 
        a.write('foo\n')
251
 
        a.close()
252
 
 
253
 
        try:
254
 
            osutils._win32_rename('b', 'a')
255
 
        except (IOError, OSError), e:
256
 
            self.assertEqual(errno.ENOENT, e.errno)
257
 
        self.assertFileEqual('foo\n', 'a')
258
 
 
259
 
    def test_rename_missing_dir(self):
260
 
        os.mkdir('a')
261
 
        try:
262
 
            osutils._win32_rename('b', 'a')
263
 
        except (IOError, OSError), e:
264
 
            self.assertEqual(errno.ENOENT, e.errno)
265
 
 
266
 
    def test_rename_current_dir(self):
267
 
        os.mkdir('a')
268
 
        os.chdir('a')
269
 
        # You can't rename the working directory
270
 
        # doing rename non-existant . usually
271
 
        # just raises ENOENT, since non-existant
272
 
        # doesn't exist.
273
 
        try:
274
 
            osutils._win32_rename('b', '.')
275
 
        except (IOError, OSError), e:
276
 
            self.assertEqual(errno.ENOENT, e.errno)
277
 
 
278
 
 
279
 
class TestMacFuncsDirs(TestCaseInTempDir):
280
 
    """Test mac special functions that require directories."""
281
 
 
282
 
    def test_getcwd(self):
283
 
        # On Mac, this will actually create Ba\u030agfors
284
 
        # but chdir will still work, because it accepts both paths
285
 
        try:
286
 
            os.mkdir(u'B\xe5gfors')
287
 
        except UnicodeError:
288
 
            raise TestSkipped("Unable to create Unicode filename")
289
 
 
290
 
        os.chdir(u'B\xe5gfors')
291
 
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
292
 
 
293
 
    def test_getcwd_nonnorm(self):
294
 
        # Test that _mac_getcwd() will normalize this path
295
 
        try:
296
 
            os.mkdir(u'Ba\u030agfors')
297
 
        except UnicodeError:
298
 
            raise TestSkipped("Unable to create Unicode filename")
299
 
 
300
 
        os.chdir(u'Ba\u030agfors')
301
 
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
302
216
 
303
217
class TestSplitLines(TestCase):
304
218
 
326
240
            ]
327
241
        self.build_tree(tree)
328
242
        expected_dirblocks = [
329
 
                (('', '.'),
330
 
                 [('0file', '0file', 'file'),
331
 
                  ('1dir', '1dir', 'directory'),
332
 
                  ('2file', '2file', 'file'),
333
 
                 ]
334
 
                ),
335
 
                (('1dir', './1dir'),
336
 
                 [('1dir/0file', '0file', 'file'),
337
 
                  ('1dir/1dir', '1dir', 'directory'),
338
 
                 ]
339
 
                ),
340
 
                (('1dir/1dir', './1dir/1dir'),
341
 
                 [
342
 
                 ]
343
 
                ),
 
243
                [
 
244
                    ('0file', '0file', 'file'),
 
245
                    ('1dir', '1dir', 'directory'),
 
246
                    ('2file', '2file', 'file'),
 
247
                ],
 
248
                [
 
249
                    ('1dir/0file', '0file', 'file'),
 
250
                    ('1dir/1dir', '1dir', 'directory'),
 
251
                ],
 
252
                [
 
253
                ],
344
254
            ]
345
255
        result = []
346
256
        found_bzrdir = False
347
 
        for dirdetail, dirblock in osutils.walkdirs('.'):
 
257
        for dirblock in osutils.walkdirs('.'):
348
258
            if len(dirblock) and dirblock[0][1] == '.bzr':
349
259
                # this tests the filtering of selected paths
350
260
                found_bzrdir = True
351
261
                del dirblock[0]
352
 
            result.append((dirdetail, dirblock))
 
262
            result.append(dirblock)
353
263
 
354
264
        self.assertTrue(found_bzrdir)
355
265
        self.assertEqual(expected_dirblocks,
356
 
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
266
            [[line[0:3] for line in block] for block in result])
357
267
        # you can search a subdir only, with a supplied prefix.
358
268
        result = []
359
 
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
 
269
        for dirblock in osutils.walkdirs('1dir', '1dir'):
360
270
            result.append(dirblock)
361
271
        self.assertEqual(expected_dirblocks[1:],
362
 
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
 
272
            [[line[0:3] for line in block] for block in result])
363
273
 
364
274
    def assertPathCompare(self, path_less, path_greater):
365
275
        """check that path_less and path_greater compare correctly."""
439
349
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
440
350
 
441
351
 
442
 
class TestCopyTree(TestCaseInTempDir):
443
 
    
444
 
    def test_copy_basic_tree(self):
445
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
446
 
        osutils.copy_tree('source', 'target')
447
 
        self.assertEqual(['a', 'b'], os.listdir('target'))
448
 
        self.assertEqual(['c'], os.listdir('target/b'))
449
 
 
450
 
    def test_copy_tree_target_exists(self):
451
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
452
 
                         'target/'])
453
 
        osutils.copy_tree('source', 'target')
454
 
        self.assertEqual(['a', 'b'], os.listdir('target'))
455
 
        self.assertEqual(['c'], os.listdir('target/b'))
456
 
 
457
 
    def test_copy_tree_symlinks(self):
458
 
        if not osutils.has_symlinks():
459
 
            return
460
 
        self.build_tree(['source/'])
461
 
        os.symlink('a/generic/path', 'source/lnk')
462
 
        osutils.copy_tree('source', 'target')
463
 
        self.assertEqual(['lnk'], os.listdir('target'))
464
 
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
465
 
 
466
 
    def test_copy_tree_handlers(self):
467
 
        processed_files = []
468
 
        processed_links = []
469
 
        def file_handler(from_path, to_path):
470
 
            processed_files.append(('f', from_path, to_path))
471
 
        def dir_handler(from_path, to_path):
472
 
            processed_files.append(('d', from_path, to_path))
473
 
        def link_handler(from_path, to_path):
474
 
            processed_links.append((from_path, to_path))
475
 
        handlers = {'file':file_handler,
476
 
                    'directory':dir_handler,
477
 
                    'symlink':link_handler,
478
 
                   }
479
 
 
480
 
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
481
 
        if osutils.has_symlinks():
482
 
            os.symlink('a/generic/path', 'source/lnk')
483
 
        osutils.copy_tree('source', 'target', handlers=handlers)
484
 
 
485
 
        self.assertEqual([('d', 'source', 'target'),
486
 
                          ('f', 'source/a', 'target/a'),
487
 
                          ('d', 'source/b', 'target/b'),
488
 
                          ('f', 'source/b/c', 'target/b/c'),
489
 
                         ], processed_files)
490
 
        self.failIfExists('target')
491
 
        if osutils.has_symlinks():
492
 
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
493
 
 
494
 
 
495
352
class TestTerminalEncoding(TestCase):
496
353
    """Test the auto-detection of proper terminal encoding."""
497
354
 
529
386
        # and in the worst case, use bzrlib.user_encoding
530
387
        self.assertEqual('user_encoding', osutils.get_terminal_encoding())
531
388
 
532
 
 
533
 
class TestSetUnsetEnv(TestCase):
534
 
    """Test updating the environment"""
535
 
 
536
 
    def setUp(self):
537
 
        super(TestSetUnsetEnv, self).setUp()
538
 
 
539
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
540
 
                         'Environment was not cleaned up properly.'
541
 
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
542
 
        def cleanup():
543
 
            if 'BZR_TEST_ENV_VAR' in os.environ:
544
 
                del os.environ['BZR_TEST_ENV_VAR']
545
 
 
546
 
        self.addCleanup(cleanup)
547
 
 
548
 
    def test_set(self):
549
 
        """Test that we can set an env variable"""
550
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
551
 
        self.assertEqual(None, old)
552
 
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
553
 
 
554
 
    def test_double_set(self):
555
 
        """Test that we get the old value out"""
556
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
557
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
558
 
        self.assertEqual('foo', old)
559
 
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
560
 
 
561
 
    def test_unicode(self):
562
 
        """Environment can only contain plain strings
563
 
        
564
 
        So Unicode strings must be encoded.
565
 
        """
566
 
        # Try a few different characters, to see if we can get
567
 
        # one that will be valid in the user_encoding
568
 
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
569
 
        for uni_val in possible_vals:
570
 
            try:
571
 
                env_val = uni_val.encode(bzrlib.user_encoding)
572
 
            except UnicodeEncodeError:
573
 
                # Try a different character
574
 
                pass
575
 
            else:
576
 
                break
577
 
        else:
578
 
            raise TestSkipped('Cannot find a unicode character that works in'
579
 
                              ' encoding %s' % (bzrlib.user_encoding,))
580
 
 
581
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
582
 
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
583
 
 
584
 
    def test_unset(self):
585
 
        """Test that passing None will remove the env var"""
586
 
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
587
 
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
588
 
        self.assertEqual('foo', old)
589
 
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
590
 
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
591