/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
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
543
class TestIniConfigSaving(tests.TestCaseInTempDir):
544
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
545
    def test_cant_save_without_a_file_name(self):
546
        conf = config.IniBasedConfig()
547
        self.assertRaises(AssertionError, conf._write_config_file)
548
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
549
    def test_saved_with_content(self):
550
        content = 'foo = bar\n'
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
551
        conf = config.IniBasedConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
552
            content, file_name='./test.conf', save=True)
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
553
        self.assertFileEqual(content, 'test.conf')
554
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
555
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
556
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
557
558
    def test_cannot_reload_without_name(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
559
        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.
560
        self.assertRaises(AssertionError, conf.reload)
561
562
    def test_reload_see_new_value(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
563
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
564
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
565
        c1._write_config_file()
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
566
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
567
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
568
        c2._write_config_file()
569
        self.assertEqual('vim', c1.get_user_option('editor'))
570
        self.assertEqual('emacs', c2.get_user_option('editor'))
571
        # Make sure we get the Right value
572
        c1.reload()
573
        self.assertEqual('emacs', c1.get_user_option('editor'))
574
575
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
576
class TestLockableConfig(tests.TestCaseInTempDir):
577
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
578
    scenarios = lockable_config_scenarios()
579
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
580
    # Set by load_tests
581
    config_class = None
582
    config_args = None
583
    config_section = None
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
584
585
    def setUp(self):
586
        super(TestLockableConfig, self).setUp()
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
587
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
588
        self.config = self.create_config(self._content)
589
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
590
    def get_existing_config(self):
591
        return self.config_class(*self.config_args)
592
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
593
    def create_config(self, content):
5396.1.1 by Vincent Ladeuil
Fix python-2.6-ism.
594
        kwargs = dict(save=True)
595
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
596
        return c
597
598
    def test_simple_read_access(self):
599
        self.assertEquals('1', self.config.get_user_option('one'))
600
601
    def test_simple_write_access(self):
602
        self.config.set_user_option('one', 'one')
603
        self.assertEquals('one', self.config.get_user_option('one'))
604
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
605
    def test_listen_to_the_last_speaker(self):
606
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
607
        c2 = self.get_existing_config()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
608
        c1.set_user_option('one', 'ONE')
609
        c2.set_user_option('two', 'TWO')
610
        self.assertEquals('ONE', c1.get_user_option('one'))
611
        self.assertEquals('TWO', c2.get_user_option('two'))
612
        # The second update respect the first one
613
        self.assertEquals('ONE', c2.get_user_option('one'))
614
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
615
    def test_last_speaker_wins(self):
616
        # If the same config is not shared, the same variable modified twice
617
        # can only see a single result.
618
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
619
        c2 = self.get_existing_config()
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
620
        c1.set_user_option('one', 'c1')
621
        c2.set_user_option('one', 'c2')
622
        self.assertEquals('c2', c2._get_user_option('one'))
623
        # The first modification is still available until another refresh
624
        # occur
625
        self.assertEquals('c1', c1._get_user_option('one'))
626
        c1.set_user_option('two', 'done')
627
        self.assertEquals('c2', c1._get_user_option('one'))
628
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
629
    def test_writes_are_serialized(self):
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
630
        c1 = self.config
631
        c2 = self.get_existing_config()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
632
633
        # We spawn a thread that will pause *during* the write
634
        before_writing = threading.Event()
635
        after_writing = threading.Event()
636
        writing_done = threading.Event()
637
        c1_orig = c1._write_config_file
638
        def c1_write_config_file():
639
            before_writing.set()
640
            c1_orig()
641
            # The lock is held we wait for the main thread to decide when to
642
            # continue
643
            after_writing.wait()
644
        c1._write_config_file = c1_write_config_file
645
        def c1_set_option():
646
            c1.set_user_option('one', 'c1')
647
            writing_done.set()
648
        t1 = threading.Thread(target=c1_set_option)
649
        # Collect the thread after the test
650
        self.addCleanup(t1.join)
651
        # Be ready to unblock the thread if the test goes wrong
652
        self.addCleanup(after_writing.set)
653
        t1.start()
654
        before_writing.wait()
655
        self.assertTrue(c1._lock.is_held)
656
        self.assertRaises(errors.LockContention,
657
                          c2.set_user_option, 'one', 'c2')
658
        self.assertEquals('c1', c1.get_user_option('one'))
659
        # Let the lock be released
660
        after_writing.set()
661
        writing_done.wait()
662
        c2.set_user_option('one', 'c2')
663
        self.assertEquals('c2', c2.get_user_option('one'))
664
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
665
    def test_read_while_writing(self):
666
       c1 = self.config
667
       # We spawn a thread that will pause *during* the write
668
       ready_to_write = threading.Event()
669
       do_writing = threading.Event()
670
       writing_done = threading.Event()
671
       c1_orig = c1._write_config_file
672
       def c1_write_config_file():
673
           ready_to_write.set()
674
           # The lock is held we wait for the main thread to decide when to
675
           # continue
676
           do_writing.wait()
677
           c1_orig()
678
           writing_done.set()
679
       c1._write_config_file = c1_write_config_file
680
       def c1_set_option():
681
           c1.set_user_option('one', 'c1')
682
       t1 = threading.Thread(target=c1_set_option)
683
       # Collect the thread after the test
684
       self.addCleanup(t1.join)
685
       # Be ready to unblock the thread if the test goes wrong
686
       self.addCleanup(do_writing.set)
687
       t1.start()
688
       # Ensure the thread is ready to write
689
       ready_to_write.wait()
690
       self.assertTrue(c1._lock.is_held)
691
       self.assertEquals('c1', c1.get_user_option('one'))
692
       # If we read during the write, we get the old value
693
       c2 = self.get_existing_config()
694
       self.assertEquals('1', c2.get_user_option('one'))
695
       # Let the writing occur and ensure it occurred
696
       do_writing.set()
697
       writing_done.wait()
698
       # Now we get the updated value
699
       c3 = self.get_existing_config()
700
       self.assertEquals('c1', c3.get_user_option('one'))
701
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
702
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
703
class TestGetUserOptionAs(TestIniConfig):
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
704
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
705
    def test_get_user_option_as_bool(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
706
        conf, parser = self.make_config_parser("""
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
707
a_true_bool = true
708
a_false_bool = 0
709
an_invalid_bool = maybe
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
710
a_list = hmm, who knows ? # This is interpreted as a list !
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
711
""")
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
712
        get_bool = conf.get_user_option_as_bool
713
        self.assertEqual(True, get_bool('a_true_bool'))
714
        self.assertEqual(False, get_bool('a_false_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
715
        warnings = []
716
        def warning(*args):
717
            warnings.append(args[0] % args[1:])
718
        self.overrideAttr(trace, 'warning', warning)
719
        msg = 'Value "%s" is not a boolean for "%s"'
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
720
        self.assertIs(None, get_bool('an_invalid_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
721
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
722
        warnings = []
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
723
        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.
724
        self.assertEquals([], warnings)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
725
726
    def test_get_user_option_as_list(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
727
        conf, parser = self.make_config_parser("""
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
728
a_list = a,b,c
729
length_1 = 1,
730
one_item = x
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
731
""")
732
        get_list = conf.get_user_option_as_list
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
733
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
734
        self.assertEqual(['1'], get_list('length_1'))
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
735
        self.assertEqual('x', conf.get_user_option('one_item'))
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
736
        # automatically cast to list
737
        self.assertEqual(['x'], get_list('one_item'))
738
739
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
740
class TestSupressWarning(TestIniConfig):
741
742
    def make_warnings_config(self, s):
743
        conf, parser = self.make_config_parser(s)
744
        return conf.suppress_warning
745
746
    def test_suppress_warning_unknown(self):
747
        suppress_warning = self.make_warnings_config('')
748
        self.assertEqual(False, suppress_warning('unknown_warning'))
749
750
    def test_suppress_warning_known(self):
751
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
752
        self.assertEqual(False, suppress_warning('c'))
753
        self.assertEqual(True, suppress_warning('a'))
754
        self.assertEqual(True, suppress_warning('b'))
755
756
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
757
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
758
759
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
760
        my_config = config.GlobalConfig()
761
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
762
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
763
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
764
        oldparserclass = config.ConfigObj
765
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
766
        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.
767
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
768
            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.
769
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
770
            config.ConfigObj = oldparserclass
771
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1551.2.20 by Aaron Bentley
Treated config files as utf-8
772
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
773
                                          '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.
774
775
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
776
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
777
778
    def test_constructs(self):
779
        branch = FakeBranch()
780
        my_config = config.BranchConfig(branch)
781
        self.assertRaises(TypeError, config.BranchConfig)
782
783
    def test_get_location_config(self):
784
        branch = FakeBranch()
785
        my_config = config.BranchConfig(branch)
786
        location_config = my_config._get_location_config()
787
        self.assertEqual(branch.base, location_config.location)
788
        self.failUnless(location_config is my_config._get_location_config())
789
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
790
    def test_get_config(self):
791
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
792
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
793
        my_config = b.get_config()
794
        self.assertIs(my_config.get_user_option('wacky'), None)
795
        my_config.set_user_option('wacky', 'unlikely')
796
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
797
798
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
799
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
800
        my_config2 = b2.get_config()
801
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
802
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
803
    def test_has_explicit_nickname(self):
804
        b = self.make_branch('.')
805
        self.assertFalse(b.get_config().has_explicit_nickname())
806
        b.nick = 'foo'
807
        self.assertTrue(b.get_config().has_explicit_nickname())
808
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
809
    def test_config_url(self):
810
        """The Branch.get_config will use section that uses a local url"""
811
        branch = self.make_branch('branch')
812
        self.assertEqual('branch', branch.nick)
813
814
        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
815
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
816
            '[%s]\nnickname = foobar' % (local_url,),
817
            local_url, save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
818
        self.assertEqual('foobar', branch.nick)
819
820
    def test_config_local_path(self):
821
        """The Branch.get_config will use a local system path"""
822
        branch = self.make_branch('branch')
823
        self.assertEqual('branch', branch.nick)
824
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
825
        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
826
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
827
            '[%s/branch]\nnickname = barry' % (local_path,),
828
            'branch',  save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
829
        self.assertEqual('barry', branch.nick)
830
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
831
    def test_config_creates_local(self):
832
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
833
        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
834
        branch.set_push_location('http://foobar')
835
        local_path = osutils.getcwd().encode('utf8')
836
        # Surprisingly ConfigObj doesn't create a trailing newline
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
837
        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.
838
                                 '[%s/branch]\n'
839
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
840
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
841
                                 % (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
842
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
843
    def test_autonick_urlencoded(self):
844
        b = self.make_branch('!repo')
845
        self.assertEqual('!repo', b.get_config().get_nickname())
846
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
847
    def test_warn_if_masked(self):
848
        warnings = []
849
        def warning(*args):
850
            warnings.append(args[0] % args[1:])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
851
        self.overrideAttr(trace, 'warning', warning)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
852
853
        def set_option(store, warn_masked=True):
854
            warnings[:] = []
855
            conf.set_user_option('example_option', repr(store), store=store,
856
                                 warn_masked=warn_masked)
857
        def assertWarning(warning):
858
            if warning is None:
859
                self.assertEqual(0, len(warnings))
860
            else:
861
                self.assertEqual(1, len(warnings))
862
                self.assertEqual(warning, warnings[0])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
863
        branch = self.make_branch('.')
864
        conf = branch.get_config()
865
        set_option(config.STORE_GLOBAL)
866
        assertWarning(None)
867
        set_option(config.STORE_BRANCH)
868
        assertWarning(None)
869
        set_option(config.STORE_GLOBAL)
870
        assertWarning('Value "4" is masked by "3" from branch.conf')
871
        set_option(config.STORE_GLOBAL, warn_masked=False)
872
        assertWarning(None)
873
        set_option(config.STORE_LOCATION)
874
        assertWarning(None)
875
        set_option(config.STORE_BRANCH)
876
        assertWarning('Value "3" is masked by "0" from locations.conf')
877
        set_option(config.STORE_BRANCH, warn_masked=False)
878
        assertWarning(None)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
879
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
880
5448.1.1 by Vincent Ladeuil
Use TestCaseInTempDir for tests requiring disk resources
881
class TestGlobalConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
882
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
883
    def test_user_id(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
884
        my_config = config.GlobalConfig.from_string(sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
885
        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
886
                         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.
887
888
    def test_absent_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
889
        my_config = config.GlobalConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
890
        self.assertEqual(None, my_config._get_user_id())
891
892
    def test_configured_editor(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
893
        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
894
        self.assertEqual("vim", my_config.get_editor())
895
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
896
    def test_signatures_always(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
897
        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
898
        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
899
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
900
        self.assertEqual(config.SIGN_ALWAYS,
901
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
902
        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
903
904
    def test_signatures_if_possible(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
905
        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
906
        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
907
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
908
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
909
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
910
        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
911
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
912
    def test_signatures_ignore(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
913
        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
914
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
915
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
916
        self.assertEqual(config.SIGN_NEVER,
917
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
918
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
919
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
920
    def _get_sample_config(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
921
        my_config = config.GlobalConfig.from_string(sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
922
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
923
1442.1.56 by Robert Collins
gpg_signing_command configuration item
924
    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.
925
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
926
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
927
        self.assertEqual(False, my_config.signature_needed())
928
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
929
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
930
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
931
        return my_config
932
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
933
    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.
934
        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.
935
        self.assertEqual("gpg", my_config.gpg_signing_command())
936
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
937
    def test_get_user_option_default(self):
938
        my_config = self._get_empty_config()
939
        self.assertEqual(None, my_config.get_user_option('no_option'))
940
941
    def test_get_user_option_global(self):
942
        my_config = self._get_sample_config()
943
        self.assertEqual("something",
944
                         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.
945
1472 by Robert Collins
post commit hook, first pass implementation
946
    def test_post_commit_default(self):
947
        my_config = self._get_sample_config()
948
        self.assertEqual(None, my_config.post_commit())
949
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
950
    def test_configured_logformat(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
951
        my_config = self._get_sample_config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
952
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
953
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
954
    def test_get_alias(self):
955
        my_config = self._get_sample_config()
956
        self.assertEqual('help', my_config.get_alias('h'))
957
2900.3.6 by Tim Penhey
Added tests.
958
    def test_get_aliases(self):
959
        my_config = self._get_sample_config()
960
        aliases = my_config.get_aliases()
961
        self.assertEqual(2, len(aliases))
962
        sorted_keys = sorted(aliases)
963
        self.assertEqual('help', aliases[sorted_keys[0]])
964
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
965
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
966
    def test_get_no_alias(self):
967
        my_config = self._get_sample_config()
968
        self.assertEqual(None, my_config.get_alias('foo'))
969
970
    def test_get_long_alias(self):
971
        my_config = self._get_sample_config()
972
        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.
973
4603.1.10 by Aaron Bentley
Provide change editor via config.
974
    def test_get_change_editor(self):
975
        my_config = self._get_sample_config()
976
        change_editor = my_config.get_change_editor('old', 'new')
977
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
978
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
979
                         ' '.join(change_editor.command_template))
980
981
    def test_get_no_change_editor(self):
982
        my_config = self._get_empty_config()
983
        change_editor = my_config.get_change_editor('old', 'new')
984
        self.assertIs(None, change_editor)
985
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
986
    def test_get_merge_tools(self):
987
        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.
988
        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.
989
        self.log(repr(tools))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
990
        self.assertEqual(
991
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
992
            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.
993
            tools)
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
994
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
995
    def test_get_merge_tools_empty(self):
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
996
        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.
997
        tools = conf.get_merge_tools()
998
        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.
999
1000
    def test_find_merge_tool(self):
1001
        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.
1002
        cmdline = conf.find_merge_tool('sometool')
1003
        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.
1004
1005
    def test_find_merge_tool_not_found(self):
1006
        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.
1007
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1008
        self.assertIs(cmdline, None)
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1009
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.
1010
    def test_find_merge_tool_known(self):
1011
        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.
1012
        cmdline = conf.find_merge_tool('kdiff3')
1013
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', 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.
1014
        
1015
    def test_find_merge_tool_override_known(self):
1016
        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.
1017
        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.
1018
        cmdline = conf.find_merge_tool('kdiff3')
1019
        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.
1020
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1021
2900.3.6 by Tim Penhey
Added tests.
1022
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1023
1024
    def test_empty(self):
1025
        my_config = config.GlobalConfig()
1026
        self.assertEqual(0, len(my_config.get_aliases()))
1027
1028
    def test_set_alias(self):
1029
        my_config = config.GlobalConfig()
1030
        alias_value = 'commit --strict'
1031
        my_config.set_alias('commit', alias_value)
1032
        new_config = config.GlobalConfig()
1033
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1034
1035
    def test_remove_alias(self):
1036
        my_config = config.GlobalConfig()
1037
        my_config.set_alias('commit', 'commit --strict')
1038
        # Now remove the alias again.
1039
        my_config.unset_alias('commit')
1040
        new_config = config.GlobalConfig()
1041
        self.assertIs(None, new_config.get_alias('commit'))
1042
1043
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1044
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1045
1046
    def test_constructs(self):
1047
        my_config = config.LocationConfig('http://example.com')
1048
        self.assertRaises(TypeError, config.LocationConfig)
1049
1050
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1051
        # This is testing the correct file names are provided.
1052
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1053
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1054
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1055
        oldparserclass = config.ConfigObj
1056
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1057
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1058
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1059
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1060
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1061
            config.ConfigObj = oldparserclass
1062
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1063
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1064
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1065
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1066
1067
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1068
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1069
        global_config = my_config._get_global_config()
1070
        self.failUnless(isinstance(global_config, config.GlobalConfig))
1071
        self.failUnless(global_config is my_config._get_global_config())
1072
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1073
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1074
        self.get_branch_config('/')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1075
        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.
1076
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1077
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1078
        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
1079
        self.assertEqual([('http://www.example.com', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1080
                         self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1081
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1082
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1083
        self.get_branch_config('http://www.example.com-com')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1084
        self.assertEqual([], self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1085
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1086
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1087
        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
1088
        self.assertEqual([('http://www.example.com', 'com')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1089
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1090
1993.3.5 by James Henstridge
add back recurse=False option to config file
1091
    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
1092
        self.get_branch_config('http://www.example.com/ignoreparent')
1093
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1094
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1095
1993.3.5 by James Henstridge
add back recurse=False option to config file
1096
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1097
        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
1098
            'http://www.example.com/ignoreparent/childbranch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1099
        self.assertEqual([('http://www.example.com/ignoreparent',
1100
                           'childbranch')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1101
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1102
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1103
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1104
        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
1105
        self.assertEqual([('/b/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1106
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1107
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1108
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1109
        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
1110
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1111
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1112
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1113
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1114
        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
1115
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1116
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1117
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1118
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1119
        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
1120
        self.assertEqual([('/a/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1121
                         self.my_location_config._get_matching_sections())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1122
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1123
    def test__get_matching_sections_explicit_over_glob(self):
1124
        # XXX: 2006-09-08 jamesh
1125
        # This test only passes because ord('c') > ord('*').  If there
1126
        # was a config section for '/a/?', it would get precedence
1127
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1128
        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
1129
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1130
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1131
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
1132
    def test__get_option_policy_normal(self):
1133
        self.get_branch_config('http://www.example.com')
1134
        self.assertEqual(
1135
            self.my_location_config._get_config_policy(
1136
            'http://www.example.com', 'normal_option'),
1137
            config.POLICY_NONE)
1138
1139
    def test__get_option_policy_norecurse(self):
1140
        self.get_branch_config('http://www.example.com')
1141
        self.assertEqual(
1142
            self.my_location_config._get_option_policy(
1143
            'http://www.example.com', 'norecurse_option'),
1144
            config.POLICY_NORECURSE)
1145
        # Test old recurse=False setting:
1146
        self.assertEqual(
1147
            self.my_location_config._get_option_policy(
1148
            'http://www.example.com/norecurse', 'normal_option'),
1149
            config.POLICY_NORECURSE)
1150
1151
    def test__get_option_policy_normal(self):
1152
        self.get_branch_config('http://www.example.com')
1153
        self.assertEqual(
1154
            self.my_location_config._get_option_policy(
1155
            'http://www.example.com', 'appendpath_option'),
1156
            config.POLICY_APPENDPATH)
1157
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1158
    def test__get_options_with_policy(self):
1159
        self.get_branch_config('/dir/subdir',
1160
                               location_config="""\
1161
[/dir]
1162
other_url = /other-dir
1163
other_url:policy = appendpath
1164
[/dir/subdir]
1165
other_url = /other-subdir
1166
""")
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1167
        self.assertOptions(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1168
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1169
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1170
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1171
            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.
1172
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1173
    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
1174
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1175
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1176
                         self.my_config.username())
1177
1178
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1179
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1180
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1181
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1182
                         self.my_config.username())
1183
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1184
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1185
        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
1186
        self.assertEqual('Robert Collins <robertc@example.org>',
1187
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1188
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1189
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1190
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1191
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1192
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1193
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1194
        self.assertEqual(config.SIGN_NEVER,
1195
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1196
1197
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1198
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1199
        self.assertEqual(config.CHECK_NEVER,
1200
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1201
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1202
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1203
        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
1204
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1205
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1206
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1207
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1208
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1209
        self.assertEqual(config.CHECK_ALWAYS,
1210
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1211
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1212
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1213
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1214
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1215
1216
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1217
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1218
        self.assertEqual("false", self.my_config.gpg_signing_command())
1219
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1220
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1221
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1222
        self.assertEqual('something',
1223
                         self.my_config.get_user_option('user_global_option'))
1224
1225
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1226
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1227
        self.assertEqual('local',
1228
                         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
1229
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
1230
    def test_get_user_option_appendpath(self):
1231
        # returned as is for the base path:
1232
        self.get_branch_config('http://www.example.com')
1233
        self.assertEqual('append',
1234
                         self.my_config.get_user_option('appendpath_option'))
1235
        # Extra path components get appended:
1236
        self.get_branch_config('http://www.example.com/a/b/c')
1237
        self.assertEqual('append/a/b/c',
1238
                         self.my_config.get_user_option('appendpath_option'))
1239
        # Overriden for http://www.example.com/dir, where it is a
1240
        # normal option:
1241
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1242
        self.assertEqual('normal',
1243
                         self.my_config.get_user_option('appendpath_option'))
1244
1245
    def test_get_user_option_norecurse(self):
1246
        self.get_branch_config('http://www.example.com')
1247
        self.assertEqual('norecurse',
1248
                         self.my_config.get_user_option('norecurse_option'))
1249
        self.get_branch_config('http://www.example.com/dir')
1250
        self.assertEqual(None,
1251
                         self.my_config.get_user_option('norecurse_option'))
1252
        # http://www.example.com/norecurse is a recurse=False section
1253
        # that redefines normal_option.  Subdirectories do not pick up
1254
        # this redefinition.
1255
        self.get_branch_config('http://www.example.com/norecurse')
1256
        self.assertEqual('norecurse',
1257
                         self.my_config.get_user_option('normal_option'))
1258
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1259
        self.assertEqual('normal',
1260
                         self.my_config.get_user_option('normal_option'))
1261
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1262
    def test_set_user_option_norecurse(self):
1263
        self.get_branch_config('http://www.example.com')
1264
        self.my_config.set_user_option('foo', 'bar',
1265
                                       store=config.STORE_LOCATION_NORECURSE)
1266
        self.assertEqual(
1267
            self.my_location_config._get_option_policy(
1268
            'http://www.example.com', 'foo'),
1269
            config.POLICY_NORECURSE)
1270
1271
    def test_set_user_option_appendpath(self):
1272
        self.get_branch_config('http://www.example.com')
1273
        self.my_config.set_user_option('foo', 'bar',
1274
                                       store=config.STORE_LOCATION_APPENDPATH)
1275
        self.assertEqual(
1276
            self.my_location_config._get_option_policy(
1277
            'http://www.example.com', 'foo'),
1278
            config.POLICY_APPENDPATH)
1279
1280
    def test_set_user_option_change_policy(self):
1281
        self.get_branch_config('http://www.example.com')
1282
        self.my_config.set_user_option('norecurse_option', 'normal',
1283
                                       store=config.STORE_LOCATION)
1284
        self.assertEqual(
1285
            self.my_location_config._get_option_policy(
1286
            'http://www.example.com', 'norecurse_option'),
1287
            config.POLICY_NONE)
1288
1289
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1290
        # The following section has recurse=False set.  The test is to
1291
        # make sure that a normal option can be added to the section,
1292
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1293
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1294
        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
1295
                             'The section "http://www.example.com/norecurse" '
1296
                             'has been converted to use policies.'],
1297
                            self.my_config.set_user_option,
1298
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1299
        self.assertEqual(
1300
            self.my_location_config._get_option_policy(
1301
            'http://www.example.com/norecurse', 'foo'),
1302
            config.POLICY_NONE)
1303
        # The previously existing option is still norecurse:
1304
        self.assertEqual(
1305
            self.my_location_config._get_option_policy(
1306
            'http://www.example.com/norecurse', 'normal_option'),
1307
            config.POLICY_NORECURSE)
1308
1472 by Robert Collins
post commit hook, first pass implementation
1309
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1310
        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
1311
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1312
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1313
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1314
    def get_branch_config(self, location, global_config=None,
1315
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1316
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1317
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1318
            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.
1319
        if location_config is None:
1320
            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.
1321
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1322
        my_global_config = config.GlobalConfig.from_string(global_config,
1323
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1324
        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.
1325
            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.
1326
        my_config = config.BranchConfig(my_branch)
1327
        self.my_config = my_config
1328
        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.
1329
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1330
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1331
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1332
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1333
        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
1334
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1335
        self.callDeprecated(['The recurse option is deprecated as of '
1336
                             '0.14.  The section "/a/c" has been '
1337
                             'converted to use policies.'],
1338
                            self.my_config.set_user_option,
1339
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1340
        self.assertEqual([('reload',),
1341
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1342
                          ('__contains__', '/a/c/'),
1343
                          ('__setitem__', '/a/c', {}),
1344
                          ('__getitem__', '/a/c'),
1345
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1346
                          ('__getitem__', '/a/c'),
1347
                          ('as_bool', 'recurse'),
1348
                          ('__getitem__', '/a/c'),
1349
                          ('__delitem__', 'recurse'),
1350
                          ('__getitem__', '/a/c'),
1351
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1352
                          ('__getitem__', '/a/c'),
1353
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1354
                          ('write',)],
1355
                         record._calls[1:])
1356
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1357
    def test_set_user_setting_sets_and_saves2(self):
1358
        self.get_branch_config('/a/c')
1359
        self.assertIs(self.my_config.get_user_option('foo'), None)
1360
        self.my_config.set_user_option('foo', 'bar')
1361
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1362
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1363
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1364
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1365
        self.my_config.set_user_option('foo', 'baz',
1366
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1367
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1368
        self.my_config.set_user_option('foo', 'qux')
1369
        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.
1370
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1371
    def test_get_bzr_remote_path(self):
1372
        my_config = config.LocationConfig('/a/c')
1373
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1374
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1375
        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.
1376
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1377
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1378
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1379
1770.2.8 by Aaron Bentley
Add precedence test
1380
precedence_global = 'option = global'
1381
precedence_branch = 'option = branch'
1382
precedence_location = """
1383
[http://]
1384
recurse = true
1385
option = recurse
1386
[http://example.com/specific]
1387
option = exact
1388
"""
1389
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1390
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1391
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1392
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1393
                          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.
1394
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1395
        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
1396
            my_global_config = config.GlobalConfig.from_string(global_config,
1397
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1398
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1399
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1400
                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.
1401
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1402
        if branch_data_config is not None:
1403
            my_config.branch.control_files.files['branch.conf'] = \
1404
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1405
        return my_config
1406
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1407
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1408
        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
1409
        my_config = config.BranchConfig(branch)
1410
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1411
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1412
        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.
1413
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1414
                                  "Robert Collins <robertc@example.org>")
1415
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1416
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1417
        self.assertEqual("Robert Collins <robertc@example.org>",
1418
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1419
1420
    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.
1421
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1422
        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
1423
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1424
        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
1425
        self.assertEqual("John", my_config._get_user_id())
1426
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1427
    def test_BZR_EMAIL_OVERRIDES(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1428
        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
1429
        branch = FakeBranch()
1430
        my_config = config.BranchConfig(branch)
1431
        self.assertEqual("Robert Collins <robertc@example.org>",
1432
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1433
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1434
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1435
        my_config = self.get_branch_config(
1436
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1437
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1438
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1439
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1440
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1441
    def test_signatures_forced_branch(self):
1442
        my_config = self.get_branch_config(
1443
            global_config=sample_ignore_signatures,
1444
            branch_data_config=sample_always_signatures)
1445
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1446
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1447
        self.assertTrue(my_config.signature_needed())
1448
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1449
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1450
        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.
1451
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1452
            # branch data cannot set gpg_signing_command
1453
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1454
        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.
1455
1456
    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.
1457
        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.
1458
        self.assertEqual('something',
1459
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1460
1461
    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.
1462
        my_config = self.get_branch_config(global_config=sample_config_text,
1463
                                      location='/a/c',
1464
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1465
        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
1466
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1467
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1468
        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.
1469
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1470
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1471
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1472
        my_config.set_user_option('post_commit', 'rmtree_root',
1473
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1474
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1475
1770.2.8 by Aaron Bentley
Add precedence test
1476
    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.
1477
        # FIXME: eager test, luckily no persitent config file makes it fail
1478
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1479
        my_config = self.get_branch_config(global_config=precedence_global)
1480
        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.
1481
        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.
1482
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1483
        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.
1484
        my_config = self.get_branch_config(
1485
            global_config=precedence_global,
1486
            branch_data_config=precedence_branch,
1487
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1488
        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.
1489
        my_config = self.get_branch_config(
1490
            global_config=precedence_global,
1491
            branch_data_config=precedence_branch,
1492
            location_config=precedence_location,
1493
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1494
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1495
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1496
    def test_get_mail_client(self):
1497
        config = self.get_branch_config()
1498
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1499
        self.assertIsInstance(client, mail_client.DefaultMail)
1500
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1501
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1502
        config.set_user_option('mail_client', 'evolution')
1503
        client = config.get_mail_client()
1504
        self.assertIsInstance(client, mail_client.Evolution)
1505
2681.5.1 by ghigo
Add KMail support to bzr send
1506
        config.set_user_option('mail_client', 'kmail')
1507
        client = config.get_mail_client()
1508
        self.assertIsInstance(client, mail_client.KMail)
1509
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1510
        config.set_user_option('mail_client', 'mutt')
1511
        client = config.get_mail_client()
1512
        self.assertIsInstance(client, mail_client.Mutt)
1513
1514
        config.set_user_option('mail_client', 'thunderbird')
1515
        client = config.get_mail_client()
1516
        self.assertIsInstance(client, mail_client.Thunderbird)
1517
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1518
        # Generic options
1519
        config.set_user_option('mail_client', 'default')
1520
        client = config.get_mail_client()
1521
        self.assertIsInstance(client, mail_client.DefaultMail)
1522
1523
        config.set_user_option('mail_client', 'editor')
1524
        client = config.get_mail_client()
1525
        self.assertIsInstance(client, mail_client.Editor)
1526
1527
        config.set_user_option('mail_client', 'mapi')
1528
        client = config.get_mail_client()
1529
        self.assertIsInstance(client, mail_client.MAPIClient)
1530
2681.1.23 by Aaron Bentley
Add support for xdg-email
1531
        config.set_user_option('mail_client', 'xdg-email')
1532
        client = config.get_mail_client()
1533
        self.assertIsInstance(client, mail_client.XDGEmail)
1534
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1535
        config.set_user_option('mail_client', 'firebird')
1536
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1537
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1538
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1539
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1540
1541
    def test_extract_email_address(self):
1542
        self.assertEqual('jane@test.com',
1543
                         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
1544
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1545
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1546
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1547
    def test_parse_username(self):
1548
        self.assertEqual(('', 'jdoe@example.com'),
1549
                         config.parse_username('jdoe@example.com'))
1550
        self.assertEqual(('', 'jdoe@example.com'),
1551
                         config.parse_username('<jdoe@example.com>'))
1552
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1553
                         config.parse_username('John Doe <jdoe@example.com>'))
1554
        self.assertEqual(('John Doe', ''),
1555
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1556
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1557
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1558
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1559
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1560
1561
    def test_get_value(self):
1562
        """Test that retreiving a value from a section is possible"""
1563
        branch = self.make_branch('.')
1564
        tree_config = config.TreeConfig(branch)
1565
        tree_config.set_option('value', 'key', 'SECTION')
1566
        tree_config.set_option('value2', 'key2')
1567
        tree_config.set_option('value3-top', 'key3')
1568
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1569
        value = tree_config.get_option('key', 'SECTION')
1570
        self.assertEqual(value, 'value')
1571
        value = tree_config.get_option('key2')
1572
        self.assertEqual(value, 'value2')
1573
        self.assertEqual(tree_config.get_option('non-existant'), None)
1574
        value = tree_config.get_option('non-existant', 'SECTION')
1575
        self.assertEqual(value, None)
1576
        value = tree_config.get_option('non-existant', default='default')
1577
        self.assertEqual(value, 'default')
1578
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1579
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1580
        self.assertEqual(value, 'default')
1581
        value = tree_config.get_option('key3')
1582
        self.assertEqual(value, 'value3-top')
1583
        value = tree_config.get_option('key3', 'SECTION')
1584
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1585
1586
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1587
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1588
1589
    def test_get_value(self):
1590
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1591
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1592
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1593
        bzrdir_config.set_option('value', 'key', 'SECTION')
1594
        bzrdir_config.set_option('value2', 'key2')
1595
        bzrdir_config.set_option('value3-top', 'key3')
1596
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1597
        value = bzrdir_config.get_option('key', 'SECTION')
1598
        self.assertEqual(value, 'value')
1599
        value = bzrdir_config.get_option('key2')
1600
        self.assertEqual(value, 'value2')
1601
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1602
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1603
        self.assertEqual(value, None)
1604
        value = bzrdir_config.get_option('non-existant', default='default')
1605
        self.assertEqual(value, 'default')
1606
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1607
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1608
                                         default='default')
1609
        self.assertEqual(value, 'default')
1610
        value = bzrdir_config.get_option('key3')
1611
        self.assertEqual(value, 'value3-top')
1612
        value = bzrdir_config.get_option('key3', 'SECTION')
1613
        self.assertEqual(value, 'value3-section')
1614
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1615
    def test_set_unset_default_stack_on(self):
1616
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1617
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1618
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1619
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1620
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1621
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1622
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1623
        bzrdir_config.set_default_stack_on(None)
1624
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1625
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1626
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1627
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1628
1629
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1630
        super(TestConfigGetOptions, self).setUp()
1631
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1632
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1633
    # One variable in none of the above
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1634
    def test_no_variable(self):
1635
        # 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.
1636
        self.assertOptions([], self.branch_config)
1637
1638
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1639
        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.
1640
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1641
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1642
1643
    def test_option_in_locations(self):
1644
        self.locations_config.set_user_option('file', 'locations')
1645
        self.assertOptions(
1646
            [('file', 'locations', self.tree.basedir, 'locations')],
1647
            self.locations_config)
1648
1649
    def test_option_in_branch(self):
1650
        self.branch_config.set_user_option('file', 'branch')
1651
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
1652
                           self.branch_config)
1653
1654
    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.
1655
        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.
1656
        self.branch_config.set_user_option('file', 'branch')
1657
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
1658
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1659
                           self.branch_config)
1660
1661
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1662
        # Hmm, locations override branch :-/
1663
        self.locations_config.set_user_option('file', 'locations')
1664
        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.
1665
        self.assertOptions(
1666
            [('file', 'locations', self.tree.basedir, 'locations'),
1667
             ('file', 'branch', 'DEFAULT', 'branch'),],
1668
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1669
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1670
    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.
1671
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1672
        self.locations_config.set_user_option('file', 'locations')
1673
        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.
1674
        self.assertOptions(
1675
            [('file', 'locations', self.tree.basedir, 'locations'),
1676
             ('file', 'branch', 'DEFAULT', 'branch'),
1677
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1678
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1679
1680
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1681
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1682
1683
    def setUp(self):
1684
        super(TestConfigRemoveOption, self).setUp()
1685
        create_configs_with_file_option(self)
1686
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1687
    def test_remove_in_locations(self):
1688
        self.locations_config.remove_user_option('file', self.tree.basedir)
1689
        self.assertOptions(
1690
            [('file', 'branch', 'DEFAULT', 'branch'),
1691
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1692
            self.branch_config)
1693
1694
    def test_remove_in_branch(self):
1695
        self.branch_config.remove_user_option('file')
1696
        self.assertOptions(
1697
            [('file', 'locations', self.tree.basedir, 'locations'),
1698
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1699
            self.branch_config)
1700
1701
    def test_remove_in_bazaar(self):
1702
        self.bazaar_config.remove_user_option('file')
1703
        self.assertOptions(
1704
            [('file', 'locations', self.tree.basedir, 'locations'),
1705
             ('file', 'branch', 'DEFAULT', 'branch'),],
1706
            self.branch_config)
1707
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
1708
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1709
class TestConfigGetSections(tests.TestCaseWithTransport):
1710
1711
    def setUp(self):
1712
        super(TestConfigGetSections, self).setUp()
1713
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1714
1715
    def assertSectionNames(self, expected, conf, name=None):
1716
        """Check which sections are returned for a given config.
1717
1718
        If fallback configurations exist their sections can be included.
1719
1720
        :param expected: A list of section names.
1721
1722
        :param conf: The configuration that will be queried.
1723
1724
        :param name: An optional section name that will be passed to
1725
            get_sections().
1726
        """
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.
1727
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1728
        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.
1729
        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.
1730
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1731
    def test_bazaar_default_section(self):
1732
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1733
1734
    def test_locations_default_section(self):
1735
        # No sections are defined in an empty file
1736
        self.assertSectionNames([], self.locations_config)
1737
1738
    def test_locations_named_section(self):
1739
        self.locations_config.set_user_option('file', 'locations')
1740
        self.assertSectionNames([self.tree.basedir], self.locations_config)
1741
1742
    def test_locations_matching_sections(self):
1743
        loc_config = self.locations_config
1744
        loc_config.set_user_option('file', 'locations')
1745
        # We need to cheat a bit here to create an option in sections above and
1746
        # below the 'location' one.
1747
        parser = loc_config._get_parser()
1748
        # locations.cong deals with '/' ignoring native os.sep
1749
        location_names = self.tree.basedir.split('/')
1750
        parent = '/'.join(location_names[:-1])
1751
        child = '/'.join(location_names + ['child'])
1752
        parser[parent] = {}
1753
        parser[parent]['file'] = 'parent'
1754
        parser[child] = {}
1755
        parser[child]['file'] = 'child'
1756
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
1757
1758
    def test_branch_data_default_section(self):
1759
        self.assertSectionNames([None],
1760
                                self.branch_config._get_branch_data_config())
1761
1762
    def test_branch_default_sections(self):
1763
        # No sections are defined in an empty locations file
1764
        self.assertSectionNames([None, 'DEFAULT'],
1765
                                self.branch_config)
1766
        # Unless we define an option
1767
        self.branch_config._get_location_config().set_user_option(
1768
            'file', 'locations')
1769
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
1770
                                self.branch_config)
1771
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1772
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1773
        # We need to cheat as the API doesn't give direct access to sections
1774
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1775
        self.bazaar_config.set_alias('bazaar', 'bzr')
1776
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1777
1778
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1779
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1780
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1781
1782
    def _got_user_passwd(self, expected_user, expected_password,
1783
                         config, *args, **kwargs):
1784
        credentials = config.get_credentials(*args, **kwargs)
1785
        if credentials is None:
1786
            user = None
1787
            password = None
1788
        else:
1789
            user = credentials['user']
1790
            password = credentials['password']
1791
        self.assertEquals(expected_user, user)
1792
        self.assertEquals(expected_password, password)
1793
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1794
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1795
        conf = config.AuthenticationConfig(_file=StringIO())
1796
        self.assertEquals({}, conf._get_config())
1797
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1798
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1799
    def test_missing_auth_section_header(self):
1800
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1801
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1802
1803
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1804
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1805
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1806
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1807
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1808
        conf = config.AuthenticationConfig(_file=StringIO(
1809
                """[broken]
1810
scheme=ftp
1811
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1812
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1813
"""))
1814
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1815
1816
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
1817
        conf = config.AuthenticationConfig(_file=StringIO(
1818
                """[broken]
1819
scheme=ftp
1820
user=joe
1821
port=port # Error: Not an int
1822
"""))
1823
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1824
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1825
    def test_unknown_password_encoding(self):
1826
        conf = config.AuthenticationConfig(_file=StringIO(
1827
                """[broken]
1828
scheme=ftp
1829
user=joe
1830
password_encoding=unknown
1831
"""))
1832
        self.assertRaises(ValueError, conf.get_password,
1833
                          'ftp', 'foo.net', 'joe')
1834
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1835
    def test_credentials_for_scheme_host(self):
1836
        conf = config.AuthenticationConfig(_file=StringIO(
1837
                """# Identity on foo.net
1838
[ftp definition]
1839
scheme=ftp
1840
host=foo.net
1841
user=joe
1842
password=secret-pass
1843
"""))
1844
        # Basic matching
1845
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1846
        # different scheme
1847
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1848
        # different host
1849
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1850
1851
    def test_credentials_for_host_port(self):
1852
        conf = config.AuthenticationConfig(_file=StringIO(
1853
                """# Identity on foo.net
1854
[ftp definition]
1855
scheme=ftp
1856
port=10021
1857
host=foo.net
1858
user=joe
1859
password=secret-pass
1860
"""))
1861
        # No port
1862
        self._got_user_passwd('joe', 'secret-pass',
1863
                              conf, 'ftp', 'foo.net', port=10021)
1864
        # different port
1865
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1866
1867
    def test_for_matching_host(self):
1868
        conf = config.AuthenticationConfig(_file=StringIO(
1869
                """# Identity on foo.net
1870
[sourceforge]
1871
scheme=bzr
1872
host=bzr.sf.net
1873
user=joe
1874
password=joepass
1875
[sourceforge domain]
1876
scheme=bzr
1877
host=.bzr.sf.net
1878
user=georges
1879
password=bendover
1880
"""))
1881
        # matching domain
1882
        self._got_user_passwd('georges', 'bendover',
1883
                              conf, 'bzr', 'foo.bzr.sf.net')
1884
        # phishing attempt
1885
        self._got_user_passwd(None, None,
1886
                              conf, 'bzr', 'bbzr.sf.net')
1887
1888
    def test_for_matching_host_None(self):
1889
        conf = config.AuthenticationConfig(_file=StringIO(
1890
                """# Identity on foo.net
1891
[catchup bzr]
1892
scheme=bzr
1893
user=joe
1894
password=joepass
1895
[DEFAULT]
1896
user=georges
1897
password=bendover
1898
"""))
1899
        # match no host
1900
        self._got_user_passwd('joe', 'joepass',
1901
                              conf, 'bzr', 'quux.net')
1902
        # no host but different scheme
1903
        self._got_user_passwd('georges', 'bendover',
1904
                              conf, 'ftp', 'quux.net')
1905
1906
    def test_credentials_for_path(self):
1907
        conf = config.AuthenticationConfig(_file=StringIO(
1908
                """
1909
[http dir1]
1910
scheme=http
1911
host=bar.org
1912
path=/dir1
1913
user=jim
1914
password=jimpass
1915
[http dir2]
1916
scheme=http
1917
host=bar.org
1918
path=/dir2
1919
user=georges
1920
password=bendover
1921
"""))
1922
        # no path no dice
1923
        self._got_user_passwd(None, None,
1924
                              conf, 'http', host='bar.org', path='/dir3')
1925
        # matching path
1926
        self._got_user_passwd('georges', 'bendover',
1927
                              conf, 'http', host='bar.org', path='/dir2')
1928
        # matching subdir
1929
        self._got_user_passwd('jim', 'jimpass',
1930
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1931
1932
    def test_credentials_for_user(self):
1933
        conf = config.AuthenticationConfig(_file=StringIO(
1934
                """
1935
[with user]
1936
scheme=http
1937
host=bar.org
1938
user=jim
1939
password=jimpass
1940
"""))
1941
        # Get user
1942
        self._got_user_passwd('jim', 'jimpass',
1943
                              conf, 'http', 'bar.org')
1944
        # Get same user
1945
        self._got_user_passwd('jim', 'jimpass',
1946
                              conf, 'http', 'bar.org', user='jim')
1947
        # Don't get a different user if one is specified
1948
        self._got_user_passwd(None, None,
1949
                              conf, 'http', 'bar.org', user='georges')
1950
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
1951
    def test_credentials_for_user_without_password(self):
1952
        conf = config.AuthenticationConfig(_file=StringIO(
1953
                """
1954
[without password]
1955
scheme=http
1956
host=bar.org
1957
user=jim
1958
"""))
1959
        # Get user but no password
1960
        self._got_user_passwd('jim', None,
1961
                              conf, 'http', 'bar.org')
1962
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1963
    def test_verify_certificates(self):
1964
        conf = config.AuthenticationConfig(_file=StringIO(
1965
                """
1966
[self-signed]
1967
scheme=https
1968
host=bar.org
1969
user=jim
1970
password=jimpass
1971
verify_certificates=False
1972
[normal]
1973
scheme=https
1974
host=foo.net
1975
user=georges
1976
password=bendover
1977
"""))
1978
        credentials = conf.get_credentials('https', 'bar.org')
1979
        self.assertEquals(False, credentials.get('verify_certificates'))
1980
        credentials = conf.get_credentials('https', 'foo.net')
1981
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1982
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1983
1984
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1985
3777.1.8 by Aaron Bentley
Commit work-in-progress
1986
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1987
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1988
        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
1989
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
1990
        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
1991
                                           port=99, path='/foo',
1992
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1993
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1994
                       'verify_certificates': False, 'scheme': 'scheme', 
1995
                       'host': 'host', 'port': 99, 'path': '/foo', 
1996
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1997
        self.assertEqual(CREDENTIALS, credentials)
1998
        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
1999
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2000
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
2001
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2002
    def test_reset_credentials_different_name(self):
2003
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2004
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
2005
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2006
        self.assertIs(None, conf._get_config().get('name'))
2007
        credentials = conf.get_credentials(host='host', scheme='scheme')
2008
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2009
                       'password', 'verify_certificates': True, 
2010
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
2011
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2012
        self.assertEqual(CREDENTIALS, credentials)
2013
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2014
2900.2.14 by Vincent Ladeuil
More tests.
2015
class TestAuthenticationConfig(tests.TestCase):
2016
    """Test AuthenticationConfig behaviour"""
2017
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2018
    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.
2019
                                       host=None, port=None, realm=None,
2020
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
2021
        if host is None:
2022
            host = 'bar.org'
2023
        user, password = 'jim', 'precious'
2024
        expected_prompt = expected_prompt_format % {
2025
            'scheme': scheme, 'host': host, 'port': port,
2026
            'user': user, 'realm': realm}
2027
2028
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2029
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
2030
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2031
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
2032
        # We use an empty conf so that the user is always prompted
2033
        conf = config.AuthenticationConfig()
2034
        self.assertEquals(password,
2035
                          conf.get_password(scheme, host, user, port=port,
2036
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2037
        self.assertEquals(expected_prompt, stderr.getvalue())
2038
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
2039
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2040
    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.
2041
                                       host=None, port=None, realm=None,
2042
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2043
        if host is None:
2044
            host = 'bar.org'
2045
        username = 'jim'
2046
        expected_prompt = expected_prompt_format % {
2047
            'scheme': scheme, 'host': host, 'port': port,
2048
            'realm': realm}
2049
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2050
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2051
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2052
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2053
        # We use an empty conf so that the user is always prompted
2054
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
2055
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
2056
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2057
        self.assertEquals(expected_prompt, stderr.getvalue())
2058
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
2059
2060
    def test_username_defaults_prompts(self):
2061
        # HTTP prompts can't be tested here, see test_http.py
2062
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
2063
        self._check_default_username_prompt(
2064
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
2065
        self._check_default_username_prompt(
2066
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
2067
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2068
    def test_username_default_no_prompt(self):
2069
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2070
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2071
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2072
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
2073
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
2074
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2075
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
2076
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2077
        self._check_default_password_prompt(
2078
            'FTP %(user)s@%(host)s password: ', 'ftp')
2079
        self._check_default_password_prompt(
2080
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
2081
        self._check_default_password_prompt(
2082
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
2083
        # SMTP port handling is a bit special (it's handled if embedded in the
2084
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
2085
        # FIXME: should we: forbid that, extend it to other schemes, leave
2086
        # things as they are that's fine thank you ?
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2087
        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
2088
                                            'smtp')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2089
        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
2090
                                            'smtp', host='bar.org:10025')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2091
        self._check_default_password_prompt(
2900.2.14 by Vincent Ladeuil
More tests.
2092
            'SMTP %(user)s@%(host)s:%(port)d password: ',
2093
            'smtp', port=10025)
2094
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2095
    def test_ssh_password_emits_warning(self):
2096
        conf = config.AuthenticationConfig(_file=StringIO(
2097
                """
2098
[ssh with password]
2099
scheme=ssh
2100
host=bar.org
2101
user=jim
2102
password=jimpass
2103
"""))
2104
        entered_password = 'typed-by-hand'
2105
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2106
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2107
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2108
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2109
2110
        # Since the password defined in the authentication config is ignored,
2111
        # the user is prompted
2112
        self.assertEquals(entered_password,
2113
                          conf.get_password('ssh', 'bar.org', user='jim'))
2114
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
2115
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2116
            'password ignored in section \[ssh with password\]')
2117
3420.1.3 by Vincent Ladeuil
John's review feedback.
2118
    def test_ssh_without_password_doesnt_emit_warning(self):
2119
        conf = config.AuthenticationConfig(_file=StringIO(
2120
                """
2121
[ssh with password]
2122
scheme=ssh
2123
host=bar.org
2124
user=jim
2125
"""))
2126
        entered_password = 'typed-by-hand'
2127
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2128
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
2129
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2130
                                            stdout=stdout,
2131
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
2132
2133
        # Since the password defined in the authentication config is ignored,
2134
        # the user is prompted
2135
        self.assertEquals(entered_password,
2136
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
2137
        # No warning shoud be emitted since there is no password. We are only
2138
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
2139
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
2140
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
2141
            'password ignored in section \[ssh with password\]')
2142
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2143
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2144
        self.overrideAttr(config, 'credential_store_registry',
2145
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2146
        store = StubCredentialStore()
2147
        store.add_credentials("http", "example.com", "joe", "secret")
2148
        config.credential_store_registry.register("stub", store, fallback=True)
2149
        conf = config.AuthenticationConfig(_file=StringIO())
2150
        creds = conf.get_credentials("http", "example.com")
2151
        self.assertEquals("joe", creds["user"])
2152
        self.assertEquals("secret", creds["password"])
2153
2900.2.14 by Vincent Ladeuil
More tests.
2154
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2155
class StubCredentialStore(config.CredentialStore):
2156
2157
    def __init__(self):
2158
        self._username = {}
2159
        self._password = {}
2160
2161
    def add_credentials(self, scheme, host, user, password=None):
2162
        self._username[(scheme, host)] = user
2163
        self._password[(scheme, host)] = password
2164
2165
    def get_credentials(self, scheme, host, port=None, user=None,
2166
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2167
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2168
        if not key in self._username:
2169
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2170
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2171
                "user": self._username[key], "password": self._password[key]}
2172
2173
2174
class CountingCredentialStore(config.CredentialStore):
2175
2176
    def __init__(self):
2177
        self._calls = 0
2178
2179
    def get_credentials(self, scheme, host, port=None, user=None,
2180
        path=None, realm=None):
2181
        self._calls += 1
2182
        return None
2183
2184
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2185
class TestCredentialStoreRegistry(tests.TestCase):
2186
2187
    def _get_cs_registry(self):
2188
        return config.credential_store_registry
2189
2190
    def test_default_credential_store(self):
2191
        r = self._get_cs_registry()
2192
        default = r.get_credential_store(None)
2193
        self.assertIsInstance(default, config.PlainTextCredentialStore)
2194
2195
    def test_unknown_credential_store(self):
2196
        r = self._get_cs_registry()
2197
        # It's hard to imagine someone creating a credential store named
2198
        # 'unknown' so we use that as an never registered key.
2199
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
2200
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2201
    def test_fallback_none_registered(self):
2202
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2203
        self.assertEquals(None,
2204
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2205
2206
    def test_register(self):
2207
        r = config.CredentialStoreRegistry()
2208
        r.register("stub", StubCredentialStore(), fallback=False)
2209
        r.register("another", StubCredentialStore(), fallback=True)
2210
        self.assertEquals(["another", "stub"], r.keys())
2211
2212
    def test_register_lazy(self):
2213
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2214
        r.register_lazy("stub", "bzrlib.tests.test_config",
2215
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2216
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2217
        self.assertIsInstance(r.get_credential_store("stub"),
2218
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2219
2220
    def test_is_fallback(self):
2221
        r = config.CredentialStoreRegistry()
2222
        r.register("stub1", None, fallback=False)
2223
        r.register("stub2", None, fallback=True)
2224
        self.assertEquals(False, r.is_fallback("stub1"))
2225
        self.assertEquals(True, r.is_fallback("stub2"))
2226
2227
    def test_no_fallback(self):
2228
        r = config.CredentialStoreRegistry()
2229
        store = CountingCredentialStore()
2230
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2231
        self.assertEquals(None,
2232
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2233
        self.assertEquals(0, store._calls)
2234
2235
    def test_fallback_credentials(self):
2236
        r = config.CredentialStoreRegistry()
2237
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2238
        store.add_credentials("http", "example.com",
2239
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2240
        r.register("stub", store, fallback=True)
2241
        creds = r.get_fallback_credentials("http", "example.com")
2242
        self.assertEquals("somebody", creds["user"])
2243
        self.assertEquals("geheim", creds["password"])
2244
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2245
    def test_fallback_first_wins(self):
2246
        r = config.CredentialStoreRegistry()
2247
        stub1 = StubCredentialStore()
2248
        stub1.add_credentials("http", "example.com",
2249
                              "somebody", "stub1")
2250
        r.register("stub1", stub1, fallback=True)
2251
        stub2 = StubCredentialStore()
2252
        stub2.add_credentials("http", "example.com",
2253
                              "somebody", "stub2")
2254
        r.register("stub2", stub1, fallback=True)
2255
        creds = r.get_fallback_credentials("http", "example.com")
2256
        self.assertEquals("somebody", creds["user"])
2257
        self.assertEquals("stub1", creds["password"])
2258
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2259
2260
class TestPlainTextCredentialStore(tests.TestCase):
2261
2262
    def test_decode_password(self):
2263
        r = config.credential_store_registry
2264
        plain_text = r.get_credential_store()
2265
        decoded = plain_text.decode_password(dict(password='secret'))
2266
        self.assertEquals('secret', decoded)
2267
2268
2900.2.14 by Vincent Ladeuil
More tests.
2269
# 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.
2270
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2271
# test_user_password_in_url
2272
# test_user_in_url_password_from_config
2273
# test_user_in_url_password_prompted
2274
# test_user_in_config
2275
# test_user_getpass.getuser
2276
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2277
class TestAuthenticationRing(tests.TestCaseWithTransport):
2278
    pass