/brz/remove-bazaar

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