/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2005-2011 Canonical Ltd
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
16
17
"""Tests for finding and reading the bzr config file[s]."""
18
# import system imports here
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
19
from cStringIO import StringIO
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
20
import os
21
import sys
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
22
import threading
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
23
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
24
25
from testtools import matchers
26
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
27
#import bzrlib specific imports here
1878.1.3 by John Arbash Meinel
some test cleanups
28
from bzrlib import (
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
29
    branch,
30
    bzrdir,
1878.1.3 by John Arbash Meinel
some test cleanups
31
    config,
4603.1.10 by Aaron Bentley
Provide change editor via config.
32
    diff,
1878.1.3 by John Arbash Meinel
some test cleanups
33
    errors,
34
    osutils,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
35
    mail_client,
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
36
    mergetools,
2900.2.14 by Vincent Ladeuil
More tests.
37
    ui,
1878.1.3 by John Arbash Meinel
some test cleanups
38
    urlutils,
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
39
    tests,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
40
    trace,
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
41
    transport,
1878.1.3 by John Arbash Meinel
some test cleanups
42
    )
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
43
from bzrlib.tests import (
44
    features,
45
    TestSkipped,
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
46
    scenarios,
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
47
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
48
from bzrlib.util.configobj import configobj
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
49
50
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
51
def lockable_config_scenarios():
52
    return [
53
        ('global',
54
         {'config_class': config.GlobalConfig,
55
          'config_args': [],
56
          'config_section': 'DEFAULT'}),
57
        ('locations',
58
         {'config_class': config.LocationConfig,
59
          'config_args': ['.'],
60
          'config_section': '.'}),]
61
62
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
63
load_tests = scenarios.load_tests_apply_scenarios
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
64
65
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
66
sample_long_alias="log -r-15..-1 --line"
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
67
sample_config_text = u"""
68
[DEFAULT]
69
email=Erik B\u00e5gfors <erik@bagfors.nu>
70
editor=vim
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
71
change_editor=vimdiff -of @new_path @old_path
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
72
gpg_signing_command=gnome-gpg
73
log_format=short
74
user_global_option=something
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
75
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
5321.2.3 by Vincent Ladeuil
Prefix mergetools option names with 'bzr.'.
76
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
77
bzr.default_mergetool=sometool
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
78
[ALIASES]
79
h=help
80
ll=""" + sample_long_alias + "\n"
81
82
83
sample_always_signatures = """
84
[DEFAULT]
85
check_signatures=ignore
86
create_signatures=always
87
"""
88
89
sample_ignore_signatures = """
90
[DEFAULT]
91
check_signatures=require
92
create_signatures=never
93
"""
94
95
sample_maybe_signatures = """
96
[DEFAULT]
97
check_signatures=ignore
98
create_signatures=when-required
99
"""
100
101
sample_branches_text = """
102
[http://www.example.com]
103
# Top level policy
104
email=Robert Collins <robertc@example.org>
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
105
normal_option = normal
106
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
107
appendpath_option:policy = appendpath
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
108
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
109
norecurse_option:policy = norecurse
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
110
[http://www.example.com/ignoreparent]
111
# different project: ignore parent dir config
112
ignore_parents=true
113
[http://www.example.com/norecurse]
114
# configuration items that only apply to this dir
115
recurse=false
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
116
normal_option = norecurse
117
[http://www.example.com/dir]
118
appendpath_option = normal
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
119
[/b/]
120
check_signatures=require
121
# test trailing / matching with no children
122
[/a/]
123
check_signatures=check-available
124
gpg_signing_command=false
125
user_local_option=local
126
# test trailing / matching
127
[/a/*]
128
#subdirs will match but not the parent
129
[/a/c]
130
check_signatures=ignore
131
post_commit=bzrlib.tests.test_config.post_commit
132
#testing explicit beats globs
133
"""
1553.6.3 by Erik Bågfors
tests for AliasesConfig
134
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
135
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
136
def create_configs(test):
137
    """Create configuration files for a given test.
138
139
    This requires creating a tree (and populate the ``test.tree`` attribute)
140
    and its associated branch and will populate the following attributes:
141
142
    - branch_config: A BranchConfig for the associated branch.
143
144
    - locations_config : A LocationConfig for the associated branch
145
146
    - bazaar_config: A GlobalConfig.
147
148
    The tree and branch are created in a 'tree' subdirectory so the tests can
149
    still use the test directory to stay outside of the branch.
150
    """
151
    tree = test.make_branch_and_tree('tree')
152
    test.tree = tree
153
    test.branch_config = config.BranchConfig(tree.branch)
154
    test.locations_config = config.LocationConfig(tree.basedir)
155
    test.bazaar_config = config.GlobalConfig()
156
5533.2.4 by Vincent Ladeuil
Fix whitespace issue.
157
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
158
def create_configs_with_file_option(test):
159
    """Create configuration files with a ``file`` option set in each.
160
161
    This builds on ``create_configs`` and add one ``file`` option in each
162
    configuration with a value which allows identifying the configuration file.
163
    """
164
    create_configs(test)
165
    test.bazaar_config.set_user_option('file', 'bazaar')
166
    test.locations_config.set_user_option('file', 'locations')
167
    test.branch_config.set_user_option('file', 'branch')
168
169
170
class TestOptionsMixin:
171
172
    def assertOptions(self, expected, conf):
173
        # We don't care about the parser (as it will make tests hard to write
174
        # and error-prone anyway)
175
        self.assertThat([opt[:4] for opt in conf._get_options()],
176
                        matchers.Equals(expected))
177
178
1474 by Robert Collins
Merge from Aaron Bentley.
179
class InstrumentedConfigObj(object):
180
    """A config obj look-enough-alike to record calls made to it."""
181
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
182
    def __contains__(self, thing):
183
        self._calls.append(('__contains__', thing))
184
        return False
185
186
    def __getitem__(self, key):
187
        self._calls.append(('__getitem__', key))
188
        return self
189
1551.2.20 by Aaron Bentley
Treated config files as utf-8
190
    def __init__(self, input, encoding=None):
191
        self._calls = [('__init__', input, encoding)]
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
192
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
193
    def __setitem__(self, key, value):
194
        self._calls.append(('__setitem__', key, value))
195
2120.6.4 by James Henstridge
add support for specifying policy when storing options
196
    def __delitem__(self, key):
197
        self._calls.append(('__delitem__', key))
198
199
    def keys(self):
200
        self._calls.append(('keys',))
201
        return []
202
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
203
    def reload(self):
204
        self._calls.append(('reload',))
205
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
206
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
207
        self._calls.append(('write',))
208
2120.6.4 by James Henstridge
add support for specifying policy when storing options
209
    def as_bool(self, value):
210
        self._calls.append(('as_bool', value))
211
        return False
212
213
    def get_value(self, section, name):
214
        self._calls.append(('get_value', section, name))
215
        return None
216
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
217
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
218
class FakeBranch(object):
219
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
220
    def __init__(self, base=None, user_id=None):
221
        if base is None:
222
            self.base = "http://example.com/branches/demo"
223
        else:
224
            self.base = base
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
225
        self._transport = self.control_files = \
226
            FakeControlFilesAndTransport(user_id=user_id)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
227
4226.1.7 by Robert Collins
Alter test_config.FakeBranch in accordance with the Branch change to have a _get_config.
228
    def _get_config(self):
229
        return config.TransportConfig(self._transport, 'branch.conf')
230
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
231
    def lock_write(self):
232
        pass
233
234
    def unlock(self):
235
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
236
237
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
238
class FakeControlFilesAndTransport(object):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
239
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
240
    def __init__(self, user_id=None):
241
        self.files = {}
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
242
        if user_id:
243
            self.files['email'] = user_id
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
244
        self._transport = self
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
245
1185.65.29 by Robert Collins
Implement final review suggestions.
246
    def get_utf8(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
247
        # from LockableFiles
248
        raise AssertionError("get_utf8 should no longer be used")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
249
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
250
    def get(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
251
        # from Transport
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
252
        try:
253
            return StringIO(self.files[filename])
254
        except KeyError:
255
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
256
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
257
    def get_bytes(self, filename):
258
        # from Transport
259
        try:
260
            return self.files[filename]
261
        except KeyError:
262
            raise errors.NoSuchFile(filename)
263
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
264
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
265
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
266
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
267
    def put_file(self, filename, fileobj):
268
        return self.put(filename, fileobj)
269
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
270
271
class InstrumentedConfig(config.Config):
272
    """An instrumented config that supplies stubs for template methods."""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
273
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
274
    def __init__(self):
275
        super(InstrumentedConfig, self).__init__()
276
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
277
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
278
279
    def _get_user_id(self):
280
        self._calls.append('_get_user_id')
281
        return "Robert Collins <robert.collins@example.org>"
282
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
283
    def _get_signature_checking(self):
284
        self._calls.append('_get_signature_checking')
285
        return self._signatures
286
4603.1.10 by Aaron Bentley
Provide change editor via config.
287
    def _get_change_editor(self):
288
        self._calls.append('_get_change_editor')
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
289
        return 'vimdiff -fo @new_path @old_path'
4603.1.10 by Aaron Bentley
Provide change editor via config.
290
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
291
1556.2.2 by Aaron Bentley
Fixed get_bool
292
bool_config = """[DEFAULT]
293
active = true
294
inactive = false
295
[UPPERCASE]
296
active = True
297
nonactive = False
298
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
299
300
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
301
class TestConfigObj(tests.TestCase):
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
302
1556.2.2 by Aaron Bentley
Fixed get_bool
303
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
304
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
305
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
306
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
307
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
308
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
309
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
310
    def test_hash_sign_in_value(self):
311
        """
312
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
313
        treated as comments when read in again. (#86838)
314
        """
315
        co = config.ConfigObj()
316
        co['test'] = 'foo#bar'
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
317
        outfile = StringIO()
318
        co.write(outfile=outfile)
319
        lines = outfile.getvalue().splitlines()
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
320
        self.assertEqual(lines, ['test = "foo#bar"'])
321
        co2 = config.ConfigObj(lines)
322
        self.assertEqual(co2['test'], 'foo#bar')
323
5050.62.10 by Alexander Belchenko
test to illustrate the problem
324
    def test_triple_quotes(self):
325
        # Bug #710410: if the value string has triple quotes
326
        # then ConfigObj versions up to 4.7.2 will quote them wrong
5050.62.12 by Alexander Belchenko
added NEWS entry
327
        # and won't able to read them back
5050.62.10 by Alexander Belchenko
test to illustrate the problem
328
        triple_quotes_value = '''spam
329
""" that's my spam """
330
eggs'''
331
        co = config.ConfigObj()
332
        co['test'] = triple_quotes_value
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
333
        # While writing this test another bug in ConfigObj has been found:
5050.62.10 by Alexander Belchenko
test to illustrate the problem
334
        # method co.write() without arguments produces list of lines
335
        # one option per line, and multiline values are not split
336
        # across multiple lines,
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
337
        # and that breaks the parsing these lines back by ConfigObj.
338
        # This issue only affects test, but it's better to avoid
339
        # `co.write()` construct at all.
340
        # [bialix 20110222] bug report sent to ConfigObj's author
5050.62.10 by Alexander Belchenko
test to illustrate the problem
341
        outfile = StringIO()
342
        co.write(outfile=outfile)
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
343
        output = outfile.getvalue()
5050.62.10 by Alexander Belchenko
test to illustrate the problem
344
        # now we're trying to read it back
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
345
        co2 = config.ConfigObj(StringIO(output))
5050.62.10 by Alexander Belchenko
test to illustrate the problem
346
        self.assertEquals(triple_quotes_value, co2['test'])
347
1556.2.2 by Aaron Bentley
Fixed get_bool
348
2900.1.1 by Vincent Ladeuil
349
erroneous_config = """[section] # line 1
350
good=good # line 2
351
[section] # line 3
352
whocares=notme # line 4
353
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
354
355
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
356
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
357
358
    def test_duplicate_section_name_error_line(self):
359
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
360
            co = configobj.ConfigObj(StringIO(erroneous_config),
361
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
362
        except config.configobj.DuplicateError, e:
363
            self.assertEqual(3, e.line_number)
364
        else:
365
            self.fail('Error in config file not detected')
366
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
367
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
368
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
369
370
    def test_constructs(self):
371
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
372
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
373
    def test_no_default_editor(self):
374
        self.assertRaises(NotImplementedError, config.Config().get_editor)
375
376
    def test_user_email(self):
377
        my_config = InstrumentedConfig()
378
        self.assertEqual('robert.collins@example.org', my_config.user_email())
379
        self.assertEqual(['_get_user_id'], my_config._calls)
380
381
    def test_username(self):
382
        my_config = InstrumentedConfig()
383
        self.assertEqual('Robert Collins <robert.collins@example.org>',
384
                         my_config.username())
385
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
386
387
    def test_signatures_default(self):
388
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
389
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
390
        self.assertEqual(config.CHECK_IF_POSSIBLE,
391
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
392
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
393
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
394
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
395
    def test_signatures_template_method(self):
396
        my_config = InstrumentedConfig()
397
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
398
        self.assertEqual(['_get_signature_checking'], my_config._calls)
399
400
    def test_signatures_template_method_none(self):
401
        my_config = InstrumentedConfig()
402
        my_config._signatures = None
403
        self.assertEqual(config.CHECK_IF_POSSIBLE,
404
                         my_config.signature_checking())
405
        self.assertEqual(['_get_signature_checking'], my_config._calls)
406
1442.1.56 by Robert Collins
gpg_signing_command configuration item
407
    def test_gpg_signing_command_default(self):
408
        my_config = config.Config()
409
        self.assertEqual('gpg', my_config.gpg_signing_command())
410
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
411
    def test_get_user_option_default(self):
412
        my_config = config.Config()
413
        self.assertEqual(None, my_config.get_user_option('no_option'))
414
1472 by Robert Collins
post commit hook, first pass implementation
415
    def test_post_commit_default(self):
416
        my_config = config.Config()
417
        self.assertEqual(None, my_config.post_commit())
418
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
419
    def test_log_format_default(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
420
        my_config = config.Config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
421
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
422
4603.1.10 by Aaron Bentley
Provide change editor via config.
423
    def test_get_change_editor(self):
424
        my_config = InstrumentedConfig()
425
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
426
        self.assertEqual(['_get_change_editor'], my_config._calls)
427
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
428
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
4603.1.10 by Aaron Bentley
Provide change editor via config.
429
                         change_editor.command_template)
430
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
431
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
432
class TestConfigPath(tests.TestCase):
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
433
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
434
    def setUp(self):
435
        super(TestConfigPath, self).setUp()
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
436
        self.overrideEnv('HOME', '/home/bogus')
437
        self.overrideEnv('XDG_CACHE_DIR', '')
2309.2.6 by Alexander Belchenko
bzr now use Win32 API to determine Application Data location, and don't rely solely on $APPDATA
438
        if sys.platform == 'win32':
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
439
            self.overrideEnv(
440
                'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
441
            self.bzr_home = \
442
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
5519.4.3 by Neil Martinsen-Burrell
be permissive about using $XDG_CONFIG_HOME/bazaar, but dont complain
443
        else:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
444
            self.bzr_home = '/home/bogus/.bazaar'
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
445
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
446
    def test_config_dir(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
447
        self.assertEqual(config.config_dir(), self.bzr_home)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
448
449
    def test_config_filename(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
450
        self.assertEqual(config.config_filename(),
451
                         self.bzr_home + '/bazaar.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
452
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
453
    def test_locations_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
454
        self.assertEqual(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
455
                         self.bzr_home + '/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
456
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
457
    def test_authentication_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
458
        self.assertEqual(config.authentication_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
459
                         self.bzr_home + '/authentication.conf')
460
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
461
    def test_xdg_cache_dir(self):
462
        self.assertEqual(config.xdg_cache_dir(),
463
            '/home/bogus/.cache')
464
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
465
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
466
class TestXDGConfigDir(tests.TestCaseInTempDir):
467
    # must be in temp dir because config tests for the existence of the bazaar
468
    # subdirectory of $XDG_CONFIG_HOME
469
5519.4.9 by Neil Martinsen-Burrell
working tests
470
    def setUp(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
471
        if sys.platform in ('darwin', 'win32'):
472
            raise tests.TestNotApplicable(
473
                'XDG config dir not used on this platform')
5519.4.9 by Neil Martinsen-Burrell
working tests
474
        super(TestXDGConfigDir, self).setUp()
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
475
        self.overrideEnv('HOME', self.test_home_dir)
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
476
        # BZR_HOME overrides everything we want to test so unset it.
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
477
        self.overrideEnv('BZR_HOME', None)
5519.4.9 by Neil Martinsen-Burrell
working tests
478
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
479
    def test_xdg_config_dir_exists(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
480
        """When ~/.config/bazaar exists, use it as the config dir."""
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
481
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
482
        os.makedirs(newdir)
483
        self.assertEqual(config.config_dir(), newdir)
484
485
    def test_xdg_config_home(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
486
        """When XDG_CONFIG_HOME is set, use it."""
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
487
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
488
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
489
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
490
        os.makedirs(newdir)
491
        self.assertEqual(config.config_dir(), newdir)
492
493
5050.13.2 by Parth Malwankar
copy config file ownership only if a new file is created
494
class TestIniConfig(tests.TestCaseInTempDir):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
495
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
496
    def make_config_parser(self, s):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
497
        conf = config.IniBasedConfig.from_string(s)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
498
        return conf, conf._get_parser()
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
499
5050.13.2 by Parth Malwankar
copy config file ownership only if a new file is created
500
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
501
class TestIniConfigBuilding(TestIniConfig):
502
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
503
    def test_contructs(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
504
        my_config = config.IniBasedConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
505
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
506
    def test_from_fp(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
507
        my_config = config.IniBasedConfig.from_string(sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
508
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
509
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
510
    def test_cached(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
511
        my_config = config.IniBasedConfig.from_string(sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
512
        parser = my_config._get_parser()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
513
        self.failUnless(my_config._get_parser() is parser)
514
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
515
    def _dummy_chown(self, path, uid, gid):
516
        self.path, self.uid, self.gid = path, uid, gid
517
518
    def test_ini_config_ownership(self):
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
519
        """Ensure that chown is happening during _write_config_file"""
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
520
        self.requireFeature(features.chown_feature)
521
        self.overrideAttr(os, 'chown', self._dummy_chown)
522
        self.path = self.uid = self.gid = None
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
523
        conf = config.IniBasedConfig(file_name='./foo.conf')
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
524
        conf._write_config_file()
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
525
        self.assertEquals(self.path, './foo.conf')
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
526
        self.assertTrue(isinstance(self.uid, int))
527
        self.assertTrue(isinstance(self.gid, int))
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
528
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
529
    def test_get_filename_parameter_is_deprecated_(self):
530
        conf = self.callDeprecated([
531
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
532
            ' Use file_name instead.'],
533
            config.IniBasedConfig, lambda: 'ini.conf')
5345.3.1 by Vincent Ladeuil
Check that _get_filename() is called and produces the desired side effect.
534
        self.assertEqual('ini.conf', conf.file_name)
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
535
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
536
    def test_get_parser_file_parameter_is_deprecated_(self):
537
        config_file = StringIO(sample_config_text.encode('utf-8'))
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
538
        conf = config.IniBasedConfig.from_string(sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
539
        conf = self.callDeprecated([
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
540
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
541
            ' Use IniBasedConfig(_content=xxx) instead.'],
542
            conf._get_parser, file=config_file)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
543
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
544
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
545
class TestIniConfigSaving(tests.TestCaseInTempDir):
546
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
547
    def test_cant_save_without_a_file_name(self):
548
        conf = config.IniBasedConfig()
549
        self.assertRaises(AssertionError, conf._write_config_file)
550
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
551
    def test_saved_with_content(self):
552
        content = 'foo = bar\n'
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
553
        conf = config.IniBasedConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
554
            content, file_name='./test.conf', save=True)
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
555
        self.assertFileEqual(content, 'test.conf')
556
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
557
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
558
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
559
    """What is the default value of expand for config options.
560
561
    This is an opt-in beta feature used to evaluate whether or not option
562
    references can appear in dangerous place raising exceptions, disapearing
563
    (and as such corrupting data) or if it's safe to activate the option by
564
    default.
565
566
    Note that these tests relies on config._expand_default_value being already
567
    overwritten in the parent class setUp.
568
    """
569
570
    def setUp(self):
571
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
572
        self.config = None
573
        self.warnings = []
574
        def warning(*args):
575
            self.warnings.append(args[0] % args[1:])
576
        self.overrideAttr(trace, 'warning', warning)
577
578
    def get_config(self, expand):
579
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
580
                                            save=True)
581
        return c
582
583
    def assertExpandIs(self, expected):
584
        actual = config._get_expand_default_value()
585
        #self.config.get_user_option_as_bool('bzr.config.expand')
586
        self.assertEquals(expected, actual)
587
588
    def test_default_is_None(self):
589
        self.assertEquals(None, config._expand_default_value)
590
591
    def test_default_is_False_even_if_None(self):
592
        self.config = self.get_config(None)
593
        self.assertExpandIs(False)
594
595
    def test_default_is_False_even_if_invalid(self):
596
        self.config = self.get_config('<your choice>')
597
        self.assertExpandIs(False)
598
        # ...
599
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
600
        # Wait, you've been warned !
601
        self.assertLength(1, self.warnings)
602
        self.assertEquals(
603
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
604
            self.warnings[0])
605
606
    def test_default_is_True(self):
607
        self.config = self.get_config(True)
608
        self.assertExpandIs(True)
609
        
610
    def test_default_is_False(self):
611
        self.config = self.get_config(False)
612
        self.assertExpandIs(False)
613
        
614
615
class TestIniConfigOptionExpansion(tests.TestCase):
616
    """Test option expansion from the IniConfig level.
617
618
    What we really want here is to test the Config level, but the class being
619
    abstract as far as storing values is concerned, this can't be done
620
    properly (yet).
621
    """
622
    # FIXME: This should be rewritten when all configs share a storage
623
    # implementation -- vila 2011-02-18
624
625
    def get_config(self, string=None):
626
        if string is None:
627
            string = ''
628
        c = config.IniBasedConfig.from_string(string)
629
        return c
630
631
    def assertExpansion(self, expected, conf, string, env=None):
632
        self.assertEquals(expected, conf.expand_options(string, env))
633
634
    def test_no_expansion(self):
635
        c = self.get_config('')
636
        self.assertExpansion('foo', c, 'foo')
637
638
    def test_env_adding_options(self):
639
        c = self.get_config('')
640
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
641
642
    def test_env_overriding_options(self):
643
        c = self.get_config('foo=baz')
644
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
645
646
    def test_simple_ref(self):
647
        c = self.get_config('foo=xxx')
648
        self.assertExpansion('xxx', c, '{foo}')
649
650
    def test_unknown_ref(self):
651
        c = self.get_config('')
652
        self.assertRaises(errors.ExpandingUnknownOption,
653
                          c.expand_options, '{foo}')
654
655
    def test_indirect_ref(self):
656
        c = self.get_config('''
657
foo=xxx
658
bar={foo}
659
''')
660
        self.assertExpansion('xxx', c, '{bar}')
661
662
    def test_embedded_ref(self):
663
        c = self.get_config('''
664
foo=xxx
665
bar=foo
666
''')
667
        self.assertExpansion('xxx', c, '{{bar}}')
668
669
    def test_simple_loop(self):
670
        c = self.get_config('foo={foo}')
671
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
672
673
    def test_indirect_loop(self):
674
        c = self.get_config('''
675
foo={bar}
676
bar={baz}
677
baz={foo}''')
678
        e = self.assertRaises(errors.OptionExpansionLoop,
679
                              c.expand_options, '{foo}')
680
        self.assertEquals('foo->bar->baz', e.refs)
681
        self.assertEquals('{foo}', e.string)
682
683
    def test_list(self):
684
        conf = self.get_config('''
685
foo=start
686
bar=middle
687
baz=end
688
list={foo},{bar},{baz}
689
''')
690
        self.assertEquals(['start', 'middle', 'end'],
691
                           conf.get_user_option('list', expand=True))
692
693
    def test_cascading_list(self):
694
        conf = self.get_config('''
695
foo=start,{bar}
696
bar=middle,{baz}
697
baz=end
698
list={foo}
699
''')
700
        self.assertEquals(['start', 'middle', 'end'],
701
                           conf.get_user_option('list', expand=True))
702
703
    def test_pathological_hidden_list(self):
704
        conf = self.get_config('''
705
foo=bin
706
bar=go
707
start={foo
708
middle=},{
709
end=bar}
710
hidden={start}{middle}{end}
711
''')
712
        # Nope, it's either a string or a list, and the list wins as soon as a
713
        # ',' appears, so the string concatenation never occur.
714
        self.assertEquals(['{foo', '}', '{', 'bar}'],
715
                          conf.get_user_option('hidden', expand=True))
716
717
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
718
719
    def get_config(self, location, string=None):
720
        if string is None:
721
            string = ''
722
        # Since we don't save the config we won't strictly require to inherit
723
        # from TestCaseInTempDir, but an error occurs so quickly...
724
        c = config.LocationConfig.from_string(string, location)
725
        return c
726
727
    def test_dont_cross_unrelated_section(self):
728
        c = self.get_config('/another/branch/path','''
729
[/one/branch/path]
730
foo = hello
731
bar = {foo}/2
732
733
[/another/branch/path]
734
bar = {foo}/2
735
''')
736
        self.assertRaises(errors.ExpandingUnknownOption,
737
                          c.get_user_option, 'bar', expand=True)
738
739
    def test_cross_related_sections(self):
740
        c = self.get_config('/project/branch/path','''
741
[/project]
742
foo = qu
743
744
[/project/branch/path]
745
bar = {foo}ux
746
''')
747
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
748
749
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
750
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
751
752
    def test_cannot_reload_without_name(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
753
        conf = config.IniBasedConfig.from_string(sample_config_text)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
754
        self.assertRaises(AssertionError, conf.reload)
755
756
    def test_reload_see_new_value(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
757
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
758
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
759
        c1._write_config_file()
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
760
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
761
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
762
        c2._write_config_file()
763
        self.assertEqual('vim', c1.get_user_option('editor'))
764
        self.assertEqual('emacs', c2.get_user_option('editor'))
765
        # Make sure we get the Right value
766
        c1.reload()
767
        self.assertEqual('emacs', c1.get_user_option('editor'))
768
769
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
770
class TestLockableConfig(tests.TestCaseInTempDir):
771
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
772
    scenarios = lockable_config_scenarios()
773
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
774
    # Set by load_tests
775
    config_class = None
776
    config_args = None
777
    config_section = None
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
778
779
    def setUp(self):
780
        super(TestLockableConfig, self).setUp()
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
781
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
782
        self.config = self.create_config(self._content)
783
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
784
    def get_existing_config(self):
785
        return self.config_class(*self.config_args)
786
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
787
    def create_config(self, content):
5396.1.1 by Vincent Ladeuil
Fix python-2.6-ism.
788
        kwargs = dict(save=True)
789
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
790
        return c
791
792
    def test_simple_read_access(self):
793
        self.assertEquals('1', self.config.get_user_option('one'))
794
795
    def test_simple_write_access(self):
796
        self.config.set_user_option('one', 'one')
797
        self.assertEquals('one', self.config.get_user_option('one'))
798
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
799
    def test_listen_to_the_last_speaker(self):
800
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
801
        c2 = self.get_existing_config()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
802
        c1.set_user_option('one', 'ONE')
803
        c2.set_user_option('two', 'TWO')
804
        self.assertEquals('ONE', c1.get_user_option('one'))
805
        self.assertEquals('TWO', c2.get_user_option('two'))
806
        # The second update respect the first one
807
        self.assertEquals('ONE', c2.get_user_option('one'))
808
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
809
    def test_last_speaker_wins(self):
810
        # If the same config is not shared, the same variable modified twice
811
        # can only see a single result.
812
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
813
        c2 = self.get_existing_config()
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
814
        c1.set_user_option('one', 'c1')
815
        c2.set_user_option('one', 'c2')
816
        self.assertEquals('c2', c2._get_user_option('one'))
817
        # The first modification is still available until another refresh
818
        # occur
819
        self.assertEquals('c1', c1._get_user_option('one'))
820
        c1.set_user_option('two', 'done')
821
        self.assertEquals('c2', c1._get_user_option('one'))
822
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
823
    def test_writes_are_serialized(self):
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
824
        c1 = self.config
825
        c2 = self.get_existing_config()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
826
827
        # We spawn a thread that will pause *during* the write
828
        before_writing = threading.Event()
829
        after_writing = threading.Event()
830
        writing_done = threading.Event()
831
        c1_orig = c1._write_config_file
832
        def c1_write_config_file():
833
            before_writing.set()
834
            c1_orig()
835
            # The lock is held we wait for the main thread to decide when to
836
            # continue
837
            after_writing.wait()
838
        c1._write_config_file = c1_write_config_file
839
        def c1_set_option():
840
            c1.set_user_option('one', 'c1')
841
            writing_done.set()
842
        t1 = threading.Thread(target=c1_set_option)
843
        # Collect the thread after the test
844
        self.addCleanup(t1.join)
845
        # Be ready to unblock the thread if the test goes wrong
846
        self.addCleanup(after_writing.set)
847
        t1.start()
848
        before_writing.wait()
849
        self.assertTrue(c1._lock.is_held)
850
        self.assertRaises(errors.LockContention,
851
                          c2.set_user_option, 'one', 'c2')
852
        self.assertEquals('c1', c1.get_user_option('one'))
853
        # Let the lock be released
854
        after_writing.set()
855
        writing_done.wait()
856
        c2.set_user_option('one', 'c2')
857
        self.assertEquals('c2', c2.get_user_option('one'))
858
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
859
    def test_read_while_writing(self):
860
       c1 = self.config
861
       # We spawn a thread that will pause *during* the write
862
       ready_to_write = threading.Event()
863
       do_writing = threading.Event()
864
       writing_done = threading.Event()
865
       c1_orig = c1._write_config_file
866
       def c1_write_config_file():
867
           ready_to_write.set()
868
           # The lock is held we wait for the main thread to decide when to
869
           # continue
870
           do_writing.wait()
871
           c1_orig()
872
           writing_done.set()
873
       c1._write_config_file = c1_write_config_file
874
       def c1_set_option():
875
           c1.set_user_option('one', 'c1')
876
       t1 = threading.Thread(target=c1_set_option)
877
       # Collect the thread after the test
878
       self.addCleanup(t1.join)
879
       # Be ready to unblock the thread if the test goes wrong
880
       self.addCleanup(do_writing.set)
881
       t1.start()
882
       # Ensure the thread is ready to write
883
       ready_to_write.wait()
884
       self.assertTrue(c1._lock.is_held)
885
       self.assertEquals('c1', c1.get_user_option('one'))
886
       # If we read during the write, we get the old value
887
       c2 = self.get_existing_config()
888
       self.assertEquals('1', c2.get_user_option('one'))
889
       # Let the writing occur and ensure it occurred
890
       do_writing.set()
891
       writing_done.wait()
892
       # Now we get the updated value
893
       c3 = self.get_existing_config()
894
       self.assertEquals('c1', c3.get_user_option('one'))
895
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
896
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
897
class TestGetUserOptionAs(TestIniConfig):
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
898
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
899
    def test_get_user_option_as_bool(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
900
        conf, parser = self.make_config_parser("""
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
901
a_true_bool = true
902
a_false_bool = 0
903
an_invalid_bool = maybe
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
904
a_list = hmm, who knows ? # This is interpreted as a list !
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
905
""")
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
906
        get_bool = conf.get_user_option_as_bool
907
        self.assertEqual(True, get_bool('a_true_bool'))
908
        self.assertEqual(False, get_bool('a_false_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
909
        warnings = []
910
        def warning(*args):
911
            warnings.append(args[0] % args[1:])
912
        self.overrideAttr(trace, 'warning', warning)
913
        msg = 'Value "%s" is not a boolean for "%s"'
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
914
        self.assertIs(None, get_bool('an_invalid_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
915
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
916
        warnings = []
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
917
        self.assertIs(None, get_bool('not_defined_in_this_config'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
918
        self.assertEquals([], warnings)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
919
920
    def test_get_user_option_as_list(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
921
        conf, parser = self.make_config_parser("""
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
922
a_list = a,b,c
923
length_1 = 1,
924
one_item = x
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
925
""")
926
        get_list = conf.get_user_option_as_list
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
927
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
928
        self.assertEqual(['1'], get_list('length_1'))
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
929
        self.assertEqual('x', conf.get_user_option('one_item'))
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
930
        # automatically cast to list
931
        self.assertEqual(['x'], get_list('one_item'))
932
933
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
934
class TestSupressWarning(TestIniConfig):
935
936
    def make_warnings_config(self, s):
937
        conf, parser = self.make_config_parser(s)
938
        return conf.suppress_warning
939
940
    def test_suppress_warning_unknown(self):
941
        suppress_warning = self.make_warnings_config('')
942
        self.assertEqual(False, suppress_warning('unknown_warning'))
943
944
    def test_suppress_warning_known(self):
945
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
946
        self.assertEqual(False, suppress_warning('c'))
947
        self.assertEqual(True, suppress_warning('a'))
948
        self.assertEqual(True, suppress_warning('b'))
949
950
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
951
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
952
953
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
954
        my_config = config.GlobalConfig()
955
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
956
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
957
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
958
        oldparserclass = config.ConfigObj
959
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
960
        my_config = config.GlobalConfig()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
961
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
962
            parser = my_config._get_parser()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
963
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
964
            config.ConfigObj = oldparserclass
965
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1551.2.20 by Aaron Bentley
Treated config files as utf-8
966
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
967
                                          'utf-8')])
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
968
969
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
970
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
971
972
    def test_constructs(self):
973
        branch = FakeBranch()
974
        my_config = config.BranchConfig(branch)
975
        self.assertRaises(TypeError, config.BranchConfig)
976
977
    def test_get_location_config(self):
978
        branch = FakeBranch()
979
        my_config = config.BranchConfig(branch)
980
        location_config = my_config._get_location_config()
981
        self.assertEqual(branch.base, location_config.location)
982
        self.failUnless(location_config is my_config._get_location_config())
983
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
984
    def test_get_config(self):
985
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
986
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
987
        my_config = b.get_config()
988
        self.assertIs(my_config.get_user_option('wacky'), None)
989
        my_config.set_user_option('wacky', 'unlikely')
990
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
991
992
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
993
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
994
        my_config2 = b2.get_config()
995
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
996
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
997
    def test_has_explicit_nickname(self):
998
        b = self.make_branch('.')
999
        self.assertFalse(b.get_config().has_explicit_nickname())
1000
        b.nick = 'foo'
1001
        self.assertTrue(b.get_config().has_explicit_nickname())
1002
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1003
    def test_config_url(self):
1004
        """The Branch.get_config will use section that uses a local url"""
1005
        branch = self.make_branch('branch')
1006
        self.assertEqual('branch', branch.nick)
1007
1008
        local_url = urlutils.local_path_to_url('branch')
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1009
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1010
            '[%s]\nnickname = foobar' % (local_url,),
1011
            local_url, save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1012
        self.assertEqual('foobar', branch.nick)
1013
1014
    def test_config_local_path(self):
1015
        """The Branch.get_config will use a local system path"""
1016
        branch = self.make_branch('branch')
1017
        self.assertEqual('branch', branch.nick)
1018
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1019
        local_path = osutils.getcwd().encode('utf8')
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1020
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1021
            '[%s/branch]\nnickname = barry' % (local_path,),
1022
            'branch',  save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1023
        self.assertEqual('barry', branch.nick)
1024
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
1025
    def test_config_creates_local(self):
1026
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
1027
        branch = self.make_branch('branch', format='knit')
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
1028
        branch.set_push_location('http://foobar')
1029
        local_path = osutils.getcwd().encode('utf8')
1030
        # Surprisingly ConfigObj doesn't create a trailing newline
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1031
        self.check_file_contents(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1032
                                 '[%s/branch]\n'
1033
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
1034
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1035
                                 % (local_path,))
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
1036
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
1037
    def test_autonick_urlencoded(self):
1038
        b = self.make_branch('!repo')
1039
        self.assertEqual('!repo', b.get_config().get_nickname())
1040
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1041
    def test_warn_if_masked(self):
1042
        warnings = []
1043
        def warning(*args):
1044
            warnings.append(args[0] % args[1:])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1045
        self.overrideAttr(trace, 'warning', warning)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1046
1047
        def set_option(store, warn_masked=True):
1048
            warnings[:] = []
1049
            conf.set_user_option('example_option', repr(store), store=store,
1050
                                 warn_masked=warn_masked)
1051
        def assertWarning(warning):
1052
            if warning is None:
1053
                self.assertEqual(0, len(warnings))
1054
            else:
1055
                self.assertEqual(1, len(warnings))
1056
                self.assertEqual(warning, warnings[0])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1057
        branch = self.make_branch('.')
1058
        conf = branch.get_config()
1059
        set_option(config.STORE_GLOBAL)
1060
        assertWarning(None)
1061
        set_option(config.STORE_BRANCH)
1062
        assertWarning(None)
1063
        set_option(config.STORE_GLOBAL)
1064
        assertWarning('Value "4" is masked by "3" from branch.conf')
1065
        set_option(config.STORE_GLOBAL, warn_masked=False)
1066
        assertWarning(None)
1067
        set_option(config.STORE_LOCATION)
1068
        assertWarning(None)
1069
        set_option(config.STORE_BRANCH)
1070
        assertWarning('Value "3" is masked by "0" from locations.conf')
1071
        set_option(config.STORE_BRANCH, warn_masked=False)
1072
        assertWarning(None)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1073
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1074
5448.1.1 by Vincent Ladeuil
Use TestCaseInTempDir for tests requiring disk resources
1075
class TestGlobalConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1076
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1077
    def test_user_id(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1078
        my_config = config.GlobalConfig.from_string(sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1079
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1080
                         my_config._get_user_id())
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1081
1082
    def test_absent_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1083
        my_config = config.GlobalConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1084
        self.assertEqual(None, my_config._get_user_id())
1085
1086
    def test_configured_editor(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1087
        my_config = config.GlobalConfig.from_string(sample_config_text)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1088
        self.assertEqual("vim", my_config.get_editor())
1089
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1090
    def test_signatures_always(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1091
        my_config = config.GlobalConfig.from_string(sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1092
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1093
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1094
        self.assertEqual(config.SIGN_ALWAYS,
1095
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1096
        self.assertEqual(True, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1097
1098
    def test_signatures_if_possible(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1099
        my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1100
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1101
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1102
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1103
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1104
        self.assertEqual(False, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1105
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1106
    def test_signatures_ignore(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1107
        my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1108
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1109
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1110
        self.assertEqual(config.SIGN_NEVER,
1111
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1112
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1113
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1114
    def _get_sample_config(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1115
        my_config = config.GlobalConfig.from_string(sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
1116
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1117
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1118
    def test_gpg_signing_command(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1119
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1120
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1121
        self.assertEqual(False, my_config.signature_needed())
1122
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1123
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1124
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1125
        return my_config
1126
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1127
    def test_gpg_signing_command_unset(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1128
        my_config = self._get_empty_config()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1129
        self.assertEqual("gpg", my_config.gpg_signing_command())
1130
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1131
    def test_get_user_option_default(self):
1132
        my_config = self._get_empty_config()
1133
        self.assertEqual(None, my_config.get_user_option('no_option'))
1134
1135
    def test_get_user_option_global(self):
1136
        my_config = self._get_sample_config()
1137
        self.assertEqual("something",
1138
                         my_config.get_user_option('user_global_option'))
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1139
1472 by Robert Collins
post commit hook, first pass implementation
1140
    def test_post_commit_default(self):
1141
        my_config = self._get_sample_config()
1142
        self.assertEqual(None, my_config.post_commit())
1143
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
1144
    def test_configured_logformat(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
1145
        my_config = self._get_sample_config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
1146
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
1147
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
1148
    def test_get_alias(self):
1149
        my_config = self._get_sample_config()
1150
        self.assertEqual('help', my_config.get_alias('h'))
1151
2900.3.6 by Tim Penhey
Added tests.
1152
    def test_get_aliases(self):
1153
        my_config = self._get_sample_config()
1154
        aliases = my_config.get_aliases()
1155
        self.assertEqual(2, len(aliases))
1156
        sorted_keys = sorted(aliases)
1157
        self.assertEqual('help', aliases[sorted_keys[0]])
1158
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1159
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
1160
    def test_get_no_alias(self):
1161
        my_config = self._get_sample_config()
1162
        self.assertEqual(None, my_config.get_alias('foo'))
1163
1164
    def test_get_long_alias(self):
1165
        my_config = self._get_sample_config()
1166
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1167
4603.1.10 by Aaron Bentley
Provide change editor via config.
1168
    def test_get_change_editor(self):
1169
        my_config = self._get_sample_config()
1170
        change_editor = my_config.get_change_editor('old', 'new')
1171
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1172
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
1173
                         ' '.join(change_editor.command_template))
1174
1175
    def test_get_no_change_editor(self):
1176
        my_config = self._get_empty_config()
1177
        change_editor = my_config.get_change_editor('old', 'new')
1178
        self.assertIs(None, change_editor)
1179
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1180
    def test_get_merge_tools(self):
1181
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1182
        tools = conf.get_merge_tools()
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1183
        self.log(repr(tools))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1184
        self.assertEqual(
1185
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1186
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1187
            tools)
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1188
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1189
    def test_get_merge_tools_empty(self):
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1190
        conf = self._get_empty_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1191
        tools = conf.get_merge_tools()
1192
        self.assertEqual({}, tools)
5321.1.103 by Gordon Tyler
Renamed _find_merge_tool back to find_merge_tool since it must be public for UI code to lookup merge tools by name, and added tests for it.
1193
1194
    def test_find_merge_tool(self):
1195
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1196
        cmdline = conf.find_merge_tool('sometool')
1197
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
5321.1.103 by Gordon Tyler
Renamed _find_merge_tool back to find_merge_tool since it must be public for UI code to lookup merge tools by name, and added tests for it.
1198
1199
    def test_find_merge_tool_not_found(self):
1200
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1201
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1202
        self.assertIs(cmdline, None)
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1203
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1204
    def test_find_merge_tool_known(self):
1205
        conf = self._get_empty_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1206
        cmdline = conf.find_merge_tool('kdiff3')
1207
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
1208
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1209
    def test_find_merge_tool_override_known(self):
1210
        conf = self._get_empty_config()
5321.1.112 by Gordon Tyler
Removed set_merge_tool, remove_merge_tool and set_default_merge_tool from Config.
1211
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1212
        cmdline = conf.find_merge_tool('kdiff3')
1213
        self.assertEqual('kdiff3 blah', cmdline)
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1214
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1215
2900.3.6 by Tim Penhey
Added tests.
1216
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1217
1218
    def test_empty(self):
1219
        my_config = config.GlobalConfig()
1220
        self.assertEqual(0, len(my_config.get_aliases()))
1221
1222
    def test_set_alias(self):
1223
        my_config = config.GlobalConfig()
1224
        alias_value = 'commit --strict'
1225
        my_config.set_alias('commit', alias_value)
1226
        new_config = config.GlobalConfig()
1227
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1228
1229
    def test_remove_alias(self):
1230
        my_config = config.GlobalConfig()
1231
        my_config.set_alias('commit', 'commit --strict')
1232
        # Now remove the alias again.
1233
        my_config.unset_alias('commit')
1234
        new_config = config.GlobalConfig()
1235
        self.assertIs(None, new_config.get_alias('commit'))
1236
1237
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1238
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1239
1240
    def test_constructs(self):
1241
        my_config = config.LocationConfig('http://example.com')
1242
        self.assertRaises(TypeError, config.LocationConfig)
1243
1244
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1245
        # This is testing the correct file names are provided.
1246
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1247
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1248
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1249
        oldparserclass = config.ConfigObj
1250
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1251
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1252
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1253
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1254
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1255
            config.ConfigObj = oldparserclass
1256
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1257
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1258
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1259
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1260
1261
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1262
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1263
        global_config = my_config._get_global_config()
1264
        self.failUnless(isinstance(global_config, config.GlobalConfig))
1265
        self.failUnless(global_config is my_config._get_global_config())
1266
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1267
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1268
        self.get_branch_config('/')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1269
        self.assertEqual([], self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1270
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1271
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1272
        self.get_branch_config('http://www.example.com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1273
        self.assertEqual([('http://www.example.com', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1274
                         self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1275
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1276
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1277
        self.get_branch_config('http://www.example.com-com')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1278
        self.assertEqual([], self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1279
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1280
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1281
        self.get_branch_config('http://www.example.com/com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1282
        self.assertEqual([('http://www.example.com', 'com')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1283
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1284
1993.3.5 by James Henstridge
add back recurse=False option to config file
1285
    def test__get_matching_sections_ignoreparent(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1286
        self.get_branch_config('http://www.example.com/ignoreparent')
1287
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1288
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1289
1993.3.5 by James Henstridge
add back recurse=False option to config file
1290
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1291
        self.get_branch_config(
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1292
            'http://www.example.com/ignoreparent/childbranch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1293
        self.assertEqual([('http://www.example.com/ignoreparent',
1294
                           'childbranch')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1295
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1296
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1297
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1298
        self.get_branch_config('/b')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1299
        self.assertEqual([('/b/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1300
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1301
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1302
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1303
        self.get_branch_config('/a/foo')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1304
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1305
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1306
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1307
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1308
        self.get_branch_config('/a/foo/bar')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1309
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1310
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1311
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1312
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1313
        self.get_branch_config('/a/')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1314
        self.assertEqual([('/a/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1315
                         self.my_location_config._get_matching_sections())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1316
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1317
    def test__get_matching_sections_explicit_over_glob(self):
1318
        # XXX: 2006-09-08 jamesh
1319
        # This test only passes because ord('c') > ord('*').  If there
1320
        # was a config section for '/a/?', it would get precedence
1321
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1322
        self.get_branch_config('/a/c')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1323
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1324
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1325
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
1326
    def test__get_option_policy_normal(self):
1327
        self.get_branch_config('http://www.example.com')
1328
        self.assertEqual(
1329
            self.my_location_config._get_config_policy(
1330
            'http://www.example.com', 'normal_option'),
1331
            config.POLICY_NONE)
1332
1333
    def test__get_option_policy_norecurse(self):
1334
        self.get_branch_config('http://www.example.com')
1335
        self.assertEqual(
1336
            self.my_location_config._get_option_policy(
1337
            'http://www.example.com', 'norecurse_option'),
1338
            config.POLICY_NORECURSE)
1339
        # Test old recurse=False setting:
1340
        self.assertEqual(
1341
            self.my_location_config._get_option_policy(
1342
            'http://www.example.com/norecurse', 'normal_option'),
1343
            config.POLICY_NORECURSE)
1344
1345
    def test__get_option_policy_normal(self):
1346
        self.get_branch_config('http://www.example.com')
1347
        self.assertEqual(
1348
            self.my_location_config._get_option_policy(
1349
            'http://www.example.com', 'appendpath_option'),
1350
            config.POLICY_APPENDPATH)
1351
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1352
    def test__get_options_with_policy(self):
1353
        self.get_branch_config('/dir/subdir',
1354
                               location_config="""\
1355
[/dir]
1356
other_url = /other-dir
1357
other_url:policy = appendpath
1358
[/dir/subdir]
1359
other_url = /other-subdir
1360
""")
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1361
        self.assertOptions(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1362
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1363
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1364
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1365
            self.my_location_config)
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1366
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1367
    def test_location_without_username(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1368
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1369
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1370
                         self.my_config.username())
1371
1372
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1373
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1374
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1375
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1376
                         self.my_config.username())
1377
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1378
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1379
        self.get_branch_config('http://www.example.com/foo')
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1380
        self.assertEqual('Robert Collins <robertc@example.org>',
1381
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1382
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1383
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1384
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1385
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1386
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1387
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1388
        self.assertEqual(config.SIGN_NEVER,
1389
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1390
1391
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1392
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1393
        self.assertEqual(config.CHECK_NEVER,
1394
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1395
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1396
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1397
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1398
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1399
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1400
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1401
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1402
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1403
        self.assertEqual(config.CHECK_ALWAYS,
1404
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1405
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1406
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1407
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1408
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1409
1410
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1411
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1412
        self.assertEqual("false", self.my_config.gpg_signing_command())
1413
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1414
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1415
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1416
        self.assertEqual('something',
1417
                         self.my_config.get_user_option('user_global_option'))
1418
1419
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1420
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1421
        self.assertEqual('local',
1422
                         self.my_config.get_user_option('user_local_option'))
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1423
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
1424
    def test_get_user_option_appendpath(self):
1425
        # returned as is for the base path:
1426
        self.get_branch_config('http://www.example.com')
1427
        self.assertEqual('append',
1428
                         self.my_config.get_user_option('appendpath_option'))
1429
        # Extra path components get appended:
1430
        self.get_branch_config('http://www.example.com/a/b/c')
1431
        self.assertEqual('append/a/b/c',
1432
                         self.my_config.get_user_option('appendpath_option'))
1433
        # Overriden for http://www.example.com/dir, where it is a
1434
        # normal option:
1435
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1436
        self.assertEqual('normal',
1437
                         self.my_config.get_user_option('appendpath_option'))
1438
1439
    def test_get_user_option_norecurse(self):
1440
        self.get_branch_config('http://www.example.com')
1441
        self.assertEqual('norecurse',
1442
                         self.my_config.get_user_option('norecurse_option'))
1443
        self.get_branch_config('http://www.example.com/dir')
1444
        self.assertEqual(None,
1445
                         self.my_config.get_user_option('norecurse_option'))
1446
        # http://www.example.com/norecurse is a recurse=False section
1447
        # that redefines normal_option.  Subdirectories do not pick up
1448
        # this redefinition.
1449
        self.get_branch_config('http://www.example.com/norecurse')
1450
        self.assertEqual('norecurse',
1451
                         self.my_config.get_user_option('normal_option'))
1452
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1453
        self.assertEqual('normal',
1454
                         self.my_config.get_user_option('normal_option'))
1455
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1456
    def test_set_user_option_norecurse(self):
1457
        self.get_branch_config('http://www.example.com')
1458
        self.my_config.set_user_option('foo', 'bar',
1459
                                       store=config.STORE_LOCATION_NORECURSE)
1460
        self.assertEqual(
1461
            self.my_location_config._get_option_policy(
1462
            'http://www.example.com', 'foo'),
1463
            config.POLICY_NORECURSE)
1464
1465
    def test_set_user_option_appendpath(self):
1466
        self.get_branch_config('http://www.example.com')
1467
        self.my_config.set_user_option('foo', 'bar',
1468
                                       store=config.STORE_LOCATION_APPENDPATH)
1469
        self.assertEqual(
1470
            self.my_location_config._get_option_policy(
1471
            'http://www.example.com', 'foo'),
1472
            config.POLICY_APPENDPATH)
1473
1474
    def test_set_user_option_change_policy(self):
1475
        self.get_branch_config('http://www.example.com')
1476
        self.my_config.set_user_option('norecurse_option', 'normal',
1477
                                       store=config.STORE_LOCATION)
1478
        self.assertEqual(
1479
            self.my_location_config._get_option_policy(
1480
            'http://www.example.com', 'norecurse_option'),
1481
            config.POLICY_NONE)
1482
1483
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1484
        # The following section has recurse=False set.  The test is to
1485
        # make sure that a normal option can be added to the section,
1486
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1487
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1488
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1489
                             'The section "http://www.example.com/norecurse" '
1490
                             'has been converted to use policies.'],
1491
                            self.my_config.set_user_option,
1492
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1493
        self.assertEqual(
1494
            self.my_location_config._get_option_policy(
1495
            'http://www.example.com/norecurse', 'foo'),
1496
            config.POLICY_NONE)
1497
        # The previously existing option is still norecurse:
1498
        self.assertEqual(
1499
            self.my_location_config._get_option_policy(
1500
            'http://www.example.com/norecurse', 'normal_option'),
1501
            config.POLICY_NORECURSE)
1502
1472 by Robert Collins
post commit hook, first pass implementation
1503
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1504
        self.get_branch_config('/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
1505
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1506
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1507
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1508
    def get_branch_config(self, location, global_config=None,
1509
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1510
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1511
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1512
            global_config = sample_config_text
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1513
        if location_config is None:
1514
            location_config = sample_branches_text
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1515
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1516
        my_global_config = config.GlobalConfig.from_string(global_config,
1517
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1518
        my_location_config = config.LocationConfig.from_string(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1519
            location_config, my_branch.base, save=True)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1520
        my_config = config.BranchConfig(my_branch)
1521
        self.my_config = my_config
1522
        self.my_location_config = my_config._get_location_config()
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1523
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1524
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1525
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1526
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1527
        self.my_location_config._parser = record
1185.62.6 by John Arbash Meinel
Updated test_set_user_setting_sets_and_saves to remove the print statement, and make sure it is doing the right thing
1528
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1529
        self.callDeprecated(['The recurse option is deprecated as of '
1530
                             '0.14.  The section "/a/c" has been '
1531
                             'converted to use policies.'],
1532
                            self.my_config.set_user_option,
1533
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1534
        self.assertEqual([('reload',),
1535
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1536
                          ('__contains__', '/a/c/'),
1537
                          ('__setitem__', '/a/c', {}),
1538
                          ('__getitem__', '/a/c'),
1539
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1540
                          ('__getitem__', '/a/c'),
1541
                          ('as_bool', 'recurse'),
1542
                          ('__getitem__', '/a/c'),
1543
                          ('__delitem__', 'recurse'),
1544
                          ('__getitem__', '/a/c'),
1545
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1546
                          ('__getitem__', '/a/c'),
1547
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1548
                          ('write',)],
1549
                         record._calls[1:])
1550
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1551
    def test_set_user_setting_sets_and_saves2(self):
1552
        self.get_branch_config('/a/c')
1553
        self.assertIs(self.my_config.get_user_option('foo'), None)
1554
        self.my_config.set_user_option('foo', 'bar')
1555
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1556
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1557
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1558
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1559
        self.my_config.set_user_option('foo', 'baz',
1560
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1561
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1562
        self.my_config.set_user_option('foo', 'qux')
1563
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1564
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1565
    def test_get_bzr_remote_path(self):
1566
        my_config = config.LocationConfig('/a/c')
1567
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1568
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1569
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1570
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1571
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1572
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1573
1770.2.8 by Aaron Bentley
Add precedence test
1574
precedence_global = 'option = global'
1575
precedence_branch = 'option = branch'
1576
precedence_location = """
1577
[http://]
1578
recurse = true
1579
option = recurse
1580
[http://example.com/specific]
1581
option = exact
1582
"""
1583
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1584
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1585
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1586
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1587
                          location_config=None, branch_data_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1588
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1589
        if global_config is not None:
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1590
            my_global_config = config.GlobalConfig.from_string(global_config,
1591
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1592
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1593
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1594
                location_config, my_branch.base, save=True)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1595
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1596
        if branch_data_config is not None:
1597
            my_config.branch.control_files.files['branch.conf'] = \
1598
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1599
        return my_config
1600
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1601
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1602
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1603
        my_config = config.BranchConfig(branch)
1604
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1605
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1606
        my_config.branch.control_files.files['email'] = "John"
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1607
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1608
                                  "Robert Collins <robertc@example.org>")
1609
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1610
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1611
        self.assertEqual("Robert Collins <robertc@example.org>",
1612
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1613
1614
    def test_not_set_in_branch(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1615
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1616
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1617
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1618
        my_config.branch.control_files.files['email'] = "John"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1619
        self.assertEqual("John", my_config._get_user_id())
1620
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1621
    def test_BZR_EMAIL_OVERRIDES(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1622
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1623
        branch = FakeBranch()
1624
        my_config = config.BranchConfig(branch)
1625
        self.assertEqual("Robert Collins <robertc@example.org>",
1626
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1627
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1628
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1629
        my_config = self.get_branch_config(
1630
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1631
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1632
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1633
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1634
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1635
    def test_signatures_forced_branch(self):
1636
        my_config = self.get_branch_config(
1637
            global_config=sample_ignore_signatures,
1638
            branch_data_config=sample_always_signatures)
1639
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1640
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1641
        self.assertTrue(my_config.signature_needed())
1642
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1643
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1644
        my_config = self.get_branch_config(
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1645
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1646
            # branch data cannot set gpg_signing_command
1647
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1648
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1649
1650
    def test_get_user_option_global(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1651
        my_config = self.get_branch_config(global_config=sample_config_text)
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1652
        self.assertEqual('something',
1653
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1654
1655
    def test_post_commit_default(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1656
        my_config = self.get_branch_config(global_config=sample_config_text,
1657
                                      location='/a/c',
1658
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1659
        self.assertEqual(my_config.branch.base, '/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
1660
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1661
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1662
        my_config.set_user_option('post_commit', 'rmtree_root')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1663
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1664
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1665
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1666
        my_config.set_user_option('post_commit', 'rmtree_root',
1667
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1668
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1669
1770.2.8 by Aaron Bentley
Add precedence test
1670
    def test_config_precedence(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1671
        # FIXME: eager test, luckily no persitent config file makes it fail
1672
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1673
        my_config = self.get_branch_config(global_config=precedence_global)
1674
        self.assertEqual(my_config.get_user_option('option'), 'global')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1675
        my_config = self.get_branch_config(global_config=precedence_global,
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1676
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1677
        self.assertEqual(my_config.get_user_option('option'), 'branch')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1678
        my_config = self.get_branch_config(
1679
            global_config=precedence_global,
1680
            branch_data_config=precedence_branch,
1681
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1682
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1683
        my_config = self.get_branch_config(
1684
            global_config=precedence_global,
1685
            branch_data_config=precedence_branch,
1686
            location_config=precedence_location,
1687
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1688
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1689
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1690
    def test_get_mail_client(self):
1691
        config = self.get_branch_config()
1692
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1693
        self.assertIsInstance(client, mail_client.DefaultMail)
1694
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1695
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1696
        config.set_user_option('mail_client', 'evolution')
1697
        client = config.get_mail_client()
1698
        self.assertIsInstance(client, mail_client.Evolution)
1699
2681.5.1 by ghigo
Add KMail support to bzr send
1700
        config.set_user_option('mail_client', 'kmail')
1701
        client = config.get_mail_client()
1702
        self.assertIsInstance(client, mail_client.KMail)
1703
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1704
        config.set_user_option('mail_client', 'mutt')
1705
        client = config.get_mail_client()
1706
        self.assertIsInstance(client, mail_client.Mutt)
1707
1708
        config.set_user_option('mail_client', 'thunderbird')
1709
        client = config.get_mail_client()
1710
        self.assertIsInstance(client, mail_client.Thunderbird)
1711
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1712
        # Generic options
1713
        config.set_user_option('mail_client', 'default')
1714
        client = config.get_mail_client()
1715
        self.assertIsInstance(client, mail_client.DefaultMail)
1716
1717
        config.set_user_option('mail_client', 'editor')
1718
        client = config.get_mail_client()
1719
        self.assertIsInstance(client, mail_client.Editor)
1720
1721
        config.set_user_option('mail_client', 'mapi')
1722
        client = config.get_mail_client()
1723
        self.assertIsInstance(client, mail_client.MAPIClient)
1724
2681.1.23 by Aaron Bentley
Add support for xdg-email
1725
        config.set_user_option('mail_client', 'xdg-email')
1726
        client = config.get_mail_client()
1727
        self.assertIsInstance(client, mail_client.XDGEmail)
1728
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1729
        config.set_user_option('mail_client', 'firebird')
1730
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1731
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1732
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1733
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1734
1735
    def test_extract_email_address(self):
1736
        self.assertEqual('jane@test.com',
1737
                         config.extract_email_address('Jane <jane@test.com>'))
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
1738
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1739
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1740
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1741
    def test_parse_username(self):
1742
        self.assertEqual(('', 'jdoe@example.com'),
1743
                         config.parse_username('jdoe@example.com'))
1744
        self.assertEqual(('', 'jdoe@example.com'),
1745
                         config.parse_username('<jdoe@example.com>'))
1746
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1747
                         config.parse_username('John Doe <jdoe@example.com>'))
1748
        self.assertEqual(('John Doe', ''),
1749
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1750
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1751
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1752
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1753
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1754
1755
    def test_get_value(self):
1756
        """Test that retreiving a value from a section is possible"""
1757
        branch = self.make_branch('.')
1758
        tree_config = config.TreeConfig(branch)
1759
        tree_config.set_option('value', 'key', 'SECTION')
1760
        tree_config.set_option('value2', 'key2')
1761
        tree_config.set_option('value3-top', 'key3')
1762
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1763
        value = tree_config.get_option('key', 'SECTION')
1764
        self.assertEqual(value, 'value')
1765
        value = tree_config.get_option('key2')
1766
        self.assertEqual(value, 'value2')
1767
        self.assertEqual(tree_config.get_option('non-existant'), None)
1768
        value = tree_config.get_option('non-existant', 'SECTION')
1769
        self.assertEqual(value, None)
1770
        value = tree_config.get_option('non-existant', default='default')
1771
        self.assertEqual(value, 'default')
1772
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1773
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1774
        self.assertEqual(value, 'default')
1775
        value = tree_config.get_option('key3')
1776
        self.assertEqual(value, 'value3-top')
1777
        value = tree_config.get_option('key3', 'SECTION')
1778
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1779
1780
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1781
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1782
1783
    def test_get_value(self):
1784
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1785
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1786
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1787
        bzrdir_config.set_option('value', 'key', 'SECTION')
1788
        bzrdir_config.set_option('value2', 'key2')
1789
        bzrdir_config.set_option('value3-top', 'key3')
1790
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1791
        value = bzrdir_config.get_option('key', 'SECTION')
1792
        self.assertEqual(value, 'value')
1793
        value = bzrdir_config.get_option('key2')
1794
        self.assertEqual(value, 'value2')
1795
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1796
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1797
        self.assertEqual(value, None)
1798
        value = bzrdir_config.get_option('non-existant', default='default')
1799
        self.assertEqual(value, 'default')
1800
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1801
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1802
                                         default='default')
1803
        self.assertEqual(value, 'default')
1804
        value = bzrdir_config.get_option('key3')
1805
        self.assertEqual(value, 'value3-top')
1806
        value = bzrdir_config.get_option('key3', 'SECTION')
1807
        self.assertEqual(value, 'value3-section')
1808
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1809
    def test_set_unset_default_stack_on(self):
1810
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1811
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1812
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1813
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1814
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1815
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1816
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1817
        bzrdir_config.set_default_stack_on(None)
1818
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1819
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1820
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1821
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1822
1823
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1824
        super(TestConfigGetOptions, self).setUp()
1825
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1826
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1827
    # One variable in none of the above
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1828
    def test_no_variable(self):
1829
        # Using branch should query branch, locations and bazaar
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1830
        self.assertOptions([], self.branch_config)
1831
1832
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1833
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1834
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1835
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1836
1837
    def test_option_in_locations(self):
1838
        self.locations_config.set_user_option('file', 'locations')
1839
        self.assertOptions(
1840
            [('file', 'locations', self.tree.basedir, 'locations')],
1841
            self.locations_config)
1842
1843
    def test_option_in_branch(self):
1844
        self.branch_config.set_user_option('file', 'branch')
1845
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
1846
                           self.branch_config)
1847
1848
    def test_option_in_bazaar_and_branch(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1849
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1850
        self.branch_config.set_user_option('file', 'branch')
1851
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
1852
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1853
                           self.branch_config)
1854
1855
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1856
        # Hmm, locations override branch :-/
1857
        self.locations_config.set_user_option('file', 'locations')
1858
        self.branch_config.set_user_option('file', 'branch')
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1859
        self.assertOptions(
1860
            [('file', 'locations', self.tree.basedir, 'locations'),
1861
             ('file', 'branch', 'DEFAULT', 'branch'),],
1862
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1863
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1864
    def test_option_in_bazaar_locations_and_branch(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1865
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1866
        self.locations_config.set_user_option('file', 'locations')
1867
        self.branch_config.set_user_option('file', 'branch')
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1868
        self.assertOptions(
1869
            [('file', 'locations', self.tree.basedir, 'locations'),
1870
             ('file', 'branch', 'DEFAULT', 'branch'),
1871
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1872
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1873
1874
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1875
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1876
1877
    def setUp(self):
1878
        super(TestConfigRemoveOption, self).setUp()
1879
        create_configs_with_file_option(self)
1880
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1881
    def test_remove_in_locations(self):
1882
        self.locations_config.remove_user_option('file', self.tree.basedir)
1883
        self.assertOptions(
1884
            [('file', 'branch', 'DEFAULT', 'branch'),
1885
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1886
            self.branch_config)
1887
1888
    def test_remove_in_branch(self):
1889
        self.branch_config.remove_user_option('file')
1890
        self.assertOptions(
1891
            [('file', 'locations', self.tree.basedir, 'locations'),
1892
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1893
            self.branch_config)
1894
1895
    def test_remove_in_bazaar(self):
1896
        self.bazaar_config.remove_user_option('file')
1897
        self.assertOptions(
1898
            [('file', 'locations', self.tree.basedir, 'locations'),
1899
             ('file', 'branch', 'DEFAULT', 'branch'),],
1900
            self.branch_config)
1901
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
1902
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1903
class TestConfigGetSections(tests.TestCaseWithTransport):
1904
1905
    def setUp(self):
1906
        super(TestConfigGetSections, self).setUp()
1907
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1908
1909
    def assertSectionNames(self, expected, conf, name=None):
1910
        """Check which sections are returned for a given config.
1911
1912
        If fallback configurations exist their sections can be included.
1913
1914
        :param expected: A list of section names.
1915
1916
        :param conf: The configuration that will be queried.
1917
1918
        :param name: An optional section name that will be passed to
1919
            get_sections().
1920
        """
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1921
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1922
        self.assertLength(len(expected), sections)
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1923
        self.assertEqual(expected, [name for name, _, _ in sections])
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1924
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1925
    def test_bazaar_default_section(self):
1926
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1927
1928
    def test_locations_default_section(self):
1929
        # No sections are defined in an empty file
1930
        self.assertSectionNames([], self.locations_config)
1931
1932
    def test_locations_named_section(self):
1933
        self.locations_config.set_user_option('file', 'locations')
1934
        self.assertSectionNames([self.tree.basedir], self.locations_config)
1935
1936
    def test_locations_matching_sections(self):
1937
        loc_config = self.locations_config
1938
        loc_config.set_user_option('file', 'locations')
1939
        # We need to cheat a bit here to create an option in sections above and
1940
        # below the 'location' one.
1941
        parser = loc_config._get_parser()
1942
        # locations.cong deals with '/' ignoring native os.sep
1943
        location_names = self.tree.basedir.split('/')
1944
        parent = '/'.join(location_names[:-1])
1945
        child = '/'.join(location_names + ['child'])
1946
        parser[parent] = {}
1947
        parser[parent]['file'] = 'parent'
1948
        parser[child] = {}
1949
        parser[child]['file'] = 'child'
1950
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
1951
1952
    def test_branch_data_default_section(self):
1953
        self.assertSectionNames([None],
1954
                                self.branch_config._get_branch_data_config())
1955
1956
    def test_branch_default_sections(self):
1957
        # No sections are defined in an empty locations file
1958
        self.assertSectionNames([None, 'DEFAULT'],
1959
                                self.branch_config)
1960
        # Unless we define an option
1961
        self.branch_config._get_location_config().set_user_option(
1962
            'file', 'locations')
1963
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
1964
                                self.branch_config)
1965
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1966
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1967
        # We need to cheat as the API doesn't give direct access to sections
1968
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1969
        self.bazaar_config.set_alias('bazaar', 'bzr')
1970
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1971
1972
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1973
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1974
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1975
1976
    def _got_user_passwd(self, expected_user, expected_password,
1977
                         config, *args, **kwargs):
1978
        credentials = config.get_credentials(*args, **kwargs)
1979
        if credentials is None:
1980
            user = None
1981
            password = None
1982
        else:
1983
            user = credentials['user']
1984
            password = credentials['password']
1985
        self.assertEquals(expected_user, user)
1986
        self.assertEquals(expected_password, password)
1987
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1988
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1989
        conf = config.AuthenticationConfig(_file=StringIO())
1990
        self.assertEquals({}, conf._get_config())
1991
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1992
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1993
    def test_missing_auth_section_header(self):
1994
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1995
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1996
1997
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1998
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1999
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2000
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2001
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2002
        conf = config.AuthenticationConfig(_file=StringIO(
2003
                """[broken]
2004
scheme=ftp
2005
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2006
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2007
"""))
2008
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2009
2010
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
2011
        conf = config.AuthenticationConfig(_file=StringIO(
2012
                """[broken]
2013
scheme=ftp
2014
user=joe
2015
port=port # Error: Not an int
2016
"""))
2017
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2018
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2019
    def test_unknown_password_encoding(self):
2020
        conf = config.AuthenticationConfig(_file=StringIO(
2021
                """[broken]
2022
scheme=ftp
2023
user=joe
2024
password_encoding=unknown
2025
"""))
2026
        self.assertRaises(ValueError, conf.get_password,
2027
                          'ftp', 'foo.net', 'joe')
2028
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2029
    def test_credentials_for_scheme_host(self):
2030
        conf = config.AuthenticationConfig(_file=StringIO(
2031
                """# Identity on foo.net
2032
[ftp definition]
2033
scheme=ftp
2034
host=foo.net
2035
user=joe
2036
password=secret-pass
2037
"""))
2038
        # Basic matching
2039
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
2040
        # different scheme
2041
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
2042
        # different host
2043
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
2044
2045
    def test_credentials_for_host_port(self):
2046
        conf = config.AuthenticationConfig(_file=StringIO(
2047
                """# Identity on foo.net
2048
[ftp definition]
2049
scheme=ftp
2050
port=10021
2051
host=foo.net
2052
user=joe
2053
password=secret-pass
2054
"""))
2055
        # No port
2056
        self._got_user_passwd('joe', 'secret-pass',
2057
                              conf, 'ftp', 'foo.net', port=10021)
2058
        # different port
2059
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
2060
2061
    def test_for_matching_host(self):
2062
        conf = config.AuthenticationConfig(_file=StringIO(
2063
                """# Identity on foo.net
2064
[sourceforge]
2065
scheme=bzr
2066
host=bzr.sf.net
2067
user=joe
2068
password=joepass
2069
[sourceforge domain]
2070
scheme=bzr
2071
host=.bzr.sf.net
2072
user=georges
2073
password=bendover
2074
"""))
2075
        # matching domain
2076
        self._got_user_passwd('georges', 'bendover',
2077
                              conf, 'bzr', 'foo.bzr.sf.net')
2078
        # phishing attempt
2079
        self._got_user_passwd(None, None,
2080
                              conf, 'bzr', 'bbzr.sf.net')
2081
2082
    def test_for_matching_host_None(self):
2083
        conf = config.AuthenticationConfig(_file=StringIO(
2084
                """# Identity on foo.net
2085
[catchup bzr]
2086
scheme=bzr
2087
user=joe
2088
password=joepass
2089
[DEFAULT]
2090
user=georges
2091
password=bendover
2092
"""))
2093
        # match no host
2094
        self._got_user_passwd('joe', 'joepass',
2095
                              conf, 'bzr', 'quux.net')
2096
        # no host but different scheme
2097
        self._got_user_passwd('georges', 'bendover',
2098
                              conf, 'ftp', 'quux.net')
2099
2100
    def test_credentials_for_path(self):
2101
        conf = config.AuthenticationConfig(_file=StringIO(
2102
                """
2103
[http dir1]
2104
scheme=http
2105
host=bar.org
2106
path=/dir1
2107
user=jim
2108
password=jimpass
2109
[http dir2]
2110
scheme=http
2111
host=bar.org
2112
path=/dir2
2113
user=georges
2114
password=bendover
2115
"""))
2116
        # no path no dice
2117
        self._got_user_passwd(None, None,
2118
                              conf, 'http', host='bar.org', path='/dir3')
2119
        # matching path
2120
        self._got_user_passwd('georges', 'bendover',
2121
                              conf, 'http', host='bar.org', path='/dir2')
2122
        # matching subdir
2123
        self._got_user_passwd('jim', 'jimpass',
2124
                              conf, 'http', host='bar.org',path='/dir1/subdir')
2125
2126
    def test_credentials_for_user(self):
2127
        conf = config.AuthenticationConfig(_file=StringIO(
2128
                """
2129
[with user]
2130
scheme=http
2131
host=bar.org
2132
user=jim
2133
password=jimpass
2134
"""))
2135
        # Get user
2136
        self._got_user_passwd('jim', 'jimpass',
2137
                              conf, 'http', 'bar.org')
2138
        # Get same user
2139
        self._got_user_passwd('jim', 'jimpass',
2140
                              conf, 'http', 'bar.org', user='jim')
2141
        # Don't get a different user if one is specified
2142
        self._got_user_passwd(None, None,
2143
                              conf, 'http', 'bar.org', user='georges')
2144
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
2145
    def test_credentials_for_user_without_password(self):
2146
        conf = config.AuthenticationConfig(_file=StringIO(
2147
                """
2148
[without password]
2149
scheme=http
2150
host=bar.org
2151
user=jim
2152
"""))
2153
        # Get user but no password
2154
        self._got_user_passwd('jim', None,
2155
                              conf, 'http', 'bar.org')
2156
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2157
    def test_verify_certificates(self):
2158
        conf = config.AuthenticationConfig(_file=StringIO(
2159
                """
2160
[self-signed]
2161
scheme=https
2162
host=bar.org
2163
user=jim
2164
password=jimpass
2165
verify_certificates=False
2166
[normal]
2167
scheme=https
2168
host=foo.net
2169
user=georges
2170
password=bendover
2171
"""))
2172
        credentials = conf.get_credentials('https', 'bar.org')
2173
        self.assertEquals(False, credentials.get('verify_certificates'))
2174
        credentials = conf.get_credentials('https', 'foo.net')
2175
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2176
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2177
2178
class TestAuthenticationStorage(tests.TestCaseInTempDir):
2179
3777.1.8 by Aaron Bentley
Commit work-in-progress
2180
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2181
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2182
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
2183
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
2184
        credentials = conf.get_credentials(host='host', scheme='scheme',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
2185
                                           port=99, path='/foo',
2186
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2187
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2188
                       'verify_certificates': False, 'scheme': 'scheme', 
2189
                       'host': 'host', 'port': 99, 'path': '/foo', 
2190
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2191
        self.assertEqual(CREDENTIALS, credentials)
2192
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
2193
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2194
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
2195
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2196
    def test_reset_credentials_different_name(self):
2197
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2198
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
2199
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2200
        self.assertIs(None, conf._get_config().get('name'))
2201
        credentials = conf.get_credentials(host='host', scheme='scheme')
2202
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2203
                       'password', 'verify_certificates': True, 
2204
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
2205
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2206
        self.assertEqual(CREDENTIALS, credentials)
2207
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2208
2900.2.14 by Vincent Ladeuil
More tests.
2209
class TestAuthenticationConfig(tests.TestCase):
2210
    """Test AuthenticationConfig behaviour"""
2211
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2212
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2213
                                       host=None, port=None, realm=None,
2214
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
2215
        if host is None:
2216
            host = 'bar.org'
2217
        user, password = 'jim', 'precious'
2218
        expected_prompt = expected_prompt_format % {
2219
            'scheme': scheme, 'host': host, 'port': port,
2220
            'user': user, 'realm': realm}
2221
2222
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2223
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
2224
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2225
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
2226
        # We use an empty conf so that the user is always prompted
2227
        conf = config.AuthenticationConfig()
2228
        self.assertEquals(password,
2229
                          conf.get_password(scheme, host, user, port=port,
2230
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2231
        self.assertEquals(expected_prompt, stderr.getvalue())
2232
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
2233
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2234
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2235
                                       host=None, port=None, realm=None,
2236
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2237
        if host is None:
2238
            host = 'bar.org'
2239
        username = 'jim'
2240
        expected_prompt = expected_prompt_format % {
2241
            'scheme': scheme, 'host': host, 'port': port,
2242
            'realm': realm}
2243
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2244
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2245
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2246
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2247
        # We use an empty conf so that the user is always prompted
2248
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
2249
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
2250
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2251
        self.assertEquals(expected_prompt, stderr.getvalue())
2252
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2253
2254
    def test_username_defaults_prompts(self):
2255
        # HTTP prompts can't be tested here, see test_http.py
2256
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
2257
        self._check_default_username_prompt(
2258
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
2259
        self._check_default_username_prompt(
2260
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
2261
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2262
    def test_username_default_no_prompt(self):
2263
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2264
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2265
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2266
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2267
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
2268
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2269
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
2270
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2271
        self._check_default_password_prompt(
2272
            'FTP %(user)s@%(host)s password: ', 'ftp')
2273
        self._check_default_password_prompt(
2274
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
2275
        self._check_default_password_prompt(
2276
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
2277
        # SMTP port handling is a bit special (it's handled if embedded in the
2278
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
2279
        # FIXME: should we: forbid that, extend it to other schemes, leave
2280
        # things as they are that's fine thank you ?
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2281
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2282
                                            'smtp')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2283
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2284
                                            'smtp', host='bar.org:10025')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2285
        self._check_default_password_prompt(
2900.2.14 by Vincent Ladeuil
More tests.
2286
            'SMTP %(user)s@%(host)s:%(port)d password: ',
2287
            'smtp', port=10025)
2288
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2289
    def test_ssh_password_emits_warning(self):
2290
        conf = config.AuthenticationConfig(_file=StringIO(
2291
                """
2292
[ssh with password]
2293
scheme=ssh
2294
host=bar.org
2295
user=jim
2296
password=jimpass
2297
"""))
2298
        entered_password = 'typed-by-hand'
2299
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2300
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2301
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2302
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2303
2304
        # Since the password defined in the authentication config is ignored,
2305
        # the user is prompted
2306
        self.assertEquals(entered_password,
2307
                          conf.get_password('ssh', 'bar.org', user='jim'))
2308
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
2309
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2310
            'password ignored in section \[ssh with password\]')
2311
3420.1.3 by Vincent Ladeuil
John's review feedback.
2312
    def test_ssh_without_password_doesnt_emit_warning(self):
2313
        conf = config.AuthenticationConfig(_file=StringIO(
2314
                """
2315
[ssh with password]
2316
scheme=ssh
2317
host=bar.org
2318
user=jim
2319
"""))
2320
        entered_password = 'typed-by-hand'
2321
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2322
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
2323
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2324
                                            stdout=stdout,
2325
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
2326
2327
        # Since the password defined in the authentication config is ignored,
2328
        # the user is prompted
2329
        self.assertEquals(entered_password,
2330
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
2331
        # No warning shoud be emitted since there is no password. We are only
2332
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
2333
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
2334
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
2335
            'password ignored in section \[ssh with password\]')
2336
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2337
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2338
        self.overrideAttr(config, 'credential_store_registry',
2339
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2340
        store = StubCredentialStore()
2341
        store.add_credentials("http", "example.com", "joe", "secret")
2342
        config.credential_store_registry.register("stub", store, fallback=True)
2343
        conf = config.AuthenticationConfig(_file=StringIO())
2344
        creds = conf.get_credentials("http", "example.com")
2345
        self.assertEquals("joe", creds["user"])
2346
        self.assertEquals("secret", creds["password"])
2347
2900.2.14 by Vincent Ladeuil
More tests.
2348
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2349
class StubCredentialStore(config.CredentialStore):
2350
2351
    def __init__(self):
2352
        self._username = {}
2353
        self._password = {}
2354
2355
    def add_credentials(self, scheme, host, user, password=None):
2356
        self._username[(scheme, host)] = user
2357
        self._password[(scheme, host)] = password
2358
2359
    def get_credentials(self, scheme, host, port=None, user=None,
2360
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2361
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2362
        if not key in self._username:
2363
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2364
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2365
                "user": self._username[key], "password": self._password[key]}
2366
2367
2368
class CountingCredentialStore(config.CredentialStore):
2369
2370
    def __init__(self):
2371
        self._calls = 0
2372
2373
    def get_credentials(self, scheme, host, port=None, user=None,
2374
        path=None, realm=None):
2375
        self._calls += 1
2376
        return None
2377
2378
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2379
class TestCredentialStoreRegistry(tests.TestCase):
2380
2381
    def _get_cs_registry(self):
2382
        return config.credential_store_registry
2383
2384
    def test_default_credential_store(self):
2385
        r = self._get_cs_registry()
2386
        default = r.get_credential_store(None)
2387
        self.assertIsInstance(default, config.PlainTextCredentialStore)
2388
2389
    def test_unknown_credential_store(self):
2390
        r = self._get_cs_registry()
2391
        # It's hard to imagine someone creating a credential store named
2392
        # 'unknown' so we use that as an never registered key.
2393
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
2394
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2395
    def test_fallback_none_registered(self):
2396
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2397
        self.assertEquals(None,
2398
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2399
2400
    def test_register(self):
2401
        r = config.CredentialStoreRegistry()
2402
        r.register("stub", StubCredentialStore(), fallback=False)
2403
        r.register("another", StubCredentialStore(), fallback=True)
2404
        self.assertEquals(["another", "stub"], r.keys())
2405
2406
    def test_register_lazy(self):
2407
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2408
        r.register_lazy("stub", "bzrlib.tests.test_config",
2409
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2410
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2411
        self.assertIsInstance(r.get_credential_store("stub"),
2412
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2413
2414
    def test_is_fallback(self):
2415
        r = config.CredentialStoreRegistry()
2416
        r.register("stub1", None, fallback=False)
2417
        r.register("stub2", None, fallback=True)
2418
        self.assertEquals(False, r.is_fallback("stub1"))
2419
        self.assertEquals(True, r.is_fallback("stub2"))
2420
2421
    def test_no_fallback(self):
2422
        r = config.CredentialStoreRegistry()
2423
        store = CountingCredentialStore()
2424
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2425
        self.assertEquals(None,
2426
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2427
        self.assertEquals(0, store._calls)
2428
2429
    def test_fallback_credentials(self):
2430
        r = config.CredentialStoreRegistry()
2431
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2432
        store.add_credentials("http", "example.com",
2433
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2434
        r.register("stub", store, fallback=True)
2435
        creds = r.get_fallback_credentials("http", "example.com")
2436
        self.assertEquals("somebody", creds["user"])
2437
        self.assertEquals("geheim", creds["password"])
2438
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2439
    def test_fallback_first_wins(self):
2440
        r = config.CredentialStoreRegistry()
2441
        stub1 = StubCredentialStore()
2442
        stub1.add_credentials("http", "example.com",
2443
                              "somebody", "stub1")
2444
        r.register("stub1", stub1, fallback=True)
2445
        stub2 = StubCredentialStore()
2446
        stub2.add_credentials("http", "example.com",
2447
                              "somebody", "stub2")
2448
        r.register("stub2", stub1, fallback=True)
2449
        creds = r.get_fallback_credentials("http", "example.com")
2450
        self.assertEquals("somebody", creds["user"])
2451
        self.assertEquals("stub1", creds["password"])
2452
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2453
2454
class TestPlainTextCredentialStore(tests.TestCase):
2455
2456
    def test_decode_password(self):
2457
        r = config.credential_store_registry
2458
        plain_text = r.get_credential_store()
2459
        decoded = plain_text.decode_password(dict(password='secret'))
2460
        self.assertEquals('secret', decoded)
2461
2462
2900.2.14 by Vincent Ladeuil
More tests.
2463
# FIXME: Once we have a way to declare authentication to all test servers, we
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2464
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2465
# test_user_password_in_url
2466
# test_user_in_url_password_from_config
2467
# test_user_in_url_password_prompted
2468
# test_user_in_config
2469
# test_user_getpass.getuser
2470
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2471
class TestAuthenticationRing(tests.TestCaseWithTransport):
2472
    pass
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
2473
2474
2475
class TestAutoUserId(tests.TestCase):
2476
    """Test inferring an automatic user name."""
2477
2478
    def test_auto_user_id(self):
2479
        """Automatic inference of user name.
2480
        
2481
        This is a bit hard to test in an isolated way, because it depends on
2482
        system functions that go direct to /etc or perhaps somewhere else.
2483
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
2484
        to be able to choose a user name with no configuration.
2485
        """
2486
        if sys.platform == 'win32':
2487
            raise TestSkipped("User name inference not implemented on win32")
2488
        realname, address = config._auto_user_id()
2489
        if os.path.exists('/etc/mailname'):
2490
            self.assertTrue(realname)
2491
            self.assertTrue(address)
2492
        else:
2493
            self.assertEquals((None, None), (realname, address))
2494