~bzr-pqm/bzr/bzr.dev

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