~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_win32utils.py

  • Committer: Wouter van Heyst
  • Date: 2012-01-25 21:13:15 UTC
  • mto: (6437.3.27 2.5)
  • mto: This revision was merged to the branch mainline in revision 6451.
  • Revision ID: larstiq@larstiq.dyndns.org-20120125211315-ch74doua37bqet0i
mechanically replace file().write() pattern with a with-keyword version

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
"""Tests for win32utils."""
 
18
 
17
19
import os
18
 
import sys
19
20
 
20
21
from bzrlib import (
21
22
    osutils,
 
23
    symbol_versioning,
22
24
    tests,
23
25
    win32utils,
24
26
    )
25
27
from bzrlib.tests import (
26
 
    Feature,
27
28
    TestCase,
28
29
    TestCaseInTempDir,
29
30
    TestSkipped,
30
 
    UnicodeFilenameFeature,
31
31
    )
 
32
from bzrlib.tests.features import backslashdir_feature
32
33
from bzrlib.win32utils import glob_expand, get_app_path
33
 
 
34
 
 
35
 
class _BackslashDirSeparatorFeature(tests.Feature):
36
 
 
37
 
    def _probe(self):
38
 
        try:
39
 
            os.lstat(os.getcwd() + '\\')
40
 
        except OSError:
41
 
            return False
42
 
        else:
43
 
            return True
44
 
 
45
 
    def feature_name(self):
46
 
        return "Filesystem treats '\\' as a directory separator."
47
 
 
48
 
BackslashDirSeparatorFeature = _BackslashDirSeparatorFeature()
49
 
 
50
 
 
51
 
class _RequiredModuleFeature(Feature):
52
 
 
53
 
    def __init__(self, mod_name):
54
 
        self.mod_name = mod_name
55
 
        super(_RequiredModuleFeature, self).__init__()
56
 
 
57
 
    def _probe(self):
58
 
        try:
59
 
            __import__(self.mod_name)
60
 
            return True
61
 
        except ImportError:
62
 
            return False
63
 
 
64
 
    def feature_name(self):
65
 
        return self.mod_name
66
 
 
67
 
Win32RegistryFeature = _RequiredModuleFeature('_winreg')
68
 
CtypesFeature = _RequiredModuleFeature('ctypes')
69
 
Win32comShellFeature = _RequiredModuleFeature('win32com.shell')
 
34
from bzrlib.tests import (
 
35
    features,
 
36
    )
 
37
 
 
38
 
 
39
Win32RegistryFeature = features.ModuleAvailableFeature('_winreg')
 
40
CtypesFeature = features.ModuleAvailableFeature('ctypes')
 
41
Win32comShellFeature = features.ModuleAvailableFeature('win32com.shell')
 
42
Win32ApiFeature = features.ModuleAvailableFeature('win32api') 
70
43
 
71
44
 
72
45
# Tests
91
64
                         'd/', 'd/d1', 'd/d2', 'd/e/', 'd/e/e1'])
92
65
 
93
66
    def build_unicode_tree(self):
94
 
        self.requireFeature(UnicodeFilenameFeature)
 
67
        self.requireFeature(features.UnicodeFilenameFeature)
95
68
        self.build_tree([u'\u1234', u'\u1234\u1234', u'\u1235/',
96
69
                         u'\u1235/\u1235'])
97
70
 
121
94
            ])
122
95
 
123
96
    def test_backslash_globbing(self):
124
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
97
        self.requireFeature(backslashdir_feature)
125
98
        self.build_ascii_tree()
126
99
        self._run_testset([
127
100
            [[u'd\\'], [u'd/']],
132
105
            ])
133
106
 
134
107
    def test_case_insensitive_globbing(self):
135
 
        self.requireFeature(tests.CaseInsCasePresFilenameFeature)
 
108
        if os.path.normcase("AbC") == "AbC":
 
109
            self.skip("Test requires case insensitive globbing function")
136
110
        self.build_ascii_tree()
137
111
        self._run_testset([
138
112
            [[u'A'], [u'A']],
164
138
            ])
165
139
 
166
140
    def test_unicode_backslashes(self):
167
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
141
        self.requireFeature(backslashdir_feature)
168
142
        self.build_unicode_tree()
