/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 breezy/tests/test_win32utils.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 18:59:44 UTC
  • mfrom: (7143.15.15 more-cleanups)
  • Revision ID: breezy.the.bot@gmail.com-20181116185944-biefv1sub37qfybm
Sprinkle some PEP8iness.

Merged from https://code.launchpad.net/~jelmer/brz/more-cleanups/+merge/358611

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2010 Canonical Ltd
 
1
# Copyright (C) 2007-2011, 2016 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
 
from bzrlib import (
 
21
from .. import (
21
22
    osutils,
22
23
    tests,
23
24
    win32utils,
24
25
    )
25
 
from bzrlib.tests import (
26
 
    Feature,
 
26
from . import (
27
27
    TestCase,
28
28
    TestCaseInTempDir,
29
29
    TestSkipped,
30
 
    UnicodeFilenameFeature,
31
 
    )
32
 
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')
 
30
    )
 
31
from .features import backslashdir_feature
 
32
from ..win32utils import glob_expand, get_app_path
 
33
from . import (
 
34
    features,
 
35
    )
 
36
 
 
37
 
 
38
Win32RegistryFeature = features.ModuleAvailableFeature('_winreg')
 
39
CtypesFeature = features.ModuleAvailableFeature('ctypes')
 
40
Win32comShellFeature = features.ModuleAvailableFeature('win32com.shell')
 
41
Win32ApiFeature = features.ModuleAvailableFeature('win32api')
70
42
 
71
43
 
72
44
# Tests
91
63
                         'd/', 'd/d1', 'd/d2', 'd/e/', 'd/e/e1'])
92
64
 
93
65
    def build_unicode_tree(self):
94
 
        self.requireFeature(UnicodeFilenameFeature)
 
66
        self.requireFeature(features.UnicodeFilenameFeature)
95
67
        self.build_tree([u'\u1234', u'\u1234\u1234', u'\u1235/',
96
68
                         u'\u1235/\u1235'])
97
69
 
102
74
        self._run_testset([
103
75
            # no wildcards
104
76
            [[u'a'], [u'a']],
105
 
            [[u'a', u'a' ], [u'a', u'a']],
 
77
            [[u'a', u'a'], [u'a', u'a']],
106
78
 
107
79
            [[u'd'], [u'd']],
108
80
            [[u'd/'], [u'd/']],
121
93
            ])
122
94
 
123
95
    def test_backslash_globbing(self):
124
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
96
        self.requireFeature(backslashdir_feature)
125
97
        self.build_ascii_tree()
126
98
        self._run_testset([
127
99
            [[u'd\\'], [u'd/']],
132
104
            ])
133
105
 
134
106
    def test_case_insensitive_globbing(self):
135
 
        self.requireFeature(tests.CaseInsCasePresFilenameFeature)
 
107
        if os.path.normcase("AbC") == "AbC":
 
108
            self.skipTest("Test requires case insensitive globbing function")
136
109
        self.build_ascii_tree()
137
110
        self._run_testset([
138
111
            [[u'A'], [u'A']],
164
137
            ])
165
138
 
166
139
    def test_unicode_backslashes(self):
167
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
140
        self.requireFeature(backslashdir_feature)
168
141
        self.build_unicode_tree()
