/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: Jelmer Vernooij
  • Date: 2018-07-08 14:45:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7036.
  • Revision ID: jelmer@jelmer.uk-20180708144527-codhlvdcdg9y0nji
Fix a bunch of merge tests.

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,
 
23
    symbol_versioning,
22
24
    tests,
23
25
    win32utils,
24
26
    )
25
 
from bzrlib.tests import (
26
 
    Feature,
 
27
from . import (
27
28
    TestCase,
28
29
    TestCaseInTempDir,
29
30
    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')
 
31
    )
 
32
from .features import backslashdir_feature
 
33
from ..win32utils import glob_expand, get_app_path
 
34
from . 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.skipTest("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
195
169
        for a in ('iexplore', 'iexplore.exe'):
196
170
            p = get_app_path(a)
197
171
            d, b = os.path.split(p)
198
 
            self.assertEquals('iexplore.exe', b.lower())
199
 
            self.assertNotEquals('', d)
 
172
            self.assertEqual('iexplore.exe', b.lower())
 
173
            self.assertNotEqual('', d)
200
174
 
201
175
    def test_wordpad(self):
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)
208
 
            self.assertEquals('wordpad.exe', b.lower())
209
 
            self.assertNotEquals('', d)
 
183
            self.assertEqual('wordpad.exe', b.lower())
 
184
            self.assertNotEqual('', d)
210
185
 
211
186
    def test_not_existing(self):
212
187
        p = get_app_path('not-existing')
213
 
        self.assertEquals('not-existing', p)
 
188
        self.assertEqual('not-existing', p)
214
189
 
215
190
 
216
191
class TestLocationsCtypes(TestCase):
217
192
 
218
 
    _test_needs_features = [CtypesFeature]
 
193
    _test_needs_features = [CtypesFeature, features.win32_feature]
219
194
 
220
195
    def assertPathsEqual(self, p1, p2):
221
196
        # TODO: The env var values in particular might return the "short"
222
197
        # version (ie, "C:\DOCUME~1\...").  Its even possible the returned
223
198
        # values will differ only by case - handle these situations as we
224
199
        # come across them.
225
 
        self.assertEquals(p1, p2)
 
200
        self.assertEqual(p1, p2)
226
201
 
227
202
    def test_appdata_not_using_environment(self):
228
203
        # Test that we aren't falling back to the environment
229
204
        first = win32utils.get_appdata_location()
230
 
        self._captureVar("APPDATA", None)
 
205
        self.overrideEnv("APPDATA", None)
231
206
        self.assertPathsEqual(first, win32utils.get_appdata_location())
232
207
 
233
208
    def test_appdata_matches_environment(self):
244
219
    def test_local_appdata_not_using_environment(self):
245
220
        # Test that we aren't falling back to the environment
246
221
        first = win32utils.get_local_appdata_location()
247
 
        self._captureVar("LOCALAPPDATA", None)
 
222
        self.overrideEnv("LOCALAPPDATA", None)
248
223
        self.assertPathsEqual(first, win32utils.get_local_appdata_location())
249
224
 
250
225
    def test_local_appdata_matches_environment(self):
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,
 
271
        if argv is None:
 
272
            argv = [line]
 
273
        argv = win32utils._command_line_to_argv(line, argv,
298
274
                single_quotes_allowed=single_quotes_allowed)
299
275
        self.assertEqual(expected, sorted(argv))
300
276
 
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'", ["add", "'lets", "do", "it.txt'"],
 
312
            single_quotes_allowed=True)
334
313
 
335
314
    def test_case_insensitive_globs(self):
336
 
        self.requireFeature(tests.CaseInsCasePresFilenameFeature)
 
315
        if os.path.normcase("AbC") == "AbC":
 
316
            self.skipTest("Test requires case insensitive globbing function")
337
317
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
338
318
        self.assertCommandLine([u'A/b.c'], 'A/B*')
339
319
 
340
320
    def test_backslashes(self):
341
 
        self.requireFeature(BackslashDirSeparatorFeature)
 
321
        self.requireFeature(backslashdir_feature)
342
322
        self.build_tree(['a/', 'a/b.c', 'a/c.c', 'a/c.h'])
343
323
        self.assertCommandLine([u'a/b.c'], 'a\\b*')
 
324
 
 
325
    def test_with_pdb(self):
 
326
        """Check stripping Python arguments before bzr script per lp:587868"""
 
327
        self.assertCommandLine([u"rocks"], "-m pdb rocks", ["rocks"])
 
328
        self.build_tree(['d/', 'd/f1', 'd/f2'])
 
329
        self.assertCommandLine([u"rm", u"x*"], "-m pdb rm x*", ["rm", u"x*"])
 
330
        self.assertCommandLine([u"add", u"d/f1", u"d/f2"], "-m pdb add d/*",
 
331
            ["add", u"d/*"])
 
332
 
 
333
 
 
334
class TestGetEnvironUnicode(tests.TestCase):
 
335
    """Tests for accessing the environment via the windows wide api"""
 
336
 
 
337
    _test_needs_features = [CtypesFeature, features.win32_feature]
 
338
 
 
339
    def setUp(self):
 
340
        super(TestGetEnvironUnicode, self).setUp()
 
341
        self.overrideEnv("TEST", "1")
 
342
 
 
343
    def test_get(self):
 
344
        """In the normal case behaves the same as os.environ access"""
 
345
        self.assertEqual("1", win32utils.get_environ_unicode("TEST"))
 
346
 
 
347
    def test_unset(self):
 
348
        """A variable not present in the environment gives None by default"""
 
349
        del os.environ["TEST"]
 
350
        self.assertIs(None, win32utils.get_environ_unicode("TEST"))
 
351
 
 
352
    def test_unset_default(self):
 
353
        """A variable not present in the environment gives passed default"""
 
354
        del os.environ["TEST"]
 
355
        self.assertIs("a", win32utils.get_environ_unicode("TEST", "a"))
 
356
 
 
357
    def test_unicode(self):
 
358
        """A non-ascii variable is returned as unicode"""
 
359
        unicode_val = u"\xa7" # non-ascii character present in many encodings
 
360
        try:
 
361
            bytes_val = unicode_val.encode(osutils.get_user_encoding())
 
362
        except UnicodeEncodeError:
 
363
            self.skipTest("Couldn't encode non-ascii string for environ")
 
364
        os.environ["TEST"] = bytes_val
 
365
        self.assertEqual(unicode_val, win32utils.get_environ_unicode("TEST"))
 
366
 
 
367
    def test_long(self):
 
368
        """A variable bigger than heuristic buffer size is still accessible"""
 
369
        big_val = "x" * (2<<10)
 
370
        os.environ["TEST"] = big_val
 
371
        self.assertEqual(big_val, win32utils.get_environ_unicode("TEST"))
 
372
 
 
373
    def test_unexpected_error(self):
 
374
        """An error from the underlying platform function is propogated"""
 
375
        ERROR_INVALID_PARAMETER = 87
 
376
        SetLastError = win32utils.ctypes.windll.kernel32.SetLastError
 
377
        def failer(*args, **kwargs):
 
378
            SetLastError(ERROR_INVALID_PARAMETER)
 
379
            return 0
 
380
        self.overrideAttr(win32utils.get_environ_unicode, "_c_function",
 
381
            failer)
 
382
        e = self.assertRaises(WindowsError,
 
383
            win32utils.get_environ_unicode, "TEST")
 
384
        self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER)