/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
1
# Copyright (C) 2005, 2006 Canonical Ltd
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
2
#
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.
7
#
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.
12
#
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
17
"""Tests for the osutils wrapper."""
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
18
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
19
import errno
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
20
import os
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
21
import socket
22
import stat
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
23
import sys
24
25
import bzrlib
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
26
from bzrlib import (
27
    errors,
28
    osutils,
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
29
    win32utils,
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
30
    )
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
31
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
32
from bzrlib.tests import (
33
        StringIOWrapper,
34
        TestCase, 
35
        TestCaseInTempDir, 
36
        TestSkipped,
37
        )
1532 by Robert Collins
Merge in John Meinels integration branch.
38
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
39
40
class TestOSUtils(TestCaseInTempDir):
41
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
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
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
56
    def test_fancy_rename(self):
57
        # This should work everywhere
58
        def rename(a, b):
59
            osutils.fancy_rename(a, b,
60
                    rename_func=os.rename,
61
                    unlink_func=os.unlink)
62
63
        open('a', 'wb').write('something in a\n')
64
        rename('a', 'b')
65
        self.failIfExists('a')
66
        self.failUnlessExists('b')
67
        self.check_file_contents('b', 'something in a\n')
68
69
        open('a', 'wb').write('new something in a\n')
70
        rename('b', 'a')
71
72
        self.check_file_contents('a', 'something in a\n')
73
74
    def test_rename(self):
75
        # Rename should be semi-atomic on all platforms
76
        open('a', 'wb').write('something in a\n')
77
        osutils.rename('a', 'b')
78
        self.failIfExists('a')
79
        self.failUnlessExists('b')
80
        self.check_file_contents('b', 'something in a\n')
81
82
        open('a', 'wb').write('new something in a\n')
83
        osutils.rename('b', 'a')
84
85
        self.check_file_contents('a', 'something in a\n')
86
87
    # TODO: test fancy_rename using a MemoryTransport
88
1553.5.5 by Martin Pool
New utility routine rand_chars
89
    def test_01_rand_chars_empty(self):
90
        result = osutils.rand_chars(0)
91
        self.assertEqual(result, '')
92
93
    def test_02_rand_chars_100(self):
94
        result = osutils.rand_chars(100)
95
        self.assertEqual(len(result), 100)
96
        self.assertEqual(type(result), str)
97
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
98
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
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'))
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
107
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
108
    def test_rmtree(self):
109
        # Check to remove tree with read-only files/dirs
110
        os.mkdir('dir')
111
        f = file('dir/file', 'w')
112
        f.write('spam')
113
        f.close()
114
        # would like to also try making the directory readonly, but at the
115
        # moment python shutil.rmtree doesn't handle that properly - it would
116
        # need to chmod the directory before removing things inside it - deferred
117
        # for now -- mbp 20060505
118
        # osutils.make_readonly('dir')
119
        osutils.make_readonly('dir/file')
120
121
        osutils.rmtree('dir')
122
123
        self.failIfExists('dir/file')
124
        self.failIfExists('dir')
125
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
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'))
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
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')
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
159
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
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
1957.1.15 by John Arbash Meinel
Review feedback from Robert
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
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
184
    def test_format_delta(self):
1957.1.15 by John Arbash Meinel
Review feedback from Robert
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)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
208
209
        # We handle when time steps the wrong direction because computers
210
        # don't have synchronized clocks.
1957.1.15 by John Arbash Meinel
Review feedback from Robert
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)
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
214
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
215
    def test_dereference_path(self):
2091.3.6 by Aaron Bentley
Add symlink test guards
216
        if not osutils.has_symlinks():
217
            raise TestSkipped('Symlinks are not supported on this platform')
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
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')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
229
        self.assertEqual(foo_path, osutils.dereference_path('./foo'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
230
231
        # Dereferences parent symlinks
232
        os.mkdir('bar/baz')
233
        baz_path = osutils.pathjoin(bar_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
234
        self.assertEqual(baz_path, osutils.dereference_path('./foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
235
236
        # Dereferences parent symlinks that are the first path element
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
237
        self.assertEqual(baz_path, osutils.dereference_path('foo/baz'))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
238
239
        # Dereferences parent symlinks in absolute paths
240
        foo_baz_path = osutils.pathjoin(foo_path, 'baz')
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
241
        self.assertEqual(baz_path, osutils.dereference_path(foo_baz_path))
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
242
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
243
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
244
    def test_kind_marker(self):
245
        self.assertEqual("", osutils.kind_marker("file"))
246
        self.assertEqual("/", osutils.kind_marker(osutils._directory_kind))
247
        self.assertEqual("@", osutils.kind_marker("symlink"))
248
        self.assertRaises(errors.BzrError, osutils.kind_marker, "unknown")
249
250
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
251
class TestSafeUnicode(TestCase):
252
253
    def test_from_ascii_string(self):
254
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
255
1534.3.2 by Robert Collins
An extra test for John.
256
    def test_from_unicode_string_ascii_contents(self):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
257
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
258
1534.3.2 by Robert Collins
An extra test for John.
259
    def test_from_unicode_string_unicode_contents(self):
260
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
261
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
262
    def test_from_utf8_string(self):
263
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
264
265
    def test_bad_utf8_string(self):
1185.65.29 by Robert Collins
Implement final review suggestions.
266
        self.assertRaises(BzrBadParameterNotUnicode,
267
                          osutils.safe_unicode,
268
                          '\xbb\xbb')
1666.1.6 by Robert Collins
Make knit the default format.
269
270
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
271
class TestSafeUtf8(TestCase):
272
273
    def test_from_ascii_string(self):
274
        f = 'foobar'
275
        self.assertEqual('foobar', osutils.safe_utf8(f))
276
277
    def test_from_unicode_string_ascii_contents(self):
278
        self.assertEqual('bargam', osutils.safe_utf8(u'bargam'))
279
280
    def test_from_unicode_string_unicode_contents(self):
281
        self.assertEqual('bargam\xc2\xae', osutils.safe_utf8(u'bargam\xae'))
282
283
    def test_from_utf8_string(self):
284
        self.assertEqual('foo\xc2\xae', osutils.safe_utf8('foo\xc2\xae'))
285
286
    def test_bad_utf8_string(self):
287
        self.assertRaises(BzrBadParameterNotUnicode,
288
                          osutils.safe_utf8, '\xbb\xbb')
289
290
291
class TestSafeRevisionId(TestCase):
292
293
    def test_from_ascii_string(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
294
        self.assertEqual('foobar', osutils.safe_revision_id('foobar'))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
295
296
    def test_from_unicode_string_ascii_contents(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
297
        self.assertEqual('bargam',
298
                         osutils.safe_revision_id(u'bargam', warn=False))
299
300
    def test_from_unicode_deprecated(self):
301
        self.assertEqual('bargam',
302
            self.callDeprecated([osutils._revision_id_warning],
303
                                osutils.safe_revision_id, u'bargam'))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
304
305
    def test_from_unicode_string_unicode_contents(self):
306
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
307
                         osutils.safe_revision_id(u'bargam\xae', warn=False))
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
308
309
    def test_from_utf8_string(self):
310
        self.assertEqual('foo\xc2\xae',
311
                         osutils.safe_revision_id('foo\xc2\xae'))
312
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
313
    def test_none(self):
314
        """Currently, None is a valid revision_id"""
315
        self.assertEqual(None, osutils.safe_revision_id(None))
316
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
317
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
318
class TestSafeFileId(TestCase):
319
320
    def test_from_ascii_string(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
321
        self.assertEqual('foobar', osutils.safe_file_id('foobar'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
322
323
    def test_from_unicode_string_ascii_contents(self):
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
324
        self.assertEqual('bargam', osutils.safe_file_id(u'bargam', warn=False))
325
326
    def test_from_unicode_deprecated(self):
327
        self.assertEqual('bargam',
328
            self.callDeprecated([osutils._file_id_warning],
329
                                osutils.safe_file_id, u'bargam'))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
330
331
    def test_from_unicode_string_unicode_contents(self):
332
        self.assertEqual('bargam\xc2\xae',
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
333
                         osutils.safe_file_id(u'bargam\xae', warn=False))
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
334
335
    def test_from_utf8_string(self):
336
        self.assertEqual('foo\xc2\xae',
337
                         osutils.safe_file_id('foo\xc2\xae'))
338
339
    def test_none(self):
340
        """Currently, None is a valid revision_id"""
341
        self.assertEqual(None, osutils.safe_file_id(None))
342
343
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
344
class TestWin32Funcs(TestCase):
345
    """Test that the _win32 versions of os utilities return appropriate paths."""
346
347
    def test_abspath(self):
348
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
349
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
350
        self.assertEqual('//HOST/path', osutils._win32_abspath(r'\\HOST\path'))
351
        self.assertEqual('//HOST/path', osutils._win32_abspath('//HOST/path'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
352
353
    def test_realpath(self):
354
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
355
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
356
357
    def test_pathjoin(self):
358
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
359
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
360
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
361
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
362
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
363
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
364
365
    def test_normpath(self):
366
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
367
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
368
369
    def test_getcwd(self):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
370
        cwd = osutils._win32_getcwd()
371
        os_cwd = os.getcwdu()
372
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
373
        # win32 is inconsistent whether it returns lower or upper case
374
        # and even if it was consistent the user might type the other
375
        # so we force it to uppercase
376
        # running python.exe under cmd.exe return capital C:\\
377
        # running win32 python inside a cygwin shell returns lowercase
378
        self.assertEqual(os_cwd[0].upper(), cwd[0])
379
380
    def test_fixdrive(self):
381
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
382
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
383
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
384
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
385
    def test_win98_abspath(self):
386
        # absolute path
387
        self.assertEqual('C:/foo', osutils._win98_abspath('C:\\foo'))
388
        self.assertEqual('C:/foo', osutils._win98_abspath('C:/foo'))
389
        # UNC path
390
        self.assertEqual('//HOST/path', osutils._win98_abspath(r'\\HOST\path'))
391
        self.assertEqual('//HOST/path', osutils._win98_abspath('//HOST/path'))
392
        # relative path
393
        cwd = osutils.getcwd().rstrip('/')
394
        drive = osutils._nt_splitdrive(cwd)[0]
395
        self.assertEqual(cwd+'/path', osutils._win98_abspath('path'))
396
        self.assertEqual(drive+'/path', osutils._win98_abspath('/path'))
397
        # unicode path
398
        u = u'\u1234'
399
        self.assertEqual(cwd+'/'+u, osutils._win98_abspath(u))
400
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
401
402
class TestWin32FuncsDirs(TestCaseInTempDir):
403
    """Test win32 functions that create files."""
404
    
405
    def test_getcwd(self):
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
406
        if win32utils.winver == 'Windows 98':
407
            raise TestSkipped('Windows 98 cannot handle unicode filenames')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
408
        # Make sure getcwd can handle unicode filenames
409
        try:
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
410
            os.mkdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
411
        except UnicodeError:
412
            raise TestSkipped("Unable to create Unicode filename")
413
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
414
        os.chdir(u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
415
        # TODO: jam 20060427 This will probably fail on Mac OSX because
416
        #       it will change the normalization of B\xe5gfors
417
        #       Consider using a different unicode character, or make
418
        #       osutils.getcwd() renormalize the path.
1830.3.9 by John Arbash Meinel
Use a directory name that doesn't get messed up on Mac for getcwd() test.
419
        self.assertEndsWith(osutils._win32_getcwd(), u'mu-\xb5')
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
420
421
    def test_mkdtemp(self):
422
        tmpdir = osutils._win32_mkdtemp(dir='.')
423
        self.assertFalse('\\' in tmpdir)
424
425
    def test_rename(self):
426
        a = open('a', 'wb')
427
        a.write('foo\n')
428
        a.close()
429
        b = open('b', 'wb')
430
        b.write('baz\n')
431
        b.close()
432
433
        osutils._win32_rename('b', 'a')
434
        self.failUnlessExists('a')
435
        self.failIfExists('b')
436
        self.assertFileEqual('baz\n', 'a')
437
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
438
    def test_rename_missing_file(self):
439
        a = open('a', 'wb')
440
        a.write('foo\n')
441
        a.close()
442
443
        try:
444
            osutils._win32_rename('b', 'a')
445
        except (IOError, OSError), e:
446
            self.assertEqual(errno.ENOENT, e.errno)
447
        self.assertFileEqual('foo\n', 'a')
448
449
    def test_rename_missing_dir(self):
450
        os.mkdir('a')
451
        try:
452
            osutils._win32_rename('b', 'a')
453
        except (IOError, OSError), e:
454
            self.assertEqual(errno.ENOENT, e.errno)
455
456
    def test_rename_current_dir(self):
457
        os.mkdir('a')
458
        os.chdir('a')
459
        # You can't rename the working directory
460
        # doing rename non-existant . usually
461
        # just raises ENOENT, since non-existant
462
        # doesn't exist.
463
        try:
464
            osutils._win32_rename('b', '.')
465
        except (IOError, OSError), e:
466
            self.assertEqual(errno.ENOENT, e.errno)
467
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
468
    def test_splitpath(self):
469
        def check(expected, path):
470
            self.assertEqual(expected, osutils.splitpath(path))
471
472
        check(['a'], 'a')
473
        check(['a', 'b'], 'a/b')
474
        check(['a', 'b'], 'a/./b')
475
        check(['a', '.b'], 'a/.b')
476
        check(['a', '.b'], 'a\\.b')
477
478
        self.assertRaises(errors.BzrError, osutils.splitpath, 'a/../b')
479
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
480
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
481
class TestMacFuncsDirs(TestCaseInTempDir):
482
    """Test mac special functions that require directories."""
483
484
    def test_getcwd(self):
485
        # On Mac, this will actually create Ba\u030agfors
486
        # but chdir will still work, because it accepts both paths
487
        try:
488
            os.mkdir(u'B\xe5gfors')
489
        except UnicodeError:
490
            raise TestSkipped("Unable to create Unicode filename")
491
492
        os.chdir(u'B\xe5gfors')
493
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
494
495
    def test_getcwd_nonnorm(self):
496
        # Test that _mac_getcwd() will normalize this path
497
        try:
498
            os.mkdir(u'Ba\u030agfors')
499
        except UnicodeError:
500
            raise TestSkipped("Unable to create Unicode filename")
501
502
        os.chdir(u'Ba\u030agfors')
503
        self.assertEndsWith(osutils._mac_getcwd(), u'B\xe5gfors')
504
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
505
1666.1.6 by Robert Collins
Make knit the default format.
506
class TestSplitLines(TestCase):
507
508
    def test_split_unicode(self):
509
        self.assertEqual([u'foo\n', u'bar\xae'],
510
                         osutils.split_lines(u'foo\nbar\xae'))
511
        self.assertEqual([u'foo\n', u'bar\xae\n'],
512
                         osutils.split_lines(u'foo\nbar\xae\n'))
513
514
    def test_split_with_carriage_returns(self):
515
        self.assertEqual(['foo\rbar\n'],
516
                         osutils.split_lines('foo\rbar\n'))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
517
518
519
class TestWalkDirs(TestCaseInTempDir):
520
521
    def test_walkdirs(self):
522
        tree = [
523
            '.bzr',
524
            '0file',
525
            '1dir/',
526
            '1dir/0file',
527
            '1dir/1dir/',
528
            '2file'
529
            ]
530
        self.build_tree(tree)
531
        expected_dirblocks = [
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
532
                (('', '.'),
533
                 [('0file', '0file', 'file'),
534
                  ('1dir', '1dir', 'directory'),
535
                  ('2file', '2file', 'file'),
536
                 ]
537
                ),
538
                (('1dir', './1dir'),
539
                 [('1dir/0file', '0file', 'file'),
540
                  ('1dir/1dir', '1dir', 'directory'),
541
                 ]
542
                ),
543
                (('1dir/1dir', './1dir/1dir'),
544
                 [
545
                 ]
546
                ),
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
547
            ]
548
        result = []
549
        found_bzrdir = False
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
550
        for dirdetail, dirblock in osutils.walkdirs('.'):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
551
            if len(dirblock) and dirblock[0][1] == '.bzr':
552
                # this tests the filtering of selected paths
553
                found_bzrdir = True
554
                del dirblock[0]
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
555
            result.append((dirdetail, dirblock))
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
556
557
        self.assertTrue(found_bzrdir)
558
        self.assertEqual(expected_dirblocks,
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
559
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
560
        # you can search a subdir only, with a supplied prefix.
561
        result = []
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
562
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
563
            result.append(dirblock)
564
        self.assertEqual(expected_dirblocks[1:],
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
565
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
566
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
567
    def test__walkdirs_utf8(self):
568
        tree = [
569
            '.bzr',
570
            '0file',
571
            '1dir/',
572
            '1dir/0file',
573
            '1dir/1dir/',
574
            '2file'
575
            ]
576
        self.build_tree(tree)
577
        expected_dirblocks = [
578
                (('', '.'),
579
                 [('0file', '0file', 'file'),
580
                  ('1dir', '1dir', 'directory'),
581
                  ('2file', '2file', 'file'),
582
                 ]
583
                ),
584
                (('1dir', './1dir'),
585
                 [('1dir/0file', '0file', 'file'),
586
                  ('1dir/1dir', '1dir', 'directory'),
587
                 ]
588
                ),
589
                (('1dir/1dir', './1dir/1dir'),
590
                 [
591
                 ]
592
                ),
593
            ]
594
        result = []
595
        found_bzrdir = False
596
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
597
            if len(dirblock) and dirblock[0][1] == '.bzr':
598
                # this tests the filtering of selected paths
599
                found_bzrdir = True
600
                del dirblock[0]
601
            result.append((dirdetail, dirblock))
602
603
        self.assertTrue(found_bzrdir)
604
        self.assertEqual(expected_dirblocks,
605
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
606
        # you can search a subdir only, with a supplied prefix.
607
        result = []
608
        for dirblock in osutils.walkdirs('./1dir', '1dir'):
609
            result.append(dirblock)
610
        self.assertEqual(expected_dirblocks[1:],
611
            [(dirinfo, [line[0:3] for line in block]) for dirinfo, block in result])
612
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
613
    def _filter_out_stat(self, result):
614
        """Filter out the stat value from the walkdirs result"""
615
        for dirdetail, dirblock in result:
616
            new_dirblock = []
617
            for info in dirblock:
618
                # Ignore info[3] which is the stat
619
                new_dirblock.append((info[0], info[1], info[2], info[4]))
620
            dirblock[:] = new_dirblock
621
622
    def test_unicode_walkdirs(self):
623
        """Walkdirs should always return unicode paths."""
624
        name0 = u'0file-\xb6'
625
        name1 = u'1dir-\u062c\u0648'
626
        name2 = u'2file-\u0633'
627
        tree = [
628
            name0,
629
            name1 + '/',
630
            name1 + '/' + name0,
631
            name1 + '/' + name1 + '/',
632
            name2,
633
            ]
634
        try:
635
            self.build_tree(tree)
636
        except UnicodeError:
637
            raise TestSkipped('Could not represent Unicode chars'
638
                              ' in current encoding.')
639
        expected_dirblocks = [
640
                ((u'', u'.'),
641
                 [(name0, name0, 'file', './' + name0),
642
                  (name1, name1, 'directory', './' + name1),
643
                  (name2, name2, 'file', './' + name2),
644
                 ]
645
                ),
646
                ((name1, './' + name1),
647
                 [(name1 + '/' + name0, name0, 'file', './' + name1
648
                                                        + '/' + name0),
649
                  (name1 + '/' + name1, name1, 'directory', './' + name1
650
                                                            + '/' + name1),
651
                 ]
652
                ),
653
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
654
                 [
655
                 ]
656
                ),
657
            ]
658
        result = list(osutils.walkdirs('.'))
659
        self._filter_out_stat(result)
660
        self.assertEqual(expected_dirblocks, result)
661
        result = list(osutils.walkdirs(u'./'+name1, name1))
662
        self._filter_out_stat(result)
663
        self.assertEqual(expected_dirblocks[1:], result)
664
665
    def test_unicode__walkdirs_utf8(self):
666
        """Walkdirs_utf8 should always return utf8 paths.
667
668
        The abspath portion might be in unicode or utf-8
669
        """
670
        name0 = u'0file-\xb6'
671
        name1 = u'1dir-\u062c\u0648'
672
        name2 = u'2file-\u0633'
673
        tree = [
674
            name0,
675
            name1 + '/',
676
            name1 + '/' + name0,
677
            name1 + '/' + name1 + '/',
678
            name2,
679
            ]
680
        try:
681
            self.build_tree(tree)
682
        except UnicodeError:
683
            raise TestSkipped('Could not represent Unicode chars'
684
                              ' in current encoding.')
685
        name0 = name0.encode('utf8')
686
        name1 = name1.encode('utf8')
687
        name2 = name2.encode('utf8')
688
689
        expected_dirblocks = [
690
                (('', '.'),
691
                 [(name0, name0, 'file', './' + name0),
692
                  (name1, name1, 'directory', './' + name1),
693
                  (name2, name2, 'file', './' + name2),
694
                 ]
695
                ),
696
                ((name1, './' + name1),
697
                 [(name1 + '/' + name0, name0, 'file', './' + name1
698
                                                        + '/' + name0),
699
                  (name1 + '/' + name1, name1, 'directory', './' + name1
700
                                                            + '/' + name1),
701
                 ]
702
                ),
703
                ((name1 + '/' + name1, './' + name1 + '/' + name1),
704
                 [
705
                 ]
706
                ),
707
            ]
708
        result = []
709
        # For ease in testing, if walkdirs_utf8 returns Unicode, assert that
710
        # all abspaths are Unicode, and encode them back into utf8.
711
        for dirdetail, dirblock in osutils._walkdirs_utf8('.'):
712
            self.assertIsInstance(dirdetail[0], str)
713
            if isinstance(dirdetail[1], unicode):
2324.2.4 by Dmitry Vasiliev
Fixed test_unicode__walkdirs_utf8 test
714
                dirdetail = (dirdetail[0], dirdetail[1].encode('utf8'))
715
                dirblock = [list(info) for info in dirblock]
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
716
                for info in dirblock:
717
                    self.assertIsInstance(info[4], unicode)
718
                    info[4] = info[4].encode('utf8')
719
            new_dirblock = []
720
            for info in dirblock:
721
                self.assertIsInstance(info[0], str)
722
                self.assertIsInstance(info[1], str)
723
                self.assertIsInstance(info[4], str)
724
                # Remove the stat information
725
                new_dirblock.append((info[0], info[1], info[2], info[4]))
726
            result.append((dirdetail, new_dirblock))
727
        self.assertEqual(expected_dirblocks, result)
728
729
    def test_unicode__walkdirs_unicode_to_utf8(self):
730
        """walkdirs_unicode_to_utf8 should be a safe fallback everywhere
731
732
        The abspath portion should be in unicode
733
        """
734
        name0u = u'0file-\xb6'
735
        name1u = u'1dir-\u062c\u0648'
736
        name2u = u'2file-\u0633'
737
        tree = [
738
            name0u,
739
            name1u + '/',
740
            name1u + '/' + name0u,
741
            name1u + '/' + name1u + '/',
742
            name2u,
743
            ]
744
        try:
745
            self.build_tree(tree)
746
        except UnicodeError:
747
            raise TestSkipped('Could not represent Unicode chars'
748
                              ' in current encoding.')
749
        name0 = name0u.encode('utf8')
750
        name1 = name1u.encode('utf8')
751
        name2 = name2u.encode('utf8')
752
753
        # All of the abspaths should be in unicode, all of the relative paths
754
        # should be in utf8
755
        expected_dirblocks = [
756
                (('', '.'),
757
                 [(name0, name0, 'file', './' + name0u),
758
                  (name1, name1, 'directory', './' + name1u),
759
                  (name2, name2, 'file', './' + name2u),
760
                 ]
761
                ),
762
                ((name1, './' + name1u),
763
                 [(name1 + '/' + name0, name0, 'file', './' + name1u
764
                                                        + '/' + name0u),
765
                  (name1 + '/' + name1, name1, 'directory', './' + name1u
766
                                                            + '/' + name1u),
767
                 ]
768
                ),
769
                ((name1 + '/' + name1, './' + name1u + '/' + name1u),
770
                 [
771
                 ]
772
                ),
773
            ]
774
        result = list(osutils._walkdirs_unicode_to_utf8('.'))
775
        self._filter_out_stat(result)
776
        self.assertEqual(expected_dirblocks, result)
777
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
778
    def assertPathCompare(self, path_less, path_greater):
779
        """check that path_less and path_greater compare correctly."""
780
        self.assertEqual(0, osutils.compare_paths_prefix_order(
781
            path_less, path_less))
782
        self.assertEqual(0, osutils.compare_paths_prefix_order(
783
            path_greater, path_greater))
784
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
785
            path_less, path_greater))
786
        self.assertEqual(1, osutils.compare_paths_prefix_order(
787
            path_greater, path_less))
788
789
    def test_compare_paths_prefix_order(self):
790
        # root before all else
791
        self.assertPathCompare("/", "/a")
792
        # alpha within a dir
793
        self.assertPathCompare("/a", "/b")
794
        self.assertPathCompare("/b", "/z")
795
        # high dirs before lower.
796
        self.assertPathCompare("/z", "/a/a")
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
797
        # except if the deeper dir should be output first
798
        self.assertPathCompare("/a/b/c", "/d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
799
        # lexical betwen dirs of the same height
800
        self.assertPathCompare("/a/z", "/z/z")
801
        self.assertPathCompare("/a/c/z", "/a/d/e")
802
803
        # this should also be consistent for no leading / paths
804
        # root before all else
805
        self.assertPathCompare("", "a")
806
        # alpha within a dir
807
        self.assertPathCompare("a", "b")
808
        self.assertPathCompare("b", "z")
809
        # high dirs before lower.
810
        self.assertPathCompare("z", "a/a")
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
811
        # except if the deeper dir should be output first
812
        self.assertPathCompare("a/b/c", "d/g")
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
813
        # lexical betwen dirs of the same height
814
        self.assertPathCompare("a/z", "z/z")
815
        self.assertPathCompare("a/c/z", "a/d/e")
816
1773.3.3 by Robert Collins
Add new tests John Meinel asked for.
817
    def test_path_prefix_sorting(self):
818
        """Doing a sort on path prefix should match our sample data."""
819
        original_paths = [
820
            'a',
821
            'a/b',
822
            'a/b/c',
823
            'b',
824
            'b/c',
825
            'd',
826
            'd/e',
827
            'd/e/f',
828
            'd/f',
829
            'd/g',
830
            'g',
831
            ]
832
833
        dir_sorted_paths = [
834
            'a',
835
            'b',
836
            'd',
837
            'g',
838
            'a/b',
839
            'a/b/c',
840
            'b/c',
841
            'd/e',
842
            'd/f',
843
            'd/g',
844
            'd/e/f',
845
            ]
846
847
        self.assertEqual(
848
            dir_sorted_paths,
849
            sorted(original_paths, key=osutils.path_prefix_key))
850
        # using the comparison routine shoudl work too:
851
        self.assertEqual(
852
            dir_sorted_paths,
853
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
854
855
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
856
class TestCopyTree(TestCaseInTempDir):
857
    
858
    def test_copy_basic_tree(self):
859
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
860
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
861
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
862
        self.assertEqual(['c'], os.listdir('target/b'))
863
864
    def test_copy_tree_target_exists(self):
865
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c',
866
                         'target/'])
867
        osutils.copy_tree('source', 'target')
2095.3.1 by Martin Pool
Tests shouldn't assume os.listdir returns sorted results
868
        self.assertEqual(['a', 'b'], sorted(os.listdir('target')))
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
869
        self.assertEqual(['c'], os.listdir('target/b'))
870
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
871
    def test_copy_tree_symlinks(self):
872
        if not osutils.has_symlinks():
873
            return
874
        self.build_tree(['source/'])
875
        os.symlink('a/generic/path', 'source/lnk')
876
        osutils.copy_tree('source', 'target')
877
        self.assertEqual(['lnk'], os.listdir('target'))
878
        self.assertEqual('a/generic/path', os.readlink('target/lnk'))
879
880
    def test_copy_tree_handlers(self):
881
        processed_files = []
882
        processed_links = []
883
        def file_handler(from_path, to_path):
884
            processed_files.append(('f', from_path, to_path))
885
        def dir_handler(from_path, to_path):
886
            processed_files.append(('d', from_path, to_path))
887
        def link_handler(from_path, to_path):
888
            processed_links.append((from_path, to_path))
889
        handlers = {'file':file_handler,
890
                    'directory':dir_handler,
891
                    'symlink':link_handler,
892
                   }
893
894
        self.build_tree(['source/', 'source/a', 'source/b/', 'source/b/c'])
895
        if osutils.has_symlinks():
896
            os.symlink('a/generic/path', 'source/lnk')
897
        osutils.copy_tree('source', 'target', handlers=handlers)
898
899
        self.assertEqual([('d', 'source', 'target'),
900
                          ('f', 'source/a', 'target/a'),
901
                          ('d', 'source/b', 'target/b'),
902
                          ('f', 'source/b/c', 'target/b/c'),
903
                         ], processed_files)
904
        self.failIfExists('target')
905
        if osutils.has_symlinks():
906
            self.assertEqual([('source/lnk', 'target/lnk')], processed_links)
907
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
908
2192.1.2 by Alexander Belchenko
Tests for osutils.get_terminal_encoding()
909
#class TestTerminalEncoding has been moved to test_osutils_encodings.py
910
# [bialix] 2006/12/26
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
911
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
912
913
class TestSetUnsetEnv(TestCase):
914
    """Test updating the environment"""
915
916
    def setUp(self):
917
        super(TestSetUnsetEnv, self).setUp()
918
919
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'),
920
                         'Environment was not cleaned up properly.'
921
                         ' Variable BZR_TEST_ENV_VAR should not exist.')
922
        def cleanup():
923
            if 'BZR_TEST_ENV_VAR' in os.environ:
924
                del os.environ['BZR_TEST_ENV_VAR']
925
926
        self.addCleanup(cleanup)
927
928
    def test_set(self):
929
        """Test that we can set an env variable"""
930
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
931
        self.assertEqual(None, old)
932
        self.assertEqual('foo', os.environ.get('BZR_TEST_ENV_VAR'))
933
934
    def test_double_set(self):
935
        """Test that we get the old value out"""
936
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
937
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'bar')
938
        self.assertEqual('foo', old)
939
        self.assertEqual('bar', os.environ.get('BZR_TEST_ENV_VAR'))
940
941
    def test_unicode(self):
942
        """Environment can only contain plain strings
943
        
944
        So Unicode strings must be encoded.
945
        """
946
        # Try a few different characters, to see if we can get
947
        # one that will be valid in the user_encoding
948
        possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
949
        for uni_val in possible_vals:
950
            try:
951
                env_val = uni_val.encode(bzrlib.user_encoding)
952
            except UnicodeEncodeError:
953
                # Try a different character
954
                pass
955
            else:
956
                break
957
        else:
958
            raise TestSkipped('Cannot find a unicode character that works in'
959
                              ' encoding %s' % (bzrlib.user_encoding,))
960
961
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', uni_val)
962
        self.assertEqual(env_val, os.environ.get('BZR_TEST_ENV_VAR'))
963
964
    def test_unset(self):
965
        """Test that passing None will remove the env var"""
966
        osutils.set_or_unset_env('BZR_TEST_ENV_VAR', 'foo')
967
        old = osutils.set_or_unset_env('BZR_TEST_ENV_VAR', None)
968
        self.assertEqual('foo', old)
969
        self.assertEqual(None, os.environ.get('BZR_TEST_ENV_VAR'))
970
        self.failIf('BZR_TEST_ENV_VAR' in os.environ)
971
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
972
973
class TestLocalTimeOffset(TestCase):
974
975
    def test_local_time_offset(self):
976
        """Test that local_time_offset() returns a sane value."""
977
        offset = osutils.local_time_offset()
978
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
979
        # Test that the offset is no more than a eighteen hours in
980
        # either direction.
981
        # Time zone handling is system specific, so it is difficult to
982
        # do more specific tests, but a value outside of this range is
983
        # probably wrong.
984
        eighteen_hours = 18 * 3600
985
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)
2215.6.2 by James Henstridge
add some simple tests for local_time_offset()
986
987
    def test_local_time_offset_with_timestamp(self):
988
        """Test that local_time_offset() works with a timestamp."""
989
        offset = osutils.local_time_offset(1000000000.1234567)
990
        self.assertTrue(isinstance(offset, int))
2215.6.3 by James Henstridge
narrow the range that the local_time_offset() test uses
991
        eighteen_hours = 18 * 3600
992
        self.assertTrue(-eighteen_hours < offset < eighteen_hours)