/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_osutils.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 by Canonical Ltd
 
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
 
 
17
"""Tests for the osutils wrapper."""
 
18
 
 
19
import errno
 
20
import os
 
21
import socket
 
22
import stat
 
23
import sys
 
24
 
 
25
import bzrlib
 
26
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
 
27
import bzrlib.osutils as osutils
 
28
from bzrlib.tests import (
 
29
        StringIOWrapper,
 
30
        TestCase, 
 
31
        TestCaseInTempDir, 
 
32
        TestSkipped,
 
33
        )
 
34
 
 
35
 
 
36
class TestOSUtils(TestCaseInTempDir):
 
37
 
 
38
    def test_fancy_rename(self):
 
39
        # This should work everywhere
 
40
        def rename(a, b):
 
41
            osutils.fancy_rename(a, b,
 
42
                    rename_func=os.rename,
 
43
                    unlink_func=os.unlink)
 
44
 
 
45
        open('a', 'wb').write('something in a\n')
 
46
        rename('a', 'b')
 
47
        self.failIfExists('a')
 
48
        self.failUnlessExists('b')
 
49
        self.check_file_contents('b', 'something in a\n')
 
50
 
 
51
        open('a', 'wb').write('new something in a\n')
 
52
        rename('b', 'a')
 
53
 
 
54
        self.check_file_contents('a', 'something in a\n')
 
55
 
 
56
    def test_rename(self):
 
57
        # Rename should be semi-atomic on all platforms
 
58
        open('a', 'wb').write('something in a\n')
 
59
        osutils.rename('a', 'b')
 
60
        self.failIfExists('a')
 
61
        self.failUnlessExists('b')
 
62
        self.check_file_contents('b', 'something in a\n')
 
63
 
 
64
        open('a', 'wb').write('new something in a\n')
 
65
        osutils.rename('b', 'a')
 
66
 
 
67
        self.check_file_contents('a', 'something in a\n')
 
68
 
 
69
    # TODO: test fancy_rename using a MemoryTransport
 
70
 
 
71
    def test_01_rand_chars_empty(self):
 
72
        result = osutils.rand_chars(0)
 
73
        self.assertEqual(result, '')
 
74
 
 
75
    def test_02_rand_chars_100(self):
 
76
        result = osutils.rand_chars(100)
 
77
        self.assertEqual(len(result), 100)
 
78
        self.assertEqual(type(result), str)
 
79
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
 
80
 
 
81
 
 
82
    def test_rmtree(self):
 
83
        # Check to remove tree with read-only files/dirs
 
84
        os.mkdir('dir')
 
85
        f = file('dir/file', 'w')
 
86
        f.write('spam')
 
87
        f.close()
 
88
        # would like to also try making the directory readonly, but at the
 
89
        # moment python shutil.rmtree doesn't handle that properly - it would
 
90
        # need to chmod the directory before removing things inside it - deferred
 
91
        # for now -- mbp 20060505
 
92
        # osutils.make_readonly('dir')
 
93
        osutils.make_readonly('dir/file')
 
94
 
 
95
        osutils.rmtree('dir')
 
96
 
 
97
        self.failIfExists('dir/file')
 
98
        self.failIfExists('dir')
 
99
 
 
100
    def test_file_kind(self):
 
101
        self.build_tree(['file', 'dir/'])
 
102
        self.assertEquals('file', osutils.file_kind('file'))
 
103
        self.assertEquals('directory', osutils.file_kind('dir/'))
 
104
        if osutils.has_symlinks():
 
105
            os.symlink('symlink', 'symlink')
 
106
            self.assertEquals('symlink', osutils.file_kind('symlink'))
 
107
        
 
108
        # TODO: jam 20060529 Test a block device
 
109
        try:
 
110
            os.lstat('/dev/null')
 
111
        except OSError, e:
 
112
            if e.errno not in (errno.ENOENT,):
 
113
                raise
 
114
        else:
 
115
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
 
116
 
 
117
        mkfifo = getattr(os, 'mkfifo', None)
 
118
        if mkfifo:
 
119
            mkfifo('fifo')
 
120
            try:
 
121
                self.assertEquals('fifo', osutils.file_kind('fifo'))
 
122
            finally:
 
123
                os.remove('fifo')
 
124
 
 
125
        AF_UNIX = getattr(socket, 'AF_UNIX', None)
 
126
        if AF_UNIX:
 
127
            s = socket.socket(AF_UNIX)
 
128
            s.bind('socket')
 
129
            try:
 
130
                self.assertEquals('socket', osutils.file_kind('socket'))
 
131
            finally:
 
132
                os.remove('socket')
 
133
 
 
134
 
 
135
class TestSafeUnicode(TestCase):
 
136
 
 
137
    def test_from_ascii_string(self):
 
138
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
 
139
 
 
140
    def test_from_unicode_string_ascii_contents(self):
 
141
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
 
142
 
 
143
    def test_from_unicode_string_unicode_contents(self):
 
144
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
 
145
 
 
146
    def test_from_utf8_string(self):
 
147
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
 
148
 
 
149
    def test_bad_utf8_string(self):
 
150
        self.assertRaises(BzrBadParameterNotUnicode,
 
151
                          osutils.safe_unicode,
 
152
                          '\xbb\xbb')
 
153
 
 
154
 
 
155
class TestWin32Funcs(TestCase):
 
156
    """Test that the _win32 versions of os utilities return appropriate paths."""
 
157
 
 
158
    def test_abspath(self):
 
159
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
 
160
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
 
161
 
 
162
    def test_realpath(self):
 
163
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
 
164
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
 
165
 
 
166
    def test_pathjoin(self):
 
167
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
 
168
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
 
169
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
 
170
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
 
171
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
 
172
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
 
173
 
 
174
    def test_normpath(self):
 
175
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
 
176
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
 
177
 
 
178
    def test_getcwd(self):
 
179
        cwd = osutils._win32_getcwd()
 
180
        os_cwd = os.getcwdu()
 
181
        self.assertEqual(os_cwd[1:].replace('\\', '/'), cwd[1:])
 
182
        # win32 is inconsistent whether it returns lower or upper case
 
183
        # and even if it was consistent the user might type the other
 
184
        # so we force it to uppercase
 
185
        # running python.exe under cmd.exe return capital C:\\
 
186
        # running win32 python inside a cygwin shell returns lowercase
 
187
        self.assertEqual(os_cwd[0].upper(), cwd[0])
 
188
 
 
189
    def test_fixdrive(self):
 
190
        self.assertEqual('H:/foo', osutils._win32_fixdrive('h:/foo'))
 
191
        self.assertEqual('H:/foo', osutils._win32_fixdrive('H:/foo'))
 
192
        self.assertEqual('C:\\foo', osutils._win32_fixdrive('c:\\foo'))
 
193
 
 
194
 
 
195
class TestWin32FuncsDirs(TestCaseInTempDir):
 
196
    """Test win32 functions that create files."""
 
197
    
 
198
    def test_getcwd(self):
 
199
        # Make sure getcwd can handle unicode filenames
 
200
        try:
 
201
            os.mkdir(u'B\xe5gfors')
 
202
        except UnicodeError:
 
203
            raise TestSkipped("Unable to create Unicode filename")
 
204
 
 
205
        os.chdir(u'B\xe5gfors')
 
206
        # TODO: jam 20060427 This will probably fail on Mac OSX because
 
207
        #       it will change the normalization of B\xe5gfors
 
208
        #       Consider using a different unicode character, or make
 
209
        #       osutils.getcwd() renormalize the path.
 
210
        self.assertTrue(osutils._win32_getcwd().endswith(u'/B\xe5gfors'))
 
211
 
 
212
    def test_mkdtemp(self):
 
213
        tmpdir = osutils._win32_mkdtemp(dir='.')
 
214
        self.assertFalse('\\' in tmpdir)
 
215
 
 
216
    def test_rename(self):
 
217
        a = open('a', 'wb')
 
218
        a.write('foo\n')
 
219
        a.close()
 
220
        b = open('b', 'wb')
 
221
        b.write('baz\n')
 
222
        b.close()
 
223
 
 
224
        osutils._win32_rename('b', 'a')
 
225
        self.failUnlessExists('a')
 
226
        self.failIfExists('b')
 
227
        self.assertFileEqual('baz\n', 'a')
 
228
 
 
229
 
 
230
class TestSplitLines(TestCase):
 
231
 
 
232
    def test_split_unicode(self):
 
233
        self.assertEqual([u'foo\n', u'bar\xae'],
 
234
                         osutils.split_lines(u'foo\nbar\xae'))
 
235
        self.assertEqual([u'foo\n', u'bar\xae\n'],
 
236
                         osutils.split_lines(u'foo\nbar\xae\n'))
 
237
 
 
238
    def test_split_with_carriage_returns(self):
 
239
        self.assertEqual(['foo\rbar\n'],
 
240
                         osutils.split_lines('foo\rbar\n'))
 
241
 
 
242
 
 
243
class TestWalkDirs(TestCaseInTempDir):
 
244
 
 
245
    def test_walkdirs(self):
 
246
        tree = [
 
247
            '.bzr',
 
248
            '0file',
 
249
            '1dir/',
 
250
            '1dir/0file',
 
251
            '1dir/1dir/',
 
252
            '2file'
 
253
            ]
 
254
        self.build_tree(tree)
 
255
        expected_dirblocks = [
 
256
                [
 
257
                    ('0file', '0file', 'file'),
 
258
                    ('1dir', '1dir', 'directory'),
 
259
                    ('2file', '2file', 'file'),
 
260
                ],
 
261
                [
 
262
                    ('1dir/0file', '0file', 'file'),
 
263
                    ('1dir/1dir', '1dir', 'directory'),
 
264
                ],
 
265
                [
 
266
                ],
 
267
            ]
 
268
        result = []
 
269
        found_bzrdir = False
 
270
        for dirblock in osutils.walkdirs('.'):
 
271
            if len(dirblock) and dirblock[0][1] == '.bzr':
 
272
                # this tests the filtering of selected paths
 
273
                found_bzrdir = True
 
274
                del dirblock[0]
 
275
            result.append(dirblock)
 
276
 
 
277
        self.assertTrue(found_bzrdir)
 
278
        self.assertEqual(expected_dirblocks,
 
279
            [[line[0:3] for line in block] for block in result])
 
280
        # you can search a subdir only, with a supplied prefix.
 
281
        result = []
 
282
        for dirblock in osutils.walkdirs('1dir', '1dir'):
 
283
            result.append(dirblock)
 
284
        self.assertEqual(expected_dirblocks[1:],
 
285
            [[line[0:3] for line in block] for block in result])
 
286
 
 
287
    def assertPathCompare(self, path_less, path_greater):
 
288
        """check that path_less and path_greater compare correctly."""
 
289
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
290
            path_less, path_less))
 
291
        self.assertEqual(0, osutils.compare_paths_prefix_order(
 
292
            path_greater, path_greater))
 
293
        self.assertEqual(-1, osutils.compare_paths_prefix_order(
 
294
            path_less, path_greater))
 
295
        self.assertEqual(1, osutils.compare_paths_prefix_order(
 
296
            path_greater, path_less))
 
297
 
 
298
    def test_compare_paths_prefix_order(self):
 
299
        # root before all else
 
300
        self.assertPathCompare("/", "/a")
 
301
        # alpha within a dir
 
302
        self.assertPathCompare("/a", "/b")
 
303
        self.assertPathCompare("/b", "/z")
 
304
        # high dirs before lower.
 
305
        self.assertPathCompare("/z", "/a/a")
 
306
        # except if the deeper dir should be output first
 
307
        self.assertPathCompare("/a/b/c", "/d/g")
 
308
        # lexical betwen dirs of the same height
 
309
        self.assertPathCompare("/a/z", "/z/z")
 
310
        self.assertPathCompare("/a/c/z", "/a/d/e")
 
311
 
 
312
        # this should also be consistent for no leading / paths
 
313
        # root before all else
 
314
        self.assertPathCompare("", "a")
 
315
        # alpha within a dir
 
316
        self.assertPathCompare("a", "b")
 
317
        self.assertPathCompare("b", "z")
 
318
        # high dirs before lower.
 
319
        self.assertPathCompare("z", "a/a")
 
320
        # except if the deeper dir should be output first
 
321
        self.assertPathCompare("a/b/c", "d/g")
 
322
        # lexical betwen dirs of the same height
 
323
        self.assertPathCompare("a/z", "z/z")
 
324
        self.assertPathCompare("a/c/z", "a/d/e")
 
325
 
 
326
    def test_path_prefix_sorting(self):
 
327
        """Doing a sort on path prefix should match our sample data."""
 
328
        original_paths = [
 
329
            'a',
 
330
            'a/b',
 
331
            'a/b/c',
 
332
            'b',
 
333
            'b/c',
 
334
            'd',
 
335
            'd/e',
 
336
            'd/e/f',
 
337
            'd/f',
 
338
            'd/g',
 
339
            'g',
 
340
            ]
 
341
 
 
342
        dir_sorted_paths = [
 
343
            'a',
 
344
            'b',
 
345
            'd',
 
346
            'g',
 
347
            'a/b',
 
348
            'a/b/c',
 
349
            'b/c',
 
350
            'd/e',
 
351
            'd/f',
 
352
            'd/g',
 
353
            'd/e/f',
 
354
            ]
 
355
 
 
356
        self.assertEqual(
 
357
            dir_sorted_paths,
 
358
            sorted(original_paths, key=osutils.path_prefix_key))
 
359
        # using the comparison routine shoudl work too:
 
360
        self.assertEqual(
 
361
            dir_sorted_paths,
 
362
            sorted(original_paths, cmp=osutils.compare_paths_prefix_order))
 
363
 
 
364
 
 
365
class TestTerminalEncoding(TestCase):
 
366
    """Test the auto-detection of proper terminal encoding."""
 
367
 
 
368
    def setUp(self):
 
369
        self._stdout = sys.stdout
 
370
        self._stderr = sys.stderr
 
371
        self._stdin = sys.stdin
 
372
        self._user_encoding = bzrlib.user_encoding
 
373
 
 
374
        self.addCleanup(self._reset)
 
375
 
 
376
        sys.stdout = StringIOWrapper()
 
377
        sys.stdout.encoding = 'stdout_encoding'
 
378
        sys.stderr = StringIOWrapper()
 
379
        sys.stderr.encoding = 'stderr_encoding'
 
380
        sys.stdin = StringIOWrapper()
 
381
        sys.stdin.encoding = 'stdin_encoding'
 
382
        bzrlib.user_encoding = 'user_encoding'
 
383
 
 
384
    def _reset(self):
 
385
        sys.stdout = self._stdout
 
386
        sys.stderr = self._stderr
 
387
        sys.stdin = self._stdin
 
388
        bzrlib.user_encoding = self._user_encoding
 
389
 
 
390
    def test_get_terminal_encoding(self):
 
391
        # first preference is stdout encoding
 
392
        self.assertEqual('stdout_encoding', osutils.get_terminal_encoding())
 
393
 
 
394
        sys.stdout.encoding = None
 
395
        # if sys.stdout is None, fall back to sys.stdin
 
396
        self.assertEqual('stdin_encoding', osutils.get_terminal_encoding())
 
397
 
 
398
        sys.stdin.encoding = None
 
399
        # and in the worst case, use bzrlib.user_encoding
 
400
        self.assertEqual('user_encoding', osutils.get_terminal_encoding())
 
401