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