169
142
        self._run_testset([
170
143
            # no wildcards
195
168
        for a in ('iexplore', 'iexplore.exe'):
196
169
            p = get_app_path(a)
197
170
            d, b = os.path.split(p)
198
 
            self.assertEquals('iexplore.exe', b.lower())
199
 
            self.assertNotEquals('', d)
 
171
            self.assertEqual('iexplore.exe', b.lower())
 
172
            self.assertNotEqual('', d)
200
173
 
201
174
    def test_wordpad(self):
202
175
        # typical windows users should have wordpad in the system
203
176
        # but there is problem: its path has the format REG_EXPAND_SZ
204
177
        # so naive attempt to get the path is not working
 
178
        self.requireFeature(Win32ApiFeature)
205
179
        for a in ('wordpad', 'wordpad.exe'):
206
180
            p = get_app_path(a)
207
181
            d, b = os.path.split(p)
208
 
            self.assertEquals('wordpad.exe', b.lower())
209
 
            self.assertNotEquals('', d)
 
182
            self.assertEqual('wordpad.exe', b.lower())
 
183
            self.assertNotEqual('', d)
210
184
 
211
185
    def test_not_existing(self):
212
186
        p = get_app_path('not-existing')
213
 
        self.assertEquals('not-existing', p)
 
187
        self.assertEqual('not-existing', p)
214
188
 
215
189
 
216
190
class TestLocationsCtypes(TestCase):
217
191
 
218
 
    _test_needs_features = [CtypesFeature]
 
192
    _test_needs_features = [CtypesFeature, features.win32_feature]
219
193
 
220
194
    def assertPathsEqual(self, p1, p2):
221
195
        # TODO: The env var values in particular might return the "short"
222
196
        # version (ie, "C:\DOCUME~1\...").  Its even possible the returned
223
197
        # values will differ only by case - handle these situations as we
224
198
        # come across them.
225
 
        self.assertEquals(p1, p2)
 
199
        self.assertEqual(p1, p2)
226
200
 
227
201
    def test_appdata_not_using_environment(self):
228
202
        # Test that we aren't falling back to the environment
229
203
        first = win32utils.get_appdata_location()
230
 
        self._captureVar("APPDATA", None)
 
204
        self.overrideEnv("APPDATA", None)
231
205
        self.assertPathsEqual(first, win32utils.get_appdata_location())
232
206
 
233
207
    def test_appdata_matches_environment(self):
244
218
    def test_local_appdata_not_using_environment(self):
245
219
        # Test that we aren't falling back to the environment
246
220
        first = win32utils.get_local_appdata_location()
247
 
        self._captureVar("LOCALAPPDATA", None)
 
221
        self.overrideEnv("LOCALAPPDATA", None)
248
222
        self.assertPathsEqual(first, win32utils.get_local_appdata_location())
249
223
 
250
224
    def test_local_appdata_matches_environment(self):
253
227
        lad = win32utils.get_local_appdata_location()
254
228
        env = os.environ.get("LOCALAPPDATA")
255
229
        if env:
256
 
            # XXX - See bug 262874, which asserts the correct encoding is 'mbcs'
 
230
            # XXX - See bug 262874, which asserts the correct encoding is
 
231
            # 'mbcs'
257
232
            encoding = osutils.get_user_encoding()
258
233
            self.assertPathsEqual(lad, env.decode(encoding))
259
234
 
274
249
 
275
250
    def test_unicode_dir(self):
276
251
        # we should handle unicode paths without errors
277
 
        self.requireFeature(UnicodeFilenameFeature)
 
252
        self.requireFeature(features.UnicodeFilenameFeature)
278
253
        os.mkdir(u'\u1234')
279
254
        win32utils.set_file_attr_hidden(u'\u1234')
280
255
 
281
256
    def test_dot_bzr_in_unicode_dir(self):
282
257
        # we should not raise traceback if we try to set hidden attribute
283
258
        # on .bzr directory below unicode path
284
 
        self.requireFeature(UnicodeFilenameFeature)
 
259
        self.requireFeature(features.UnicodeFilenameFeature)
285
260
        os.makedirs(u'\u1234\\.bzr')
286
261
        path = osutils.abspath(u'\u1234\\.bzr')
287
262
        win32utils.set_file_attr_hidden(path)
288
263
 
289
264
 
290
 
 
291
 
 
292
265
class Test_CommandLineToArgv(tests.TestCaseInTempDir):
293
266
 
294
 
    def assertCommandLine(self, expected, line, single_quotes_allowed=False):
 
267
    def assertCommandLine(self, expected, line, argv=None,
 
268
                          single_quotes_allowed=False):
295
269
        # Strictly speaking we should respect parameter order versus glob
296
270
        # expansions, but it's not really worth the effort here
297
 
        argv = win32utils._command_line_to_argv(line,
298
 
                single_quotes_allowed=single_quotes_allowed)
 
271
        if argv is None:
 
272
            argv = [line]
 
273
        argv = win32utils._command_line_to_argv(
 
274
            line, argv, single_quotes_allowed=single_quotes_allowed)
299
275
        self.assertEqual(expected, sorted(argv))
300
276
 
301
277
    def test_glob_paths(self):
313
289
        self.assertCommandLine([u'a/*.c'], '"a/*.c"')
314
290
        self.assertCommandLine([u"'a/*.c'"], "'a/*.c'")
315
291
        self.assertCommandLine([u'a/*.c'], "'a/*.c'",
316
 
            single_quotes_allowed=True)
 
292
                               single_quotes_allowed=True)
317
293
 
318
294
    def test_slashes_changed(self):
319
295
        # Quoting doesn't change the supplied args
320
296
        self.assertCommandLine([u'a\\*.c'], '"a\\*.c"')
321
297
        self.assertCommandLine([u'a\\*.c'], "'a\\*.c'",
322
 
            single_quotes_allowed=True)
 
298
                               single_quotes_allowed=True)
323
299
        # Expands the glob, but nothing matches, swaps slashes
324
300
        self.assertCommandLine([u'a/*.c'], 'a\\*.c')
325
301
        self.assertCommandLine([u'a/?.c'], 'a\\?.c')
328
304
 
329
305
    def test_single_quote_support(self):
330
306
        self.assertCommandLine(["add", "let's-do-it.txt"],
331
 
            "add let's-do-it.txt")
332
 
        self.assertCommandLine(["add", "lets do it.txt"],
333
 
            "add 'lets do it.txt'", single_quotes_allowed=True)
 
307
                               "add let's-do-it.txt",
 
308
                               ["add", "let's-do-it.txt"])
 
309
        self.expectFailure("Using single quotes breaks trimming from argv",
 
310
                           self.assertCommandLine, ["add", "lets do it.txt"],
 
311
                           "add 'lets do it.txt'", [
 
312
                               "add", "'lets", "do", "it.txt'"],
 
313
                           single_quotes_allowed=True)
334
314
 
335
315
    def test_case_insensitive_globs(self):
336
 
        self.requireFeature(tests.CaseInsCasePresFilenameFeature)
 
316
        if os.path.normcase("AbC") == "AbC":
 
317
            self.skipTest("Test requires case insensitive globbing function")
337
318
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
338
319
        self.assertCommandLine([u'A/b.c'], 'A/B*')
339
320
 
340
321
    def test_backslashes(self):
341
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
322
        self.requireFeature(backslashdir_feature)
342
323
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
343
324
        self.assertCommandLine([u'a/b.c'], 'a\\b*')
 
325
 
 
326
    def test_with_pdb(self):
 
327
        """Check stripping Python arguments before bzr script per lp:587868"""
 
328
        self.assertCommandLine([u"rocks"], "-m pdb rocks", ["rocks"])
 
329
        self.build_tree(['d/', 'd/f1', 'd/f2'])
 
330
        self.assertCommandLine([u"rm", u"x*"], "-m pdb rm x*", ["rm", u"x*"])
 
331
        self.assertCommandLine([u"add", u"d/f1", u"d/f2"], "-m pdb add d/*",
 
332
                               ["add", u"d/*"])
 
333
 
 
334
 
 
335
class TestGetEnvironUnicode(tests.TestCase):
 
336
    """Tests for accessing the environment via the windows wide api"""
 
337
 
 
338
    _test_needs_features = [CtypesFeature, features.win32_feature]
 
339
 
 
340
    def setUp(self):
 
341
        super(TestGetEnvironUnicode, self).setUp()
 
342
        self.overrideEnv("TEST", "1")
 
343
 
 
344
    def test_get(self):
 
345
        """In the normal case behaves the same as os.environ access"""
 
346
        self.assertEqual("1", win32utils.get_environ_unicode("TEST"))
 
347
 
 
348
    def test_unset(self):
 
349
        """A variable not present in the environment gives None by default"""
 
350
        del os.environ["TEST"]
 
351
        self.assertIs(None, win32utils.get_environ_unicode("TEST"))
 
352
 
 
353
    def test_unset_default(self):
 
354
        """A variable not present in the environment gives passed default"""
 
355
        del os.environ["TEST"]
 
356
        self.assertIs("a", win32utils.get_environ_unicode("TEST", "a"))
 
357
 
 
358
    def test_unicode(self):
 
359
        """A non-ascii variable is returned as unicode"""
 
360
        unicode_val = u"\xa7"  # non-ascii character present in many encodings
 
361
        try:
 
362
            bytes_val = unicode_val.encode(osutils.get_user_encoding())
 
363
        except UnicodeEncodeError:
 
364
            self.skipTest("Couldn't encode non-ascii string for environ")
 
365
        os.environ["TEST"] = bytes_val
 
366
        self.assertEqual(unicode_val, win32utils.get_environ_unicode("TEST"))
 
367
 
 
368
    def test_long(self):
 
369
        """A variable bigger than heuristic buffer size is still accessible"""
 
370
        big_val = "x" * (2 << 10)
 
371
        os.environ["TEST"] = big_val
 
372
        self.assertEqual(big_val, win32utils.get_environ_unicode("TEST"))
 
373
 
 
374
    def test_unexpected_error(self):
 
375
        """An error from the underlying platform function is propogated"""
 
376
        ERROR_INVALID_PARAMETER = 87
 
377
        SetLastError = win32utils.ctypes.windll.kernel32.SetLastError
 
378
 
 
379
        def failer(*args, **kwargs):
 
380
            SetLastError(ERROR_INVALID_PARAMETER)
 
381
            return 0
 
382
        self.overrideAttr(win32utils.get_environ_unicode, "_c_function",
 
383
                          failer)
 
384
        e = self.assertRaises(WindowsError,
 
385
                              win32utils.get_environ_unicode, "TEST")
 
386
        self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER)