1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tests for the osutils wrapper."""
19
from cStringIO import StringIO
34
from bzrlib.tests import (
40
class _UTF8DirReaderFeature(tests.Feature):
44
from bzrlib import _readdir_pyx
45
self.reader = _readdir_pyx.UTF8DirReader
50
def feature_name(self):
51
return 'bzrlib._readdir_pyx'
53
UTF8DirReaderFeature = _UTF8DirReaderFeature()
56
class TestOSUtils(tests.TestCaseInTempDir):
58
def test_contains_whitespace(self):
59
self.failUnless(osutils.contains_whitespace(u' '))
60
self.failUnless(osutils.contains_whitespace(u'hello there'))
61
self.failUnless(osutils.contains_whitespace(u'hellothere\n'))
62
self.failUnless(osutils.contains_whitespace(u'hello\nthere'))
63
self.failUnless(osutils.contains_whitespace(u'hello\rthere'))
64
self.failUnless(osutils.contains_whitespace(u'hello\tthere'))
66
# \xa0 is "Non-breaking-space" which on some python locales thinks it
67
# is whitespace, but we do not.
68
self.failIf(osutils.contains_whitespace(u''))
69
self.failIf(osutils.contains_whitespace(u'hellothere'))
70
self.failIf(osutils.contains_whitespace(u'hello\xa0there'))
72
def test_fancy_rename(self):
73
# This should work everywhere
75
osutils.fancy_rename(a, b,
76
rename_func=os.rename,
77
unlink_func=os.unlink)
79
open('a', 'wb').write('something in a\n')
81
self.failIfExists('a')
82
self.failUnlessExists('b')
83
self.check_file_contents('b', 'something in a\n')
85
open('a', 'wb').write('new something in a\n')
88
self.check_file_contents('a', 'something in a\n')
90
def test_rename(self):
91
# Rename should be semi-atomic on all platforms
92
open('a', 'wb').write('something in a\n')
93
osutils.rename('a', 'b')
94
self.failIfExists('a')
95
self.failUnlessExists('b')
96
self.check_file_contents('b', 'something in a\n')
98
open('a', 'wb').write('new something in a\n')
99
osutils.rename('b', 'a')
101
self.check_file_contents('a', 'something in a\n')
103
# TODO: test fancy_rename using a MemoryTransport
105
def test_rename_change_case(self):
106
# on Windows we should be able to change filename case by rename
107
self.build_tree(['a', 'b/'])
108
osutils.rename('a', 'A')
109
osutils.rename('b', 'B')
110
# we can't use failUnlessExists on case-insensitive filesystem
111
# so try to check shape of the tree
112
shape = sorted(os.listdir('.'))
113
self.assertEquals(['A', 'B'], shape)
115
def test_01_rand_chars_empty(self):
116
result = osutils.rand_chars(0)
117
self.assertEqual(result, '')
119
def test_02_rand_chars_100(self):
120
result = osutils.rand_chars(100)
121
self.assertEqual(len(result), 100)
122
self.assertEqual(type(result), str)
123
self.assertContainsRe(result, r'^[a-z0-9]{100}$')
125
def test_is_inside(self):
126
is_inside = osutils.is_inside
127
self.assertTrue(is_inside('src', 'src/foo.c'))
128
self.assertFalse(is_inside('src', 'srccontrol'))
129
self.assertTrue(is_inside('src', 'src/a/a/a/foo.c'))
130
self.assertTrue(is_inside('foo.c', 'foo.c'))
131
self.assertFalse(is_inside('foo.c', ''))
132
self.assertTrue(is_inside('', 'foo.c'))
134
def test_is_inside_any(self):
135
SRC_FOO_C = osutils.pathjoin('src', 'foo.c')
136
for dirs, fn in [(['src', 'doc'], SRC_FOO_C),
137
(['src'], SRC_FOO_C),
140
self.assert_(osutils.is_inside_any(dirs, fn))
141
for dirs, fn in [(['src'], 'srccontrol'),
142
(['src'], 'srccontrol/foo')]:
143
self.assertFalse(osutils.is_inside_any(dirs, fn))
145
def test_is_inside_or_parent_of_any(self):
146
for dirs, fn in [(['src', 'doc'], 'src/foo.c'),
147
(['src'], 'src/foo.c'),
148
(['src/bar.c'], 'src'),
149
(['src/bar.c', 'bla/foo.c'], 'src'),
152
self.assert_(osutils.is_inside_or_parent_of_any(dirs, fn))
154
for dirs, fn in [(['src'], 'srccontrol'),
155
(['srccontrol/foo.c'], 'src'),
156
(['src'], 'srccontrol/foo')]:
157
self.assertFalse(osutils.is_inside_or_parent_of_any(dirs, fn))
159
def test_rmtree(self):
160
# Check to remove tree with read-only files/dirs
162
f = file('dir/file', 'w')
165
# would like to also try making the directory readonly, but at the
166
# moment python shutil.rmtree doesn't handle that properly - it would
167
# need to chmod the directory before removing things inside it - deferred
168
# for now -- mbp 20060505
169
# osutils.make_readonly('dir')
170
osutils.make_readonly('dir/file')
172
osutils.rmtree('dir')
174
self.failIfExists('dir/file')
175
self.failIfExists('dir')
177
def test_file_kind(self):
178
self.build_tree(['file', 'dir/'])
179
self.assertEquals('file', osutils.file_kind('file'))
180
self.assertEquals('directory', osutils.file_kind('dir/'))
181
if osutils.has_symlinks():
182
os.symlink('symlink', 'symlink')
183
self.assertEquals('symlink', osutils.file_kind('symlink'))
185
# TODO: jam 20060529 Test a block device
187
os.lstat('/dev/null')
189
if e.errno not in (errno.ENOENT,):
192
self.assertEquals('chardev', osutils.file_kind('/dev/null'))
194
mkfifo = getattr(os, 'mkfifo', None)
198
self.assertEquals('fifo', osutils.file_kind('fifo'))
202
AF_UNIX = getattr(socket, 'AF_UNIX', None)
204
s = socket.socket(AF_UNIX)
207
self.assertEquals('socket', osutils.file_kind('socket'))
211
def test_kind_marker(self):
212
self.assertEqual(osutils.kind_marker('file'), '')
213
self.assertEqual(osutils.kind_marker('directory'), '/')
214
self.assertEqual(osutils.kind_marker('symlink'), '@')
215
self.assertEqual(osutils.kind_marker('tree-reference'), '+')
217
def test_get_umask(self):
218
if sys.platform == 'win32':
219
# umask always returns '0', no way to set it
220
self.assertEqual(0, osutils.get_umask())
223
orig_umask = osutils.get_umask()
224
self.addCleanup(os.umask, orig_umask)
226
self.assertEqual(0222, osutils.get_umask())
228
self.assertEqual(0022, osutils.get_umask())
230
self.assertEqual(0002, osutils.get_umask())
232
self.assertEqual(0027, osutils.get_umask())
234
def assertFormatedDelta(self, expected, seconds):
235
"""Assert osutils.format_delta formats as expected"""
236
actual = osutils.format_delta(seconds)
237
self.assertEqual(expected, actual)
239
def test_format_delta(self):
240
self.assertFormatedDelta('0 seconds ago', 0)
241
self.assertFormatedDelta('1 second ago', 1)
242
self.assertFormatedDelta('10 seconds ago', 10)
243
self.assertFormatedDelta('59 seconds ago', 59)
244
self.assertFormatedDelta('89 seconds ago', 89)
245
self.assertFormatedDelta('1 minute, 30 seconds ago', 90)
246
self.assertFormatedDelta('3 minutes, 0 seconds ago', 180)
247
self.assertFormatedDelta('3 minutes, 1 second ago', 181)
248
self.assertFormatedDelta('10 minutes, 15 seconds ago', 615)
249
self.assertFormatedDelta('30 minutes, 59 seconds ago', 1859)
250
self.assertFormatedDelta('31 minutes, 0 seconds ago', 1860)
251
self.assertFormatedDelta('60 minutes, 0 seconds ago', 3600)
252
self.assertFormatedDelta('89 minutes, 59 seconds ago', 5399)
253
self.assertFormatedDelta('1 hour, 30 minutes ago', 5400)
254
self.assertFormatedDelta('2 hours, 30 minutes ago', 9017)
255
self.assertFormatedDelta('10 hours, 0 minutes ago', 36000)
256
self.assertFormatedDelta('24 hours, 0 minutes ago', 86400)
257
self.assertFormatedDelta('35 hours, 59 minutes ago', 129599)
258
self.assertFormatedDelta('36 hours, 0 minutes ago', 129600)
259
self.assertFormatedDelta('36 hours, 0 minutes ago', 129601)
260
self.assertFormatedDelta('36 hours, 1 minute ago', 129660)
261
self.assertFormatedDelta('36 hours, 1 minute ago', 129661)
262
self.assertFormatedDelta('84 hours, 10 minutes ago', 303002)
264
# We handle when time steps the wrong direction because computers
265
# don't have synchronized clocks.
266
self.assertFormatedDelta('84 hours, 10 minutes in the future', -303002)
267
self.assertFormatedDelta('1 second in the future', -1)
268
self.assertFormatedDelta('2 seconds in the future', -2)
270
def test_format_date(self):
271
self.assertRaises(errors.UnsupportedTimezoneFormat,
272
osutils.format_date, 0, timezone='foo')
273
self.assertIsInstance(osutils.format_date(0), str)
274
self.assertIsInstance(osutils.format_local_date(0), unicode)
275
# Testing for the actual value of the local weekday without
276
# duplicating the code from format_date is difficult.
277
# Instead blackbox.test_locale should check for localized
278
# dates once they do occur in output strings.
280
def test_dereference_path(self):
281
self.requireFeature(tests.SymlinkFeature)
282
cwd = osutils.realpath('.')
284
bar_path = osutils.pathjoin(cwd, 'bar')
285
# Using './' to avoid bug #1213894 (first path component not
286
# dereferenced) in Python 2.4.1 and earlier
287
self.assertEqual(bar_path, osutils.realpath('./bar'))
288
os.symlink('bar', 'foo')
289
self.assertEqual(bar_path, osutils.realpath('./foo'))
291
# Does not dereference terminal symlinks
292
foo_path = osutils.pathjoin(cwd, 'foo')
293
self.assertEqual(foo_path, osutils.dereference_path('./foo'))
295
# Dereferences parent symlinks
297
baz_path = osutils.pathjoin(bar_path, 'baz')
298
self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
300
# Dereferences parent symlinks that are the first path element
301
self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
303
# Dereferences parent symlinks in absolute paths
304
foo_baz_path = osutils.pathjoin(foo_path, 'baz')
305
self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
307
def test_changing_access(self):
308
f = file('file', 'w')
312
# Make a file readonly
313
osutils.make_readonly('file')
314
mode = os.lstat('file').st_mode
315
self.assertEqual(mode, mode & 0777555)
317
# Make a file writable
318
osutils.make_writable('file')
319
mode = os.lstat('file').st_mode
320
self.assertEqual(mode, mode | 0200)
322
if osutils.has_symlinks():
323
# should not error when handed a symlink
324
os.symlink('nonexistent', 'dangling')
325
osutils.make_readonly('dangling')
326
osutils.make_writable('dangling')
328
def test_kind_marker(self):
329
self.assertEqual("", osutils.kind_marker("file"))
330
self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
331
self.assertEqual("@", osutils.kind_marker("symlink"))
332
self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
334
def test_host_os_dereferences_symlinks(self):
335
osutils.host_os_dereferences_symlinks()
338
class TestCanonicalRelPath(tests.TestCaseInTempDir):
340
_test_needs_features = [tests.CaseInsCasePresFilenameFeature]
342
def test_canonical_relpath_simple(self):
343
f = file('MixedCaseName', 'w')
345
# Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
346
real_base_dir = osutils.realpath(self.test_base_dir)
347
actual = osutils.canonical_relpath(real_base_dir, 'mixedcasename')
348
self.failUnlessEqual('work/MixedCaseName', actual)
350
def test_canonical_relpath_missing_tail(self):
351
os.mkdir('MixedCaseParent')
352
# Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
353
real_base_dir = osutils.realpath(self.test_base_dir)
354
actual = osutils.canonical_relpath(real_base_dir,
355
'mixedcaseparent/nochild')
356
self.failUnlessEqual('work/MixedCaseParent/nochild', actual)
359
class TestPumpFile(tests.TestCase):
360
"""Test pumpfile method."""
363
tests.TestCase.setUp(self)
364
# create a test datablock
365
self.block_size = 512
366
pattern = '0123456789ABCDEF'
367
self.test_data = pattern * (3 * self.block_size / len(pattern))
368
self.test_data_len = len(self.test_data)
370
def test_bracket_block_size(self):
371
"""Read data in blocks with the requested read size bracketing the
373
# make sure test data is larger than max read size
374
self.assertTrue(self.test_data_len > self.block_size)
376
from_file = file_utils.FakeReadFile(self.test_data)
379
# read (max / 2) bytes and verify read size wasn't affected
380
num_bytes_to_read = self.block_size / 2
381
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
382
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
383
self.assertEqual(from_file.get_read_count(), 1)
385
# read (max) bytes and verify read size wasn't affected
386
num_bytes_to_read = self.block_size
387
from_file.reset_read_count()
388
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
389
self.assertEqual(from_file.get_max_read_size(), num_bytes_to_read)
390
self.assertEqual(from_file.get_read_count(), 1)
392
# read (max + 1) bytes and verify read size was limited
393
num_bytes_to_read = self.block_size + 1
394
from_file.reset_read_count()
395
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
396
self.assertEqual(from_file.get_max_read_size(), self.block_size)
397
self.assertEqual(from_file.get_read_count(), 2)
399
# finish reading the rest of the data
400
num_bytes_to_read = self.test_data_len - to_file.tell()
401
osutils.pumpfile(from_file, to_file, num_bytes_to_read, self.block_size)
403
# report error if the data wasn't equal (we only report the size due
404
# to the length of the data)
405
response_data = to_file.getvalue()
406
if response_data != self.test_data:
407
message = "Data not equal. Expected %d bytes, received %d."
408
self.fail(message % (len(response_data), self.test_data_len))
410
def test_specified_size(self):
411
"""Request a transfer larger than the maximum block size and verify
412
that the maximum read doesn't exceed the block_size."""
413
# make sure test data is larger than max read size
414
self.assertTrue(self.test_data_len > self.block_size)
416
# retrieve data in blocks
417
from_file = file_utils.FakeReadFile(self.test_data)
419
osutils.pumpfile(from_file, to_file, self.test_data_len,
422
# verify read size was equal to the maximum read size
423
self.assertTrue(from_file.get_max_read_size() > 0)
424
self.assertEqual(from_file.get_max_read_size(), self.block_size)
425
self.assertEqual(from_file.get_read_count(), 3)
427
# report error if the data wasn't equal (we only report the size due
428
# to the length of the data)
429
response_data = to_file.getvalue()
430
if response_data != self.test_data:
431
message = "Data not equal. Expected %d bytes, received %d."
432
self.fail(message % (len(response_data), self.test_data_len))
434
def test_to_eof(self):
435
"""Read to end-of-file and verify that the reads are not larger than
436
the maximum read size."""
437
# make sure test data is larger than max read size
438
self.assertTrue(self.test_data_len > self.block_size)
440
# retrieve data to EOF
441
from_file = file_utils.FakeReadFile(self.test_data)
443
osutils.pumpfile(from_file, to_file, -1, self.block_size)
445
# verify read size was equal to the maximum read size
446
self.assertEqual(from_file.get_max_read_size(), self.block_size)
447
self.assertEqual(from_file.get_read_count(), 4)
449
# report error if the data wasn't equal (we only report the size due
450
# to the length of the data)
451
response_data = to_file.getvalue()
452
if response_data != self.test_data:
453
message = "Data not equal. Expected %d bytes, received %d."
454
self.fail(message % (len(response_data), self.test_data_len))
456
def test_defaults(self):
457
"""Verifies that the default arguments will read to EOF -- this
458
test verifies that any existing usages of pumpfile will not be broken
459
with this new version."""
460
# retrieve data using default (old) pumpfile method
461
from_file = file_utils.FakeReadFile(self.test_data)
463
osutils.pumpfile(from_file, to_file)
465
# report error if the data wasn't equal (we only report the size due
466
# to the length of the data)
467
response_data = to_file.getvalue()
468
if response_data != self.test_data:
469
message = "Data not equal. Expected %d bytes, received %d."
470
self.fail(message % (len(response_data), self.test_data_len))
472
def test_report_activity(self):
474
def log_activity(length, direction):
475
activity.append((length, direction))
476
from_file = StringIO(self.test_data)
478
osutils.pumpfile(from_file, to_file, buff_size=500,
479
report_activity=log_activity, direction='read')
480
self.assertEqual([(500, 'read'), (500, 'read'), (500, 'read'),
481
(36, 'read')], activity)
483
from_file = StringIO(self.test_data)
486
osutils.pumpfile(from_file, to_file, buff_size=500,
487
report_activity=log_activity, direction='write')
488
self.assertEqual([(500, 'write'), (500, 'write'), (500, 'write'),
489
(36, 'write')], activity)
491
# And with a limited amount of data
492
from_file = StringIO(self.test_data)
495
osutils.pumpfile(from_file, to_file, buff_size=500, read_length=1028,
496
report_activity=log_activity, direction='read')
497
self.assertEqual([(500, 'read'), (500, 'read'), (28, 'read')], activity)
501
class TestPumpStringFile(tests.TestCase):
503
def test_empty(self):
505
osutils.pump_string_file("", output)
506
self.assertEqual("", output.getvalue())
508
def test_more_than_segment_size(self):
510
osutils.pump_string_file("123456789", output, 2)
511
self.assertEqual("123456789", output.getvalue())
513
def test_segment_size(self):
515
osutils.pump_string_file("12", output, 2)
516
self.assertEqual("12", output.getvalue())
518
def test_segment_size_multiple(self):
520
osutils.pump_string_file("1234", output, 2)
521
self.assertEqual("1234", output.getvalue())
524
class TestSafeUnicode(tests.TestCase):
526
def test_from_ascii_string(self):
527
self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
529
def test_from_unicode_string_ascii_contents(self):
530
self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
532
def test_from_unicode_string_unicode_contents(self):
533
self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
535
def test_from_utf8_string(self):
536
self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
538
def test_bad_utf8_string(self):
539
self.assertRaises(errors.BzrBadParameterNotUnicode,
540
osutils.safe_unicode,
544
class TestSafeUtf8(tests.TestCase):
546
def test_from_ascii_string(self):
548
self.assertEqual('foobar', osutils.safe_utf8(f))
550
def test_from_unicode_string_ascii_contents(self):
551
self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
553
def test_from_unicode_string_unicode_contents(self):
554
self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
556
def test_from_utf8_string(self):
557
self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
559
def test_bad_utf8_string(self):
560
self.assertRaises(errors.BzrBadParameterNotUnicode,
561
osutils.safe_utf8, '\xbb\xbb')
564
class TestSafeRevisionId(tests.TestCase):
566
def test_from_ascii_string(self):
567
# this shouldn't give a warning because it's getting an ascii string
568
self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
570
def test_from_unicode_string_ascii_contents(self):
571
self.assertEqual('bargam',
572
osutils.safe_revision_id(u'bargam', warn=False))
574
def test_from_unicode_deprecated(self):
575
self.assertEqual('bargam',
576
self.callDeprecated([osutils._revision_id_warning],
577
osutils.safe_revision_id, u'bargam'))
579
def test_from_unicode_string_unicode_contents(self):
580
self.assertEqual('bargam\xc2\xae',
581
osutils.safe_revision_id(u'bargam\xae', warn=False))
583
def test_from_utf8_string(self):
584
self.assertEqual('foo\xc2\xae',
585
osutils.safe_revision_id('foo\xc2\xae'))
588
"""Currently, None is a valid revision_id"""
589
self.assertEqual(None, osutils.safe_revision_id(None))
592
class TestSafeFileId(tests.TestCase):
594
def test_from_ascii_string(self):
595
self.assertEqual('foobar', osutils.safe_file_id('foobar'))
597
def test_from_unicode_string_ascii_contents(self):
598
self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
600
def test_from_unicode_deprecated(self):
601
self.assertEqual('bargam',
602
self.callDeprecated([osutils._file_id_warning],
603
osutils.safe_file_id, u'bargam'))
605
def test_from_unicode_string_unicode_contents(self):
606
self.assertEqual('bargam\xc2\xae',
607
osutils.safe_file_id(u'bargam\xae', warn=False))
609
def test_from_utf8_string(self):
610
self.assertEqual('foo\xc2\xae',
611
osutils.safe_file_id('foo\xc2\xae'))
614
"""Currently, None is a valid revision_id"""
615
self.assertEqual(None, osutils.safe_file_id(None))
618
class TestWin32Funcs(tests.TestCase):
619
"""Test that _win32 versions of os utilities return appropriate paths."""
621
def test_abspath(self):
622
self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
623
self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
624
self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
625
self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
627
def test_realpath(self):
628
self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
629
self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
631
def test_pathjoin(self):
632
self.assertEqual('path/to/foo',
633
osutils._win32_pathjoin('path', 'to', 'foo'))
634
self.assertEqual('C:/foo',
635
osutils._win32_pathjoin('path\\to', 'C:\\foo'))
636
self.assertEqual('C:/foo',
637
osutils._win32_pathjoin('path/to', 'C:/foo'))
638
self.assertEqual('path/to/foo',
639
osutils._win32_pathjoin('path/to/', 'foo'))
640
self.assertEqual('/foo',
641
osutils._win32_pathjoin('C:/path/to/', '/foo'))
642
self.assertEqual('/foo',
643
osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
645
def test_normpath(self):
646
self.assertEqual('path/to/foo',
647
osutils._win32_normpath(r'path\\from\..\to\.\foo'))
648
self.assertEqual('path/to/foo',
649
osutils._win32_normpath('path//from/../to/./foo'))
651
def test_getcwd(self):
652
cwd = osutils._win32_getcwd()
653
os_cwd = os.getcwdu()
654
self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
655
# win32 is inconsistent whether it returns lower or upper case
656
# and even if it was consistent the user might type the other
657
# so we force it to uppercase
658
# running python.exe under cmd.exe return capital C:\\
659
# running win32 python inside a cygwin shell returns lowercase
660
self.assertEqual(os_cwd[0].upper(), cwd[0])
662
def test_fixdrive(self):
663
self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
664
self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
665
self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
667
def test_win98_abspath(self):
669
self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
670
self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
672
self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
673
self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
675
cwd = osutils.getcwd().rstrip('/')
676
drive = osutils._nt_splitdrive(cwd)[0]
677
self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
678
self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
681
self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
684
class TestWin32FuncsDirs(tests.TestCaseInTempDir):
685
"""Test win32 functions that create files."""
687
def test_getcwd(self):
688
self.requireFeature(tests.UnicodeFilenameFeature)
691
# TODO: jam 20060427 This will probably fail on Mac OSX because
692
# it will change the normalization of B\xe5gfors
693
# Consider using a different unicode character, or make
694
# osutils.getcwd() renormalize the path.
695
self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
697
def test_minimum_path_selection(self):
698
self.assertEqual(set(),
699
osutils.minimum_path_selection([]))
700
self.assertEqual(set(['a', 'b']),
701
osutils.minimum_path_selection(['a', 'b']))
702
self.assertEqual(set(['a/', 'b']),
703
osutils.minimum_path_selection(['a/', 'b']))
704
self.assertEqual(set(['a/', 'b']),
705
osutils.minimum_path_selection(['a/c', 'a/', 'b']))
707
def test_mkdtemp(self):
708
tmpdir = osutils._win32_mkdtemp(dir='.')
709
self.assertFalse('\\' in tmpdir)
711
def test_rename(self):
719
osutils._win32_rename('b', 'a')
720
self.failUnlessExists('a')
721
self.failIfExists('b')
722
self.assertFileEqual('baz\n', 'a')
724
def test_rename_missing_file(self):
730
osutils._win32_rename('b', 'a')
731
except (IOError, OSError), e:
732
self.assertEqual(errno.ENOENT, e.errno)
733
self.assertFileEqual('foo\n', 'a')
735
def test_rename_missing_dir(self):
738
osutils._win32_rename('b', 'a')
739
except (IOError, OSError), e:
740
self.assertEqual(errno.ENOENT, e.errno)
742
def test_rename_current_dir(self):
745
# You can't rename the working directory
746
# doing rename non-existant . usually
747
# just raises ENOENT, since non-existant
750
osutils._win32_rename('b', '.')
751
except (IOError, OSError), e:
752
self.assertEqual(errno.ENOENT, e.errno)
754
def test_splitpath(self):
755
def check(expected, path):
756
self.assertEqual(expected, osutils.splitpath(path))
759
check(['a', 'b'], 'a/b')
760
check(['a', 'b'], 'a/./b')
761
check(['a', '.b'], 'a/.b')
762
check(['a', '.b'], 'a\\.b')
764
self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
767
class TestMacFuncsDirs(tests.TestCaseInTempDir):
768
"""Test mac special functions that require directories."""
770
def test_getcwd(self):
771
self.requireFeature(tests.UnicodeFilenameFeature)
772
os.mkdir(u'B\xe5gfors')
773
os.chdir(u'B\xe5gfors')
774
self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
776
def test_getcwd_nonnorm(self):
777
self.requireFeature(tests.UnicodeFilenameFeature)
778
# Test that _mac_getcwd() will normalize this path
779
os.mkdir(u'Ba\u030agfors')
780
os.chdir(u'Ba\u030agfors')
781
self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
784
class TestChunksToLines(tests.TestCase):
786
def test_smoketest(self):
787
self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
788
osutils.chunks_to_lines(['foo\nbar', '\nbaz\n']))
789
self.assertEqual(['foo\n', 'bar\n', 'baz\n'],
790
osutils.chunks_to_lines(['foo\n', 'bar\n', 'baz\n']))
792
def test_osutils_binding(self):
793
from bzrlib.tests import test__chunks_to_lines
794
if test__chunks_to_lines.CompiledChunksToLinesFeature.available():
795
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
797
from bzrlib._chunks_to_lines_py import chunks_to_lines
798
self.assertIs(chunks_to_lines, osutils.chunks_to_lines)
801
class TestSplitLines(tests.TestCase):
803
def test_split_unicode(self):
804
self.assertEqual([u'foo\n', u'bar\xae'],
805
osutils.split_lines(u'foo\nbar\xae'))
806
self.assertEqual([u'foo\n', u'bar\xae\n'],
807
osutils.split_lines(u'foo\nbar\xae\n'))
809
def test_split_with_carriage_returns(self):
810
self.assertEqual(['foo\rbar\n'],
811
osutils.split_lines('foo\rbar\n'))
814
class TestWalkDirs(tests.TestCaseInTempDir):
816
def test_walkdirs(self):
825
self.build_tree(tree)
826
expected_dirblocks = [
828
[('0file', '0file', 'file'),
829
('1dir', '1dir', 'directory'),
830
('2file', '2file', 'file'),
834
[('1dir/0file', '0file', 'file'),
835
('1dir/1dir', '1dir', 'directory'),
838
(('1dir/1dir', './1dir/1dir'),
845
for dirdetail, dirblock in osutils.walkdirs('.'):
846
if len(dirblock) and dirblock[0][1] == '.bzr':
847
# this tests the filtering of selected paths
850
result.append((dirdetail, dirblock))
852
self.assertTrue(found_bzrdir)
853
self.assertEqual(expected_dirblocks,
854
[(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
855
# you can search a subdir only, with a supplied prefix.
857
for dirblock in osutils.walkdirs('./1dir', '1dir'):
858
result.append(dirblock)
859
self.assertEqual(expected_dirblocks[1:],
860
[(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
862
def test_walkdirs_os_error(self):
863
# <https://bugs.edge.launchpad.net/bzr/+bug/338653>
864
# Pyrex readdir didn't raise useful messages if it had an error
865
# reading the directory
866
if sys.platform == 'win32':
867
raise tests.TestNotApplicable(
868
"readdir IOError not tested on win32")
869
os.mkdir("test-unreadable")
870
os.chmod("test-unreadable", 0000)
871
# must chmod it back so that it can be removed
872
self.addCleanup(lambda: os.chmod("test-unreadable", 0700))
873
# The error is not raised until the generator is actually evaluated.
874
# (It would be ok if it happened earlier but at the moment it
876
e = self.assertRaises(OSError, list, osutils._walkdirs_utf8("."))
877
self.assertEquals('./test-unreadable', e.filename)
878
self.assertEquals(errno.EACCES, e.errno)
879
# Ensure the message contains the file name
880
self.assertContainsRe(str(e), "\./test-unreadable")
882
def test__walkdirs_utf8(self):
891
self.build_tree(tree)
892
expected_dirblocks = [
894
[('0file', '0file', 'file'),
895
('1dir', '1dir', 'directory'),
896
('2file', '2file', 'file'),
900
[('1dir/0file', '0file', 'file'),
901
('1dir/1dir', '1dir', 'directory'),
904
(('1dir/1dir', './1dir/1dir'),
911
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
912
if len(dirblock) and dirblock[0][1] == '.bzr':
913
# this tests the filtering of selected paths
916
result.append((dirdetail, dirblock))
918
self.assertTrue(found_bzrdir)
919
self.assertEqual(expected_dirblocks,
920
[(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
921
# you can search a subdir only, with a supplied prefix.
923
for dirblock in osutils.walkdirs('./1dir', '1dir'):
924
result.append(dirblock)
925
self.assertEqual(expected_dirblocks[1:],
926
[(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
928
def _filter_out_stat(self, result):
929
"""Filter out the stat value from the walkdirs result"""
930
for dirdetail, dirblock in result:
932
for info in dirblock:
933
# Ignore info[3] which is the stat
934
new_dirblock.append((info[0], info[1], info[2], info[4]))
935
dirblock[:] = new_dirblock
937
def _save_platform_info(self):
938
cur_winver = win32utils.winver
939
cur_fs_enc = osutils._fs_enc
940
cur_dir_reader = osutils._selected_dir_reader
942
win32utils.winver = cur_winver
943
osutils._fs_enc = cur_fs_enc
944
osutils._selected_dir_reader = cur_dir_reader
945
self.addCleanup(restore)
947
def assertReadFSDirIs(self, expected):
948
"""Assert the right implementation for _walkdirs_utf8 is chosen."""
949
# Force it to redetect
950
osutils._selected_dir_reader = None
951
# Nothing to list, but should still trigger the selection logic
952
self.assertEqual([(('', '.'), [])], list(osutils._walkdirs_utf8('.')))
953
self.assertIsInstance(osutils._selected_dir_reader, expected)
955
def test_force_walkdirs_utf8_fs_utf8(self):
956
self.requireFeature(UTF8DirReaderFeature)
957
self._save_platform_info()
958
win32utils.winver = None # Avoid the win32 detection code
959
osutils._fs_enc = 'UTF-8'
960
self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
962
def test_force_walkdirs_utf8_fs_ascii(self):
963
self.requireFeature(UTF8DirReaderFeature)
964
self._save_platform_info()
965
win32utils.winver = None # Avoid the win32 detection code
966
osutils._fs_enc = 'US-ASCII'
967
self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
969
def test_force_walkdirs_utf8_fs_ANSI(self):
970
self.requireFeature(UTF8DirReaderFeature)
971
self._save_platform_info()
972
win32utils.winver = None # Avoid the win32 detection code
973
osutils._fs_enc = 'ANSI_X3.4-1968'
974
self.assertReadFSDirIs(UTF8DirReaderFeature.reader)
976
def test_force_walkdirs_utf8_fs_latin1(self):
977
self._save_platform_info()
978
win32utils.winver = None # Avoid the win32 detection code
979
osutils._fs_enc = 'latin1'
980
self.assertReadFSDirIs(osutils.UnicodeDirReader)
982
def test_force_walkdirs_utf8_nt(self):
983
# Disabled because the thunk of the whole walkdirs api is disabled.
984
self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
985
self._save_platform_info()
986
win32utils.winver = 'Windows NT'
987
from bzrlib._walkdirs_win32 import Win32ReadDir
988
self.assertReadFSDirIs(Win32ReadDir)
990
def test_force_walkdirs_utf8_98(self):
991
self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
992
self._save_platform_info()
993
win32utils.winver = 'Windows 98'
994
self.assertReadFSDirIs(osutils.UnicodeDirReader)
996
def test_unicode_walkdirs(self):
997
"""Walkdirs should always return unicode paths."""
998
self.requireFeature(tests.UnicodeFilenameFeature)
999
name0 = u'0file-\xb6'
1000
name1 = u'1dir-\u062c\u0648'
1001
name2 = u'2file-\u0633'
1005
name1 + '/' + name0,
1006
name1 + '/' + name1 + '/',
1009
self.build_tree(tree)
1010
expected_dirblocks = [
1012
[(name0, name0, 'file', './' + name0),
1013
(name1, name1, 'directory', './' + name1),
1014
(name2, name2, 'file', './' + name2),
1017
((name1, './' + name1),
1018
[(name1 + '/' + name0, name0, 'file', './' + name1
1020
(name1 + '/' + name1, name1, 'directory', './' + name1
1024
((name1 + '/' + name1, './' + name1 + '/' + name1),
1029
result = list(osutils.walkdirs('.'))
1030
self._filter_out_stat(result)
1031
self.assertEqual(expected_dirblocks, result)
1032
result = list(osutils.walkdirs(u'./'+name1, name1))
1033
self._filter_out_stat(result)
1034
self.assertEqual(expected_dirblocks[1:], result)
1036
def test_unicode__walkdirs_utf8(self):
1037
"""Walkdirs_utf8 should always return utf8 paths.
1039
The abspath portion might be in unicode or utf-8
1041
self.requireFeature(tests.UnicodeFilenameFeature)
1042
name0 = u'0file-\xb6'
1043
name1 = u'1dir-\u062c\u0648'
1044
name2 = u'2file-\u0633'
1048
name1 + '/' + name0,
1049
name1 + '/' + name1 + '/',
1052
self.build_tree(tree)
1053
name0 = name0.encode('utf8')
1054
name1 = name1.encode('utf8')
1055
name2 = name2.encode('utf8')
1057
expected_dirblocks = [
1059
[(name0, name0, 'file', './' + name0),
1060
(name1, name1, 'directory', './' + name1),
1061
(name2, name2, 'file', './' + name2),
1064
((name1, './' + name1),
1065
[(name1 + '/' + name0, name0, 'file', './' + name1
1067
(name1 + '/' + name1, name1, 'directory', './' + name1
1071
((name1 + '/' + name1, './' + name1 + '/' + name1),
1077
# For ease in testing, if walkdirs_utf8 returns Unicode, assert that
1078
# all abspaths are Unicode, and encode them back into utf8.
1079
for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
1080
self.assertIsInstance(dirdetail[0], str)
1081
if isinstance(dirdetail[1], unicode):
1082
dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
1083
dirblock = [list(info) for info in dirblock]
1084
for info in dirblock:
1085
self.assertIsInstance(info[4], unicode)
1086
info[4] = info[4].encode('utf8')
1088
for info in dirblock:
1089
self.assertIsInstance(info[0], str)
1090
self.assertIsInstance(info[1], str)
1091
self.assertIsInstance(info[4], str)
1092
# Remove the stat information
1093
new_dirblock.append((info[0], info[1], info[2], info[4]))
1094
result.append((dirdetail, new_dirblock))
1095
self.assertEqual(expected_dirblocks, result)
1097
def test__walkdirs_utf8_with_unicode_fs(self):
1098
"""UnicodeDirReader should be a safe fallback everywhere
1100
The abspath portion should be in unicode
1102
self.requireFeature(tests.UnicodeFilenameFeature)
1103
# Use the unicode reader. TODO: split into driver-and-driven unit
1105
self._save_platform_info()
1106
osutils._selected_dir_reader = osutils.UnicodeDirReader()
1107
name0u = u'0file-\xb6'
1108
name1u = u'1dir-\u062c\u0648'
1109
name2u = u'2file-\u0633'
1113
name1u + '/' + name0u,
1114
name1u + '/' + name1u + '/',
1117
self.build_tree(tree)
1118
name0 = name0u.encode('utf8')
1119
name1 = name1u.encode('utf8')
1120
name2 = name2u.encode('utf8')
1122
# All of the abspaths should be in unicode, all of the relative paths
1124
expected_dirblocks = [
1126
[(name0, name0, 'file', './' + name0u),
1127
(name1, name1, 'directory', './' + name1u),
1128
(name2, name2, 'file', './' + name2u),
1131
((name1, './' + name1u),
1132
[(name1 + '/' + name0, name0, 'file', './' + name1u
1134
(name1 + '/' + name1, name1, 'directory', './' + name1u
1138
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1143
result = list(osutils._walkdirs_utf8('.'))
1144
self._filter_out_stat(result)
1145
self.assertEqual(expected_dirblocks, result)
1147
def test__walkdirs_utf8_win32readdir(self):
1148
self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1149
self.requireFeature(tests.UnicodeFilenameFeature)
1150
from bzrlib._walkdirs_win32 import Win32ReadDir
1151
self._save_platform_info()
1152
osutils._selected_dir_reader = Win32ReadDir()
1153
name0u = u'0file-\xb6'
1154
name1u = u'1dir-\u062c\u0648'
1155
name2u = u'2file-\u0633'
1159
name1u + '/' + name0u,
1160
name1u + '/' + name1u + '/',
1163
self.build_tree(tree)
1164
name0 = name0u.encode('utf8')
1165
name1 = name1u.encode('utf8')
1166
name2 = name2u.encode('utf8')
1168
# All of the abspaths should be in unicode, all of the relative paths
1170
expected_dirblocks = [
1172
[(name0, name0, 'file', './' + name0u),
1173
(name1, name1, 'directory', './' + name1u),
1174
(name2, name2, 'file', './' + name2u),
1177
((name1, './' + name1u),
1178
[(name1 + '/' + name0, name0, 'file', './' + name1u
1180
(name1 + '/' + name1, name1, 'directory', './' + name1u
1184
((name1 + '/' + name1, './' + name1u + '/' + name1u),
1189
result = list(osutils._walkdirs_utf8(u'.'))
1190
self._filter_out_stat(result)
1191
self.assertEqual(expected_dirblocks, result)
1193
def assertStatIsCorrect(self, path, win32stat):
1194
os_stat = os.stat(path)
1195
self.assertEqual(os_stat.st_size, win32stat.st_size)
1196
self.assertAlmostEqual(os_stat.st_mtime, win32stat.st_mtime, places=4)
1197
self.assertAlmostEqual(os_stat.st_ctime, win32stat.st_ctime, places=4)
1198
self.assertAlmostEqual(os_stat.st_atime, win32stat.st_atime, places=4)
1199
self.assertEqual(os_stat.st_dev, win32stat.st_dev)
1200
self.assertEqual(os_stat.st_ino, win32stat.st_ino)
1201
self.assertEqual(os_stat.st_mode, win32stat.st_mode)
1203
def test__walkdirs_utf_win32_find_file_stat_file(self):
1204
"""make sure our Stat values are valid"""
1205
self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1206
self.requireFeature(tests.UnicodeFilenameFeature)
1207
from bzrlib._walkdirs_win32 import Win32ReadDir
1208
name0u = u'0file-\xb6'
1209
name0 = name0u.encode('utf8')
1210
self.build_tree([name0u])
1211
# I hate to sleep() here, but I'm trying to make the ctime different
1214
f = open(name0u, 'ab')
1216
f.write('just a small update')
1220
result = Win32ReadDir().read_dir('', u'.')
1222
self.assertEqual((name0, name0, 'file'), entry[:3])
1223
self.assertEqual(u'./' + name0u, entry[4])
1224
self.assertStatIsCorrect(entry[4], entry[3])
1225
self.assertNotEqual(entry[3].st_mtime, entry[3].st_ctime)
1227
def test__walkdirs_utf_win32_find_file_stat_directory(self):
1228
"""make sure our Stat values are valid"""
1229
self.requireFeature(test__walkdirs_win32.Win32ReadDirFeature)
1230
self.requireFeature(tests.UnicodeFilenameFeature)
1231
from bzrlib._walkdirs_win32 import Win32ReadDir
1232
name0u = u'0dir-\u062c\u0648'
1233
name0 = name0u.encode('utf8')
1234
self.build_tree([name0u + '/'])
1236
result = Win32ReadDir().read_dir('', u'.')
1238
self.assertEqual((name0, name0, 'directory'), entry[:3])
1239
self.assertEqual(u'./' + name0u, entry[4])
1240
self.assertStatIsCorrect(entry[4], entry[3])
1242
def assertPathCompare(self, path_less, path_greater):
1243
"""check that path_less and path_greater compare correctly."""
1244
self.assertEqual(0, osutils.compare_paths_prefix_order(
1245
path_less, path_less))
1246
self.assertEqual(0, osutils.compare_paths_prefix_order(
1247
path_greater, path_greater))
1248
self.assertEqual(-1, osutils.compare_paths_prefix_order(
1249
path_less, path_greater))
1250
self.assertEqual(1, osutils.compare_paths_prefix_order(
1251
path_greater, path_less))
1253
def test_compare_paths_prefix_order(self):
1254
# root before all else
1255
self.assertPathCompare("/", "/a")
1256
# alpha within a dir
1257
self.assertPathCompare("/a", "/b")
1258
self.assertPathCompare("/b", "/z")
1259
# high dirs before lower.
1260
self.assertPathCompare("/z", "/a/a")
1261
# except if the deeper dir should be output first
1262
self.assertPathCompare("/a/b/c", "/d/g")
1263
# lexical betwen dirs of the same height
1264
self.assertPathCompare("/a/z", "/z/z")
1265
self.assertPathCompare("/a/c/z", "/a/d/e")
1267
# this should also be consistent for no leading / paths
1268
# root before all else
1269
self.assertPathCompare("", "a")
1270
# alpha within a dir
1271
self.assertPathCompare("a", "b")
1272
self.assertPathCompare("b", "z")
1273
# high dirs before lower.
1274
self.assertPathCompare("z", "a/a")
1275
# except if the deeper dir should be output first
1276
self.assertPathCompare("a/b/c", "d/g")
1277
# lexical betwen dirs of the same height
1278
self.assertPathCompare("a/z", "z/z")
1279
self.assertPathCompare("a/c/z", "a/d/e")
1281
def test_path_prefix_sorting(self):
1282
"""Doing a sort on path prefix should match our sample data."""
1297
dir_sorted_paths = [
1313
sorted(original_paths, key=osutils.path_prefix_key))
1314
# using the comparison routine shoudl work too:
1317
sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1320
class TestCopyTree(tests.TestCaseInTempDir):
1322
def test_copy_basic_tree(self):
1323
self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1324
osutils.copy_tree('source', 'target')
1325
self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1326
self.assertEqual(['c'], os.listdir('target/b'))
1328
def test_copy_tree_target_exists(self):
1329
self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
1331
osutils.copy_tree('source', 'target')
1332
self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1333
self.assertEqual(['c'], os.listdir('target/b'))
1335
def test_copy_tree_symlinks(self):
1336
self.requireFeature(tests.SymlinkFeature)
1337
self.build_tree(['source/'])
1338
os.symlink('a/generic/path', 'source/lnk')
1339
osutils.copy_tree('source', 'target')
1340
self.assertEqual(['lnk'], os.listdir('target'))
1341
self.assertEqual('a/generic/path', os.readlink('target/lnk'))
1343
def test_copy_tree_handlers(self):
1344
processed_files = []
1345
processed_links = []
1346
def file_handler(from_path, to_path):
1347
processed_files.append(('f', from_path, to_path))
1348
def dir_handler(from_path, to_path):
1349
processed_files.append(('d', from_path, to_path))
1350
def link_handler(from_path, to_path):
1351
processed_links.append((from_path, to_path))
1352
handlers = {'file':file_handler,
1353
'directory':dir_handler,
1354
'symlink':link_handler,
1357
self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
1358
if osutils.has_symlinks():
1359
os.symlink('a/generic/path', 'source/lnk')
1360
osutils.copy_tree('source', 'target', handlers=handlers)
1362
self.assertEqual([('d', 'source', 'target'),
1363
('f', 'source/a', 'target/a'),
1364
('d', 'source/b', 'target/b'),
1365
('f', 'source/b/c', 'target/b/c'),
1367
self.failIfExists('target')
1368
if osutils.has_symlinks():
1369
self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
1372
class TestSetUnsetEnv(tests.TestCase):
1373
"""Test updating the environment"""
1376
super(TestSetUnsetEnv, self).setUp()
1378
self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
1379
'Environment was not cleaned up properly.'
1380
' Variable BZR_TEST_ENV_VAR should not exist.')
1382
if 'BZR_TEST_ENV_VAR' in os.environ:
1383
del os.environ['BZR_TEST_ENV_VAR']
1385
self.addCleanup(cleanup)
1388
"""Test that we can set an env variable"""
1389
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1390
self.assertEqual(None, old)
1391
self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
1393
def test_double_set(self):
1394
"""Test that we get the old value out"""
1395
osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1396
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
1397
self.assertEqual('foo', old)
1398
self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
1400
def test_unicode(self):
1401
"""Environment can only contain plain strings
1403
So Unicode strings must be encoded.
1405
uni_val, env_val = tests.probe_unicode_in_user_encoding()
1407
raise tests.TestSkipped(
1408
'Cannot find a unicode character that works in encoding %s'
1409
% (osutils.get_user_encoding(),))
1411
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
1412
self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
1414
def test_unset(self):
1415
"""Test that passing None will remove the env var"""
1416
osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
1417
old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
1418
self.assertEqual('foo', old)
1419
self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
1420
self.failIf('BZR_TEST_ENV_VAR' in os.environ)
1423
class TestLocalTimeOffset(tests.TestCase):
1425
def test_local_time_offset(self):
1426
"""Test that local_time_offset() returns a sane value."""
1427
offset = osutils.local_time_offset()
1428
self.assertTrue(isinstance(offset, int))
1429
# Test that the offset is no more than a eighteen hours in
1431
# Time zone handling is system specific, so it is difficult to
1432
# do more specific tests, but a value outside of this range is
1434
eighteen_hours = 18 * 3600
1435
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
1437
def test_local_time_offset_with_timestamp(self):
1438
"""Test that local_time_offset() works with a timestamp."""
1439
offset = osutils.local_time_offset(1000000000.1234567)
1440
self.assertTrue(isinstance(offset, int))
1441
eighteen_hours = 18 * 3600
1442
self.assertTrue(-eighteen_hours < offset < eighteen_hours)
1445
class TestSizeShaFile(tests.TestCaseInTempDir):
1447
def test_sha_empty(self):
1448
self.build_tree_contents([('foo', '')])
1449
expected_sha = osutils.sha_string('')
1451
self.addCleanup(f.close)
1452
size, sha = osutils.size_sha_file(f)
1453
self.assertEqual(0, size)
1454
self.assertEqual(expected_sha, sha)
1456
def test_sha_mixed_endings(self):
1457
text = 'test\r\nwith\nall\rpossible line endings\r\n'
1458
self.build_tree_contents([('foo', text)])
1459
expected_sha = osutils.sha_string(text)
1461
self.addCleanup(f.close)
1462
size, sha = osutils.size_sha_file(f)
1463
self.assertEqual(38, size)
1464
self.assertEqual(expected_sha, sha)
1467
class TestShaFileByName(tests.TestCaseInTempDir):
1469
def test_sha_empty(self):
1470
self.build_tree_contents([('foo', '')])
1471
expected_sha = osutils.sha_string('')
1472
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1474
def test_sha_mixed_endings(self):
1475
text = 'test\r\nwith\nall\rpossible line endings\r\n'
1476
self.build_tree_contents([('foo', text)])
1477
expected_sha = osutils.sha_string(text)
1478
self.assertEqual(expected_sha, osutils.sha_file_by_name('foo'))
1481
class TestResourceLoading(tests.TestCaseInTempDir):
1483
def test_resource_string(self):
1484
# test resource in bzrlib
1485
text = osutils.resource_string('bzrlib', 'debug.py')
1486
self.assertContainsRe(text, "debug_flags = set()")
1487
# test resource under bzrlib
1488
text = osutils.resource_string('bzrlib.ui', 'text.py')
1489
self.assertContainsRe(text, "class TextUIFactory")
1490
# test unsupported package
1491
self.assertRaises(errors.BzrError, osutils.resource_string, 'zzzz',
1493
# test unknown resource
1494
self.assertRaises(IOError, osutils.resource_string, 'bzrlib', 'yyy.xx')
1497
class TestReCompile(tests.TestCase):
1499
def test_re_compile_checked(self):
1500
r = osutils.re_compile_checked(r'A*', re.IGNORECASE)
1501
self.assertTrue(r.match('aaaa'))
1502
self.assertTrue(r.match('aAaA'))
1504
def test_re_compile_checked_error(self):
1505
# like https://bugs.launchpad.net/bzr/+bug/251352
1506
err = self.assertRaises(
1507
errors.BzrCommandError,
1508
osutils.re_compile_checked, '*', re.IGNORECASE, 'test case')
1510
"Invalid regular expression in test case: '*': "
1511
"nothing to repeat",