169
143
        self._run_testset([
170
144
            # no wildcards
202
176
        # typical windows users should have wordpad in the system
203
177
        # but there is problem: its path has the format REG_EXPAND_SZ
204
178
        # so naive attempt to get the path is not working
 
179
        self.requireFeature(Win32ApiFeature)
205
180
        for a in ('wordpad', 'wordpad.exe'):
206
181
            p = get_app_path(a)
207
182
            d, b = os.path.split(p)
213
188
        self.assertEquals('not-existing', p)
214
189
 
215
190
 
 
191
class TestLocations(TestCase):
 
192
    """Tests for windows specific path and name retrieving functions"""
 
193
 
 
194
    def test__ensure_unicode_deprecated(self):
 
195
        s = "text"
 
196
        u1 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
197
            win32utils._ensure_unicode, s)
 
198
        self.assertEqual(s, u1)
 
199
        self.assertIsInstance(u1, unicode)
 
200
        u2 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
201
            win32utils._ensure_unicode, u1)
 
202
        self.assertIs(u1, u2)
 
203
    
 
204
    def test_appdata_unicode_deprecated(self):
 
205
        self.overrideEnv("APPDATA", "fakepath")
 
206
        s = win32utils.get_appdata_location()
 
207
        u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
208
            win32utils.get_appdata_location_unicode)
 
209
        self.assertEqual(s, u)
 
210
        self.assertIsInstance(s, unicode)
 
211
 
 
212
    def test_home_unicode_deprecated(self):
 
213
        s = win32utils.get_home_location()
 
214
        u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
215
            win32utils.get_home_location_unicode)
 
216
        self.assertEqual(s, u)
 
217
        self.assertIsInstance(s, unicode)
 
218
 
 
219
    def test_user_unicode_deprecated(self):
 
220
        self.overrideEnv("USERNAME", "alien")
 
221
        s = win32utils.get_user_name()
 
222
        u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
223
            win32utils.get_user_name_unicode)
 
224
        self.assertEqual(s, u)
 
225
        self.assertIsInstance(s, unicode)
 
226
 
 
227
    def test_host_unicode_deprecated(self):
 
228
        self.overrideEnv("COMPUTERNAME", "alienbox")
 
229
        s = win32utils.get_host_name()
 
230
        u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
 
231
            win32utils.get_host_name_unicode)
 
232
        self.assertEqual(s, u)
 
233
        self.assertIsInstance(s, unicode)
 
234
 
 
235
 
216
236
class TestLocationsCtypes(TestCase):
217
237
 
218
238
    _test_needs_features = [CtypesFeature]
227
247
    def test_appdata_not_using_environment(self):
228
248
        # Test that we aren't falling back to the environment
229
249
        first = win32utils.get_appdata_location()
230
 
        self._captureVar("APPDATA", None)
 
250
        self.overrideEnv("APPDATA", None)
231
251
        self.assertPathsEqual(first, win32utils.get_appdata_location())
232
252
 
233
253
    def test_appdata_matches_environment(self):
244
264
    def test_local_appdata_not_using_environment(self):
245
265
        # Test that we aren't falling back to the environment
246
266
        first = win32utils.get_local_appdata_location()
247
 
        self._captureVar("LOCALAPPDATA", None)
 
267
        self.overrideEnv("LOCALAPPDATA", None)
248
268
        self.assertPathsEqual(first, win32utils.get_local_appdata_location())
249
269
 
250
270
    def test_local_appdata_matches_environment(self):
274
294
 
275
295
    def test_unicode_dir(self):
276
296
        # we should handle unicode paths without errors
277
 
        self.requireFeature(UnicodeFilenameFeature)
 
297
        self.requireFeature(features.UnicodeFilenameFeature)
278
298
        os.mkdir(u'\u1234')
279
299
        win32utils.set_file_attr_hidden(u'\u1234')
280
300
 
281
301
    def test_dot_bzr_in_unicode_dir(self):
282
302
        # we should not raise traceback if we try to set hidden attribute
283
303
        # on .bzr directory below unicode path
284
 
        self.requireFeature(UnicodeFilenameFeature)
 
304
        self.requireFeature(features.UnicodeFilenameFeature)
285
305
        os.makedirs(u'\u1234\\.bzr')
286
306
        path = osutils.abspath(u'\u1234\\.bzr')
287
307
        win32utils.set_file_attr_hidden(path)
288
308
 
289
309
 
290
 
 
291
 
class TestUnicodeShlex(tests.TestCase):
292
 
 
293
 
    def assertAsTokens(self, expected, line):
294
 
        s = win32utils.UnicodeShlex(line)
295
 
        self.assertEqual(expected, list(s))
296
 
 
297
 
    def test_simple(self):
298
 
        self.assertAsTokens([(False, u'foo'), (False, u'bar'), (False, u'baz')],
299
 
                            u'foo bar baz')
300
 
 
301
 
    def test_ignore_multiple_spaces(self):
302
 
        self.assertAsTokens([(False, u'foo'), (False, u'bar')], u'foo  bar')
303
 
 
304
 
    def test_ignore_leading_space(self):
305
 
        self.assertAsTokens([(False, u'foo'), (False, u'bar')], u'  foo bar')
306
 
 
307
 
    def test_ignore_trailing_space(self):
308
 
        self.assertAsTokens([(False, u'foo'), (False, u'bar')], u'foo bar  ')
309
 
 
310
 
    def test_posix_quotations(self):
311
 
        self.assertAsTokens([(True, u'foo bar')], u'"foo bar"')
312
 
        self.assertAsTokens([(False, u"'fo''o"), (False, u"b''ar'")],
313
 
            u"'fo''o b''ar'")
314
 
        self.assertAsTokens([(True, u'foo bar')], u'"fo""o b""ar"')
315
 
        self.assertAsTokens([(True, u"fo'o"), (True, u"b'ar")],
316
 
            u'"fo"\'o b\'"ar"')
317
 
 
318
 
    def test_nested_quotations(self):
319
 
        self.assertAsTokens([(True, u'foo"" bar')], u"\"foo\\\"\\\" bar\"")
320
 
        self.assertAsTokens([(True, u'foo\'\' bar')], u"\"foo'' bar\"")
321
 
 
322
 
    def test_empty_result(self):
323
 
        self.assertAsTokens([], u'')
324
 
        self.assertAsTokens([], u'    ')
325
 
 
326
 
    def test_quoted_empty(self):
327
 
        self.assertAsTokens([(True, '')], u'""')
328
 
        self.assertAsTokens([(False, u"''")], u"''")
329
 
 
330
 
    def test_unicode_chars(self):
331
 
        self.assertAsTokens([(False, u'f\xb5\xee'), (False, u'\u1234\u3456')],
332
 
                             u'f\xb5\xee \u1234\u3456')
333
 
 
334
 
    def test_newline_in_quoted_section(self):
335
 
        self.assertAsTokens([(True, u'foo\nbar\nbaz\n')], u'"foo\nbar\nbaz\n"')
336
 
 
337
 
    def test_escape_chars(self):
338
 
        self.assertAsTokens([(False, u'foo\\bar')], u'foo\\bar')
339
 
 
340
 
    def test_escape_quote(self):
341
 
        self.assertAsTokens([(True, u'foo"bar')], u'"foo\\"bar"')
342
 
 
343
 
    def test_double_escape(self):
344
 
        self.assertAsTokens([(True, u'foo\\bar')], u'"foo\\\\bar"')
345
 
        self.assertAsTokens([(False, u'foo\\\\bar')], u"foo\\\\bar")
346
 
 
347
 
 
348
310
class Test_CommandLineToArgv(tests.TestCaseInTempDir):
349
311
 
350
 
    def assertCommandLine(self, expected, line):
 
312
    def assertCommandLine(self, expected, line, argv=None,
 
313
            single_quotes_allowed=False):
351
314
        # Strictly speaking we should respect parameter order versus glob
352
315
        # expansions, but it's not really worth the effort here
353
 
        self.assertEqual(expected,
354
 
                         sorted(win32utils._command_line_to_argv(line)))
 
316
        if argv is None:
 
317
            argv = [line]
 
318
        argv = win32utils._command_line_to_argv(line, argv,
 
319
                single_quotes_allowed=single_quotes_allowed)
 
320
        self.assertEqual(expected, sorted(argv))
355
321
 
356
322
    def test_glob_paths(self):
357
323
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
367
333
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
368
334
        self.assertCommandLine([u'a/*.c'], '"a/*.c"')
369
335
        self.assertCommandLine([u"'a/*.c'"], "'a/*.c'")
 
336
        self.assertCommandLine([u'a/*.c'], "'a/*.c'",
 
337
            single_quotes_allowed=True)
370
338
 
371
339
    def test_slashes_changed(self):
372
340
        # Quoting doesn't change the supplied args
373
341
        self.assertCommandLine([u'a\\*.c'], '"a\\*.c"')
 
342
        self.assertCommandLine([u'a\\*.c'], "'a\\*.c'",
 
343
            single_quotes_allowed=True)
374
344
        # Expands the glob, but nothing matches, swaps slashes
375
345
        self.assertCommandLine([u'a/*.c'], 'a\\*.c')
376
346
        self.assertCommandLine([u'a/?.c'], 'a\\?.c')
377
347
        # No glob, doesn't touch slashes
378
348
        self.assertCommandLine([u'a\\foo.c'], 'a\\foo.c')
379
349
 
380
 
    def test_no_single_quote_supported(self):
 
350
    def test_single_quote_support(self):
381
351
        self.assertCommandLine(["add", "let's-do-it.txt"],
382
 
            "add let's-do-it.txt")
 
352
            "add let's-do-it.txt",
 
353
            ["add", "let's-do-it.txt"])
 
354
        self.expectFailure("Using single quotes breaks trimming from argv",
 
355
            self.assertCommandLine, ["add", "lets do it.txt"],
 
356
            "add 'lets do it.txt'", ["add", "'lets", "do", "it.txt'"],
 
357
            single_quotes_allowed=True)
383
358
 
384
359
    def test_case_insensitive_globs(self):
385
 
        self.requireFeature(tests.CaseInsCasePresFilenameFeature)
 
360
        if os.path.normcase("AbC") == "AbC":
 
361
            self.skip("Test requires case insensitive globbing function")
386
362
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
387
363
        self.assertCommandLine([u'A/b.c'], 'A/B*')
388
364
 
389
365
    def test_backslashes(self):
390
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
366
        self.requireFeature(backslashdir_feature)
391
367
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
392
368
        self.assertCommandLine([u'a/b.c'], 'a\\b*')
 
369
 
 
370
    def test_with_pdb(self):
 
371
        """Check stripping Python arguments before bzr script per lp:587868"""
 
372
        self.assertCommandLine([u"rocks"], "-m pdb rocks", ["rocks"])
 
373
        self.build_tree(['d/', 'd/f1', 'd/f2'])
 
374
        self.assertCommandLine([u"rm", u"x*"], "-m pdb rm x*", ["rm", u"x*"])
 
375
        self.assertCommandLine([u"add", u"d/f1", u"d/f2"], "-m pdb add d/*",
 
376
            ["add", u"d/*"])
 
377
 
 
378
 
 
379
class TestGetEnvironUnicode(tests.TestCase):
 
380
    """Tests for accessing the environment via the windows wide api"""
 
381
 
 
382
    _test_needs_features = [CtypesFeature, features.win32_feature]
 
383
 
 
384
    def setUp(self):
 
385
        super(TestGetEnvironUnicode, self).setUp()
 
386
        self.overrideEnv("TEST", "1")
 
387
 
 
388
    def test_get(self):
 
389
        """In the normal case behaves the same as os.environ access"""
 
390
        self.assertEqual("1", win32utils.get_environ_unicode("TEST"))
 
391
 
 
392
    def test_unset(self):
 
393
        """A variable not present in the environment gives None by default"""
 
394
        del os.environ["TEST"]
 
395
        self.assertIs(None, win32utils.get_environ_unicode("TEST"))
 
396
 
 
397
    def test_unset_default(self):
 
398
        """A variable not present in the environment gives passed default"""
 
399
        del os.environ["TEST"]
 
400
        self.assertIs("a", win32utils.get_environ_unicode("TEST", "a"))
 
401
 
 
402
    def test_unicode(self):
 
403
        """A non-ascii variable is returned as unicode"""
 
404
        unicode_val = u"\xa7" # non-ascii character present in many encodings
 
405
        try:
 
406
            bytes_val = unicode_val.encode(osutils.get_user_encoding())
 
407
        except UnicodeEncodeError:
 
408
            self.skip("Couldn't encode non-ascii string to place in environ")
 
409
        os.environ["TEST"] = bytes_val
 
410
        self.assertEqual(unicode_val, win32utils.get_environ_unicode("TEST"))
 
411
 
 
412
    def test_long(self):
 
413
        """A variable bigger than heuristic buffer size is still accessible"""
 
414
        big_val = "x" * (2<<10)
 
415
        os.environ["TEST"] = big_val
 
416
        self.assertEqual(big_val, win32utils.get_environ_unicode("TEST"))
 
417
 
 
418
    def test_unexpected_error(self):
 
419
        """An error from the underlying platform function is propogated"""
 
420
        ERROR_INVALID_PARAMETER = 87
 
421
        SetLastError = win32utils.ctypes.windll.kernel32.SetLastError
 
422
        def failer(*args, **kwargs):
 
423
            SetLastError(ERROR_INVALID_PARAMETER)
 
424
            return 0
 
425
        self.overrideAttr(win32utils.get_environ_unicode, "_c_function",
 
426
            failer)
 
427
        e = self.assertRaises(WindowsError,
 
428
            win32utils.get_environ_unicode, "TEST")
 
429
        self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER)