/brz/remove-bazaar

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