/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
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
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
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
26
from bzrlib.errors import BzrBadParameterNotUnicode, InvalidURL
1532 by Robert Collins
Merge in John Meinels integration branch.
27
import bzrlib.osutils as osutils
1685.1.75 by Wouter van Heyst
more tests handle LANG=C
28
from bzrlib.tests import TestCaseInTempDir, TestCase, TestSkipped
1532 by Robert Collins
Merge in John Meinels integration branch.
29
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
30
31
class TestOSUtils(TestCaseInTempDir):
32
33
    def test_fancy_rename(self):
34
        # This should work everywhere
35
        def rename(a, b):
36
            osutils.fancy_rename(a, b,
37
                    rename_func=os.rename,
38
                    unlink_func=os.unlink)
39
40
        open('a', 'wb').write('something in a\n')
41
        rename('a', 'b')
42
        self.failIfExists('a')
43
        self.failUnlessExists('b')
44
        self.check_file_contents('b', 'something in a\n')
45
46
        open('a', 'wb').write('new something in a\n')
47
        rename('b', 'a')
48
49
        self.check_file_contents('a', 'something in a\n')
50
51
    def test_rename(self):
52
        # Rename should be semi-atomic on all platforms
53
        open('a', 'wb').write('something in a\n')
54
        osutils.rename('a', 'b')
55
        self.failIfExists('a')
56
        self.failUnlessExists('b')
57
        self.check_file_contents('b', 'something in a\n')
58
59
        open('a', 'wb').write('new something in a\n')
60
        osutils.rename('b', 'a')
61
62
        self.check_file_contents('a', 'something in a\n')
63
64
    # TODO: test fancy_rename using a MemoryTransport
65
1553.5.5 by Martin Pool
New utility routine rand_chars
66
    def test_01_rand_chars_empty(self):
67
        result = osutils.rand_chars(0)
68
        self.assertEqual(result, '')
69
70
    def test_02_rand_chars_100(self):
71
        result = osutils.rand_chars(100)
72
        self.assertEqual(len(result), 100)
73
        self.assertEqual(type(result), str)
74
        self.assertContainsRe(result, r'^[a-z0-9]{100}$')
75
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
76
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
77
    def test_rmtree(self):
78
        # Check to remove tree with read-only files/dirs
79
        os.mkdir('dir')
80
        f = file('dir/file', 'w')
81
        f.write('spam')
82
        f.close()
83
        # would like to also try making the directory readonly, but at the
84
        # moment python shutil.rmtree doesn't handle that properly - it would
85
        # need to chmod the directory before removing things inside it - deferred
86
        # for now -- mbp 20060505
87
        # osutils.make_readonly('dir')
88
        osutils.make_readonly('dir/file')
89
90
        osutils.rmtree('dir')
91
92
        self.failIfExists('dir/file')
93
        self.failIfExists('dir')
94
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
95
    def test_file_kind(self):
96
        self.build_tree(['file', 'dir/'])
97
        self.assertEquals('file', osutils.file_kind('file'))
98
        self.assertEquals('directory', osutils.file_kind('dir/'))
99
        if osutils.has_symlinks():
100
            os.symlink('symlink', 'symlink')
101
            self.assertEquals('symlink', osutils.file_kind('symlink'))
1732.1.28 by John Arbash Meinel
Add tests for fancy file types.
102
        
103
        # TODO: jam 20060529 Test a block device
104
        try:
105
            os.lstat('/dev/null')
106
        except OSError, e:
107
            if e.errno not in (errno.ENOENT,):
108
                raise
109
        else:
110
            self.assertEquals('chardev', osutils.file_kind('/dev/null'))
111
112
        mkfifo = getattr(os, 'mkfifo', None)
113
        if mkfifo:
114
            mkfifo('fifo')
115
            try:
116
                self.assertEquals('fifo', osutils.file_kind('fifo'))
117
            finally:
118
                os.remove('fifo')
119
120
        AF_UNIX = getattr(socket, 'AF_UNIX', None)
121
        if AF_UNIX:
122
            s = socket.socket(AF_UNIX)
123
            s.bind('socket')
124
            try:
125
                self.assertEquals('socket', osutils.file_kind('socket'))
126
            finally:
127
                os.remove('socket')
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
128
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
129
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
130
class TestSafeUnicode(TestCase):
131
132
    def test_from_ascii_string(self):
133
        self.assertEqual(u'foobar', osutils.safe_unicode('foobar'))
134
1534.3.2 by Robert Collins
An extra test for John.
135
    def test_from_unicode_string_ascii_contents(self):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
136
        self.assertEqual(u'bargam', osutils.safe_unicode(u'bargam'))
137
1534.3.2 by Robert Collins
An extra test for John.
138
    def test_from_unicode_string_unicode_contents(self):
139
        self.assertEqual(u'bargam\xae', osutils.safe_unicode(u'bargam\xae'))
140
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
141
    def test_from_utf8_string(self):
142
        self.assertEqual(u'foo\xae', osutils.safe_unicode('foo\xc2\xae'))
143
144
    def test_bad_utf8_string(self):
1185.65.29 by Robert Collins
Implement final review suggestions.
145
        self.assertRaises(BzrBadParameterNotUnicode,
146
                          osutils.safe_unicode,
147
                          '\xbb\xbb')
1666.1.6 by Robert Collins
Make knit the default format.
148
149
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
150
class TestWin32Funcs(TestCase):
151
    """Test that the _win32 versions of os utilities return appropriate paths."""
152
153
    def test_abspath(self):
154
        self.assertEqual('C:/foo', osutils._win32_abspath('C:\\foo'))
155
        self.assertEqual('C:/foo', osutils._win32_abspath('C:/foo'))
156
157
    def test_realpath(self):
158
        self.assertEqual('C:/foo', osutils._win32_realpath('C:\\foo'))
159
        self.assertEqual('C:/foo', osutils._win32_realpath('C:/foo'))
160
161
    def test_pathjoin(self):
162
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path', 'to', 'foo'))
163
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path\\to', 'C:\\foo'))
164
        self.assertEqual('C:/foo', osutils._win32_pathjoin('path/to', 'C:/foo'))
165
        self.assertEqual('path/to/foo', osutils._win32_pathjoin('path/to/', 'foo'))
166
        self.assertEqual('/foo', osutils._win32_pathjoin('C:/path/to/', '/foo'))
167
        self.assertEqual('/foo', osutils._win32_pathjoin('C:\\path\\to\\', '\\foo'))
168
169
    def test_normpath(self):
170
        self.assertEqual('path/to/foo', osutils._win32_normpath(r'path\\from\..\to\.\foo'))
171
        self.assertEqual('path/to/foo', osutils._win32_normpath('path//from/../to/./foo'))
172
173
    def test_getcwd(self):
174
        self.assertEqual(os.getcwdu().replace('\\', '/'), osutils._win32_getcwd())
175
176
177
class TestWin32FuncsDirs(TestCaseInTempDir):
178
    """Test win32 functions that create files."""
179
    
180
    def test_getcwd(self):
181
        # Make sure getcwd can handle unicode filenames
182
        try:
183
            os.mkdir(u'B\xe5gfors')
184
        except UnicodeError:
185
            raise TestSkipped("Unable to create Unicode filename")
186
187
        os.chdir(u'B\xe5gfors')
188
        # TODO: jam 20060427 This will probably fail on Mac OSX because
189
        #       it will change the normalization of B\xe5gfors
190
        #       Consider using a different unicode character, or make
191
        #       osutils.getcwd() renormalize the path.
192
        self.assertTrue(osutils._win32_getcwd().endswith(u'/B\xe5gfors'))
193
194
    def test_mkdtemp(self):
195
        tmpdir = osutils._win32_mkdtemp(dir='.')
196
        self.assertFalse('\\' in tmpdir)
197
198
    def test_rename(self):
199
        a = open('a', 'wb')
200
        a.write('foo\n')
201
        a.close()
202
        b = open('b', 'wb')
203
        b.write('baz\n')
204
        b.close()
205
206
        osutils._win32_rename('b', 'a')
207
        self.failUnlessExists('a')
208
        self.failIfExists('b')
209
        self.assertFileEqual('baz\n', 'a')
210
211
1666.1.6 by Robert Collins
Make knit the default format.
212
class TestSplitLines(TestCase):
213
214
    def test_split_unicode(self):
215
        self.assertEqual([u'foo\n', u'bar\xae'],
216
                         osutils.split_lines(u'foo\nbar\xae'))
217
        self.assertEqual([u'foo\n', u'bar\xae\n'],
218
                         osutils.split_lines(u'foo\nbar\xae\n'))
219
220
    def test_split_with_carriage_returns(self):
221
        self.assertEqual(['foo\rbar\n'],
222
                         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.
223
224
225
class TestWalkDirs(TestCaseInTempDir):
226
227
    def test_walkdirs(self):
228
        tree = [
229
            '.bzr',
230
            '0file',
231
            '1dir/',
232
            '1dir/0file',
233
            '1dir/1dir/',
234
            '2file'
235
            ]
236
        self.build_tree(tree)
237
        expected_dirblocks = [
238
                [
239
                    ('0file', '0file', 'file'),
240
                    ('1dir', '1dir', 'directory'),
241
                    ('2file', '2file', 'file'),
242
                ],
243
                [
244
                    ('1dir/0file', '0file', 'file'),
245
                    ('1dir/1dir', '1dir', 'directory'),
246
                ],
247
                [
248
                ],
249
            ]
250
        result = []
251
        found_bzrdir = False
252
        for dirblock in osutils.walkdirs('.'):
253
            if len(dirblock) and dirblock[0][1] == '.bzr':
254
                # this tests the filtering of selected paths
255
                found_bzrdir = True
256
                del dirblock[0]
257
            result.append(dirblock)
258
259
        self.assertTrue(found_bzrdir)
260
        self.assertEqual(expected_dirblocks,
261
            [[line[0:3] for line in block] for block in result])
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
262
        # you can search a subdir only, with a supplied prefix.
263
        result = []
264
        for dirblock in osutils.walkdirs('1dir', '1dir'):
265
            result.append(dirblock)
266
        self.assertEqual(expected_dirblocks[1:],
267
            [[line[0:3] for line in block] for block in result])
268