/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: John Arbash Meinel
  • Date: 2006-04-25 15:05:42 UTC
  • mfrom: (1185.85.85 bzr-encoding)
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060425150542-c7b518dca9928691
[merge] the old bzr-encoding changes, reparenting them on bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2014, 2016 Canonical Ltd
 
1
# Copyright (C) 2005 by Canonical Ltd
 
2
#   Authors: Robert Collins <robert.collins@canonical.com>
2
3
#
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
12
13
#
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""Tests for finding and reading the bzr config file[s]."""
18
 
 
19
 
from textwrap import dedent
 
19
# import system imports here
 
20
from bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
 
21
from cStringIO import StringIO
20
22
import os
21
23
import sys
22
 
import threading
23
 
 
24
 
import configobj
25
 
from testtools import matchers
26
 
 
27
 
from .. import (
28
 
    branch,
29
 
    config,
30
 
    bedding,
31
 
    controldir,
32
 
    diff,
33
 
    errors,
34
 
    lock,
35
 
    osutils,
36
 
    mail_client,
37
 
    ui,
38
 
    urlutils,
39
 
    registry as _mod_registry,
40
 
    tests,
41
 
    trace,
42
 
    )
43
 
from ..bzr import (
44
 
    remote,
45
 
    )
46
 
from ..sixish import (
47
 
    BytesIO,
48
 
    text_type,
49
 
    )
50
 
from ..transport import remote as transport_remote
51
 
from . import (
52
 
    features,
53
 
    scenarios,
54
 
    test_server,
55
 
    )
56
 
 
57
 
 
58
 
def lockable_config_scenarios():
59
 
    return [
60
 
        ('global',
61
 
         {'config_class': config.GlobalConfig,
62
 
          'config_args': [],
63
 
          'config_section': 'DEFAULT'}),
64
 
        ('locations',
65
 
         {'config_class': config.LocationConfig,
66
 
          'config_args': ['.'],
67
 
          'config_section': '.'}), ]
68
 
 
69
 
 
70
 
load_tests = scenarios.load_tests_apply_scenarios
71
 
 
72
 
# Register helpers to build stores
73
 
config.test_store_builder_registry.register(
74
 
    'configobj', lambda test: config.TransportIniFileStore(
75
 
        test.get_transport(), 'configobj.conf'))
76
 
config.test_store_builder_registry.register(
77
 
    'breezy', lambda test: config.GlobalStore())
78
 
config.test_store_builder_registry.register(
79
 
    'location', lambda test: config.LocationStore())
80
 
 
81
 
 
82
 
def build_backing_branch(test, relpath,
83
 
                         transport_class=None, server_class=None):
84
 
    """Test helper to create a backing branch only once.
85
 
 
86
 
    Some tests needs multiple stores/stacks to check concurrent update
87
 
    behaviours. As such, they need to build different branch *objects* even if
88
 
    they share the branch on disk.
89
 
 
90
 
    :param relpath: The relative path to the branch. (Note that the helper
91
 
        should always specify the same relpath).
92
 
 
93
 
    :param transport_class: The Transport class the test needs to use.
94
 
 
95
 
    :param server_class: The server associated with the ``transport_class``
96
 
        above.
97
 
 
98
 
    Either both or neither of ``transport_class`` and ``server_class`` should
99
 
    be specified.
100
 
    """
101
 
    if transport_class is not None and server_class is not None:
102
 
        test.transport_class = transport_class
103
 
        test.transport_server = server_class
104
 
    elif not (transport_class is None and server_class is None):
105
 
        raise AssertionError('Specify both ``transport_class`` and '
106
 
                             '``server_class`` or neither of them')
107
 
    if getattr(test, 'backing_branch', None) is None:
108
 
        # First call, let's build the branch on disk
109
 
        test.backing_branch = test.make_branch(relpath)
110
 
 
111
 
 
112
 
def build_branch_store(test):
113
 
    build_backing_branch(test, 'branch')
114
 
    b = branch.Branch.open('branch')
115
 
    return config.BranchStore(b)
116
 
 
117
 
 
118
 
config.test_store_builder_registry.register('branch', build_branch_store)
119
 
 
120
 
 
121
 
def build_control_store(test):
122
 
    build_backing_branch(test, 'branch')
123
 
    b = controldir.ControlDir.open('branch')
124
 
    return config.ControlStore(b)
125
 
 
126
 
 
127
 
config.test_store_builder_registry.register('control', build_control_store)
128
 
 
129
 
 
130
 
def build_remote_branch_store(test):
131
 
    # There is only one permutation (but we won't be able to handle more with
132
 
    # this design anyway)
133
 
    (transport_class,
134
 
     server_class) = transport_remote.get_test_permutations()[0]
135
 
    build_backing_branch(test, 'branch', transport_class, server_class)
136
 
    b = branch.Branch.open(test.get_url('branch'))
137
 
    return config.BranchStore(b)
138
 
 
139
 
 
140
 
config.test_store_builder_registry.register('remote_branch',
141
 
                                            build_remote_branch_store)
142
 
 
143
 
 
144
 
config.test_stack_builder_registry.register(
145
 
    'breezy', lambda test: config.GlobalStack())
146
 
config.test_stack_builder_registry.register(
147
 
    'location', lambda test: config.LocationStack('.'))
148
 
 
149
 
 
150
 
def build_branch_stack(test):
151
 
    build_backing_branch(test, 'branch')
152
 
    b = branch.Branch.open('branch')
153
 
    return config.BranchStack(b)
154
 
 
155
 
 
156
 
config.test_stack_builder_registry.register('branch', build_branch_stack)
157
 
 
158
 
 
159
 
def build_branch_only_stack(test):
160
 
    # There is only one permutation (but we won't be able to handle more with
161
 
    # this design anyway)
162
 
    (transport_class,
163
 
     server_class) = transport_remote.get_test_permutations()[0]
164
 
    build_backing_branch(test, 'branch', transport_class, server_class)
165
 
    b = branch.Branch.open(test.get_url('branch'))
166
 
    return config.BranchOnlyStack(b)
167
 
 
168
 
 
169
 
config.test_stack_builder_registry.register('branch_only',
170
 
                                            build_branch_only_stack)
171
 
 
172
 
 
173
 
def build_remote_control_stack(test):
174
 
    # There is only one permutation (but we won't be able to handle more with
175
 
    # this design anyway)
176
 
    (transport_class,
177
 
     server_class) = transport_remote.get_test_permutations()[0]
178
 
    # We need only a bzrdir for this, not a full branch, but it's not worth
179
 
    # creating a dedicated helper to create only the bzrdir
180
 
    build_backing_branch(test, 'branch', transport_class, server_class)
181
 
    b = branch.Branch.open(test.get_url('branch'))
182
 
    return config.RemoteControlStack(b.controldir)
183
 
 
184
 
 
185
 
config.test_stack_builder_registry.register('remote_control',
186
 
                                            build_remote_control_stack)
187
 
 
188
 
 
189
 
sample_long_alias = "log -r-15..-1 --line"
190
 
sample_config_text = u"""
191
 
[DEFAULT]
192
 
email=Erik B\u00e5gfors <erik@bagfors.nu>
193
 
editor=vim
194
 
change_editor=vimdiff -of {new_path} {old_path}
195
 
gpg_signing_key=DD4D5088
196
 
log_format=short
197
 
validate_signatures_in_log=true
198
 
acceptable_keys=amy
199
 
user_global_option=something
200
 
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
201
 
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
202
 
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
203
 
bzr.default_mergetool=sometool
204
 
[ALIASES]
205
 
h=help
206
 
ll=""".encode('utf-8') + sample_long_alias.encode('utf-8') + b"\n"
207
 
 
208
 
 
209
 
sample_always_signatures = b"""
210
 
[DEFAULT]
211
 
check_signatures=ignore
212
 
create_signatures=always
213
 
"""
214
 
 
215
 
sample_ignore_signatures = b"""
216
 
[DEFAULT]
217
 
check_signatures=require
218
 
create_signatures=never
219
 
"""
220
 
 
221
 
sample_maybe_signatures = b"""
222
 
[DEFAULT]
223
 
check_signatures=ignore
224
 
create_signatures=when-required
225
 
"""
226
 
 
227
 
sample_branches_text = b"""
228
 
[http://www.example.com]
229
 
# Top level policy
230
 
email=Robert Collins <robertc@example.org>
231
 
normal_option = normal
232
 
appendpath_option = append
233
 
appendpath_option:policy = appendpath
234
 
norecurse_option = norecurse
235
 
norecurse_option:policy = norecurse
236
 
[http://www.example.com/ignoreparent]
237
 
# different project: ignore parent dir config
238
 
ignore_parents=true
239
 
[http://www.example.com/norecurse]
240
 
# configuration items that only apply to this dir
241
 
recurse=false
242
 
normal_option = norecurse
243
 
[http://www.example.com/dir]
244
 
appendpath_option = normal
245
 
[/b/]
246
 
check_signatures=require
247
 
# test trailing / matching with no children
248
 
[/a/]
249
 
check_signatures=check-available
250
 
gpg_signing_key=default
251
 
user_local_option=local
252
 
# test trailing / matching
253
 
[/a/*]
254
 
#subdirs will match but not the parent
255
 
[/a/c]
256
 
check_signatures=ignore
257
 
post_commit=breezy.tests.test_config.post_commit
258
 
#testing explicit beats globs
259
 
"""
260
 
 
261
 
 
262
 
def create_configs(test):
263
 
    """Create configuration files for a given test.
264
 
 
265
 
    This requires creating a tree (and populate the ``test.tree`` attribute)
266
 
    and its associated branch and will populate the following attributes:
267
 
 
268
 
    - branch_config: A BranchConfig for the associated branch.
269
 
 
270
 
    - locations_config : A LocationConfig for the associated branch
271
 
 
272
 
    - breezy_config: A GlobalConfig.
273
 
 
274
 
    The tree and branch are created in a 'tree' subdirectory so the tests can
275
 
    still use the test directory to stay outside of the branch.
276
 
    """
277
 
    tree = test.make_branch_and_tree('tree')
278
 
    test.tree = tree
279
 
    test.branch_config = config.BranchConfig(tree.branch)
280
 
    test.locations_config = config.LocationConfig(tree.basedir)
281
 
    test.breezy_config = config.GlobalConfig()
282
 
 
283
 
 
284
 
def create_configs_with_file_option(test):
285
 
    """Create configuration files with a ``file`` option set in each.
286
 
 
287
 
    This builds on ``create_configs`` and add one ``file`` option in each
288
 
    configuration with a value which allows identifying the configuration file.
289
 
    """
290
 
    create_configs(test)
291
 
    test.breezy_config.set_user_option('file', 'breezy')
292
 
    test.locations_config.set_user_option('file', 'locations')
293
 
    test.branch_config.set_user_option('file', 'branch')
294
 
 
295
 
 
296
 
class TestOptionsMixin:
297
 
 
298
 
    def assertOptions(self, expected, conf):
299
 
        # We don't care about the parser (as it will make tests hard to write
300
 
        # and error-prone anyway)
301
 
        self.assertThat([opt[:4] for opt in conf._get_options()],
302
 
                        matchers.Equals(expected))
 
24
 
 
25
#import bzrlib specific imports here
 
26
import bzrlib.config as config
 
27
import bzrlib.errors as errors
 
28
from bzrlib.tests import TestCase, TestCaseInTempDir
 
29
 
 
30
 
 
31
sample_long_alias="log -r-15..-1 --line"
 
32
sample_config_text = ("[DEFAULT]\n"
 
33
                      u"email=Erik B\u00e5gfors <erik@bagfors.nu>\n"
 
34
                      "editor=vim\n"
 
35
                      "gpg_signing_command=gnome-gpg\n"
 
36
                      "log_format=short\n"
 
37
                      "user_global_option=something\n"
 
38
                      "[ALIASES]\n"
 
39
                      "h=help\n"
 
40
                      "ll=" + sample_long_alias + "\n")
 
41
 
 
42
 
 
43
sample_always_signatures = ("[DEFAULT]\n"
 
44
                            "check_signatures=require\n")
 
45
 
 
46
 
 
47
sample_ignore_signatures = ("[DEFAULT]\n"
 
48
                            "check_signatures=ignore\n")
 
49
 
 
50
 
 
51
sample_maybe_signatures = ("[DEFAULT]\n"
 
52
                            "check_signatures=check-available\n")
 
53
 
 
54
 
 
55
sample_branches_text = ("[http://www.example.com]\n"
 
56
                        "# Top level policy\n"
 
57
                        "email=Robert Collins <robertc@example.org>\n"
 
58
                        "[http://www.example.com/useglobal]\n"
 
59
                        "# different project, forces global lookup\n"
 
60
                        "recurse=false\n"
 
61
                        "[/b/]\n"
 
62
                        "check_signatures=require\n"
 
63
                        "# test trailing / matching with no children\n"
 
64
                        "[/a/]\n"
 
65
                        "check_signatures=check-available\n"
 
66
                        "gpg_signing_command=false\n"
 
67
                        "user_local_option=local\n"
 
68
                        "# test trailing / matching\n"
 
69
                        "[/a/*]\n"
 
70
                        "#subdirs will match but not the parent\n"
 
71
                        "recurse=False\n"
 
72
                        "[/a/c]\n"
 
73
                        "check_signatures=ignore\n"
 
74
                        "post_commit=bzrlib.tests.test_config.post_commit\n"
 
75
                        "#testing explicit beats globs\n")
 
76
 
303
77
 
304
78
 
305
79
class InstrumentedConfigObj(object):
319
93
    def __setitem__(self, key, value):
320
94
        self._calls.append(('__setitem__', key, value))
321
95
 
322
 
    def __delitem__(self, key):
323
 
        self._calls.append(('__delitem__', key))
324
 
 
325
 
    def keys(self):
326
 
        self._calls.append(('keys',))
327
 
        return []
328
 
 
329
 
    def reload(self):
330
 
        self._calls.append(('reload',))
331
 
 
332
96
    def write(self, arg):
333
97
        self._calls.append(('write',))
334
98
 
335
 
    def as_bool(self, value):
336
 
        self._calls.append(('as_bool', value))
337
 
        return False
338
 
 
339
 
    def get_value(self, section, name):
340
 
        self._calls.append(('get_value', section, name))
341
 
        return None
342
 
 
343
99
 
344
100
class FakeBranch(object):
345
101
 
346
 
    def __init__(self, base=None):
347
 
        if base is None:
348
 
            self.base = "http://example.com/branches/demo"
349
 
        else:
350
 
            self.base = base
351
 
        self._transport = self.control_files = \
352
 
            FakeControlFilesAndTransport()
353
 
 
354
 
    def _get_config(self):
355
 
        return config.TransportConfig(self._transport, 'branch.conf')
356
 
 
357
 
    def lock_write(self):
358
 
        return lock.LogicalLockResult(self.unlock)
359
 
 
360
 
    def unlock(self):
361
 
        pass
362
 
 
363
 
 
364
 
class FakeControlFilesAndTransport(object):
365
 
 
366
 
    def __init__(self):
367
 
        self.files = {}
368
 
        self._transport = self
369
 
 
370
 
    def get(self, filename):
371
 
        # from Transport
372
 
        try:
373
 
            return BytesIO(self.files[filename])
374
 
        except KeyError:
375
 
            raise errors.NoSuchFile(filename)
376
 
 
377
 
    def get_bytes(self, filename):
378
 
        # from Transport
379
 
        try:
380
 
            return self.files[filename]
381
 
        except KeyError:
382
 
            raise errors.NoSuchFile(filename)
383
 
 
384
 
    def put(self, filename, fileobj):
385
 
        self.files[filename] = fileobj.read()
386
 
 
387
 
    def put_file(self, filename, fileobj):
388
 
        return self.put(filename, fileobj)
 
102
    def __init__(self):
 
103
        self.base = "http://example.com/branches/demo"
 
104
        self.control_files = FakeControlFiles()
 
105
 
 
106
 
 
107
class FakeControlFiles(object):
 
108
 
 
109
    def __init__(self):
 
110
        self.email = 'Robert Collins <robertc@example.net>\n'
 
111
 
 
112
    def get_utf8(self, filename):
 
113
        if filename != 'email':
 
114
            raise NotImplementedError
 
115
        if self.email is not None:
 
116
            return StringIO(self.email)
 
117
        raise errors.NoSuchFile(filename)
389
118
 
390
119
 
391
120
class InstrumentedConfig(config.Config):
392
121
    """An instrumented config that supplies stubs for template methods."""
393
 
 
 
122
    
394
123
    def __init__(self):
395
124
        super(InstrumentedConfig, self).__init__()
396
125
        self._calls = []
397
126
        self._signatures = config.CHECK_NEVER
398
 
        self._change_editor = 'vimdiff -fo {new_path} {old_path}'
399
127
 
400
128
    def _get_user_id(self):
401
129
        self._calls.append('_get_user_id')
405
133
        self._calls.append('_get_signature_checking')
406
134
        return self._signatures
407
135
 
408
 
    def _get_change_editor(self):
409
 
        self._calls.append('_get_change_editor')
410
 
        return self._change_editor
411
 
 
412
 
 
413
 
bool_config = b"""[DEFAULT]
 
136
 
 
137
bool_config = """[DEFAULT]
414
138
active = true
415
139
inactive = false
416
140
[UPPERCASE]
417
141
active = True
418
142
nonactive = False
419
143
"""
420
 
 
421
 
 
422
 
class TestConfigObj(tests.TestCase):
423
 
 
 
144
class TestConfigObj(TestCase):
424
145
    def test_get_bool(self):
425
 
        co = config.ConfigObj(BytesIO(bool_config))
 
146
        from bzrlib.config import ConfigObj
 
147
        co = ConfigObj(StringIO(bool_config))
426
148
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
427
149
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
428
150
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
429
151
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
430
152
 
431
 
    def test_hash_sign_in_value(self):
432
 
        """
433
 
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
434
 
        treated as comments when read in again. (#86838)
435
 
        """
436
 
        co = config.ConfigObj()
437
 
        co['test'] = 'foo#bar'
438
 
        outfile = BytesIO()
439
 
        co.write(outfile=outfile)
440
 
        lines = outfile.getvalue().splitlines()
441
 
        self.assertEqual(lines, [b'test = "foo#bar"'])
442
 
        co2 = config.ConfigObj(lines)
443
 
        self.assertEqual(co2['test'], 'foo#bar')
444
 
 
445
 
    def test_triple_quotes(self):
446
 
        # Bug #710410: if the value string has triple quotes
447
 
        # then ConfigObj versions up to 4.7.2 will quote them wrong
448
 
        # and won't able to read them back
449
 
        triple_quotes_value = '''spam
450
 
""" that's my spam """
451
 
eggs'''
452
 
        co = config.ConfigObj()
453
 
        co['test'] = triple_quotes_value
454
 
        # While writing this test another bug in ConfigObj has been found:
455
 
        # method co.write() without arguments produces list of lines
456
 
        # one option per line, and multiline values are not split
457
 
        # across multiple lines,
458
 
        # and that breaks the parsing these lines back by ConfigObj.
459
 
        # This issue only affects test, but it's better to avoid
460
 
        # `co.write()` construct at all.
461
 
        # [bialix 20110222] bug report sent to ConfigObj's author
462
 
        outfile = BytesIO()
463
 
        co.write(outfile=outfile)
464
 
        output = outfile.getvalue()
465
 
        # now we're trying to read it back
466
 
        co2 = config.ConfigObj(BytesIO(output))
467
 
        self.assertEqual(triple_quotes_value, co2['test'])
468
 
 
469
 
 
470
 
erroneous_config = b"""[section] # line 1
471
 
good=good # line 2
472
 
[section] # line 3
473
 
whocares=notme # line 4
474
 
"""
475
 
 
476
 
 
477
 
class TestConfigObjErrors(tests.TestCase):
478
 
 
479
 
    def test_duplicate_section_name_error_line(self):
480
 
        try:
481
 
            co = configobj.ConfigObj(BytesIO(erroneous_config),
482
 
                                     raise_errors=True)
483
 
        except config.configobj.DuplicateError as e:
484
 
            self.assertEqual(3, e.line_number)
485
 
        else:
486
 
            self.fail('Error in config file not detected')
487
 
 
488
 
 
489
 
class TestConfig(tests.TestCase):
 
153
 
 
154
class TestConfig(TestCase):
490
155
 
491
156
    def test_constructs(self):
492
157
        config.Config()
 
158
 
 
159
    def test_no_default_editor(self):
 
160
        self.assertRaises(NotImplementedError, config.Config().get_editor)
493
161
 
494
162
    def test_user_email(self):
495
163
        my_config = InstrumentedConfig()
502
170
                         my_config.username())
503
171
        self.assertEqual(['_get_user_id'], my_config._calls)
504
172
 
 
173
    def test_signatures_default(self):
 
174
        my_config = config.Config()
 
175
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
176
                         my_config.signature_checking())
 
177
 
 
178
    def test_signatures_template_method(self):
 
179
        my_config = InstrumentedConfig()
 
180
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
181
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
182
 
 
183
    def test_signatures_template_method_none(self):
 
184
        my_config = InstrumentedConfig()
 
185
        my_config._signatures = None
 
186
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
187
                         my_config.signature_checking())
 
188
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
189
 
 
190
    def test_gpg_signing_command_default(self):
 
191
        my_config = config.Config()
 
192
        self.assertEqual('gpg', my_config.gpg_signing_command())
 
193
 
505
194
    def test_get_user_option_default(self):
506
195
        my_config = config.Config()
507
196
        self.assertEqual(None, my_config.get_user_option('no_option'))
508
197
 
509
 
    def test_validate_signatures_in_log_default(self):
510
 
        my_config = config.Config()
511
 
        self.assertEqual(False, my_config.validate_signatures_in_log())
512
 
 
513
 
    def test_get_change_editor(self):
514
 
        my_config = InstrumentedConfig()
515
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
516
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
517
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
518
 
        self.assertEqual(['vimdiff', '-fo', '{new_path}', '{old_path}'],
519
 
                         change_editor.command_template)
520
 
 
521
 
    def test_get_change_editor_implicit_args(self):
522
 
        # If there are no substitution variables, then assume the
523
 
        # old and new path are the last arguments.
524
 
        my_config = InstrumentedConfig()
525
 
        my_config._change_editor = 'vimdiff -o'
526
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
527
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
528
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
529
 
        self.assertEqual(['vimdiff', '-o', '{old_path}', '{new_path}'],
530
 
                         change_editor.command_template)
531
 
 
532
 
    def test_get_change_editor_old_style(self):
533
 
        # Test the old style format for the change_editor setting.
534
 
        my_config = InstrumentedConfig()
535
 
        my_config._change_editor = 'vimdiff -o @old_path @new_path'
536
 
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
537
 
        self.assertEqual(['_get_change_editor'], my_config._calls)
538
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
539
 
        self.assertEqual(['vimdiff', '-o', '{old_path}', '{new_path}'],
540
 
                         change_editor.command_template)
541
 
 
542
 
 
543
 
class TestIniConfig(tests.TestCaseInTempDir):
544
 
 
545
 
    def make_config_parser(self, s):
546
 
        conf = config.IniBasedConfig.from_string(s)
547
 
        return conf, conf._get_parser()
548
 
 
549
 
 
550
 
class TestIniConfigBuilding(TestIniConfig):
 
198
    def test_post_commit_default(self):
 
199
        my_config = config.Config()
 
200
        self.assertEqual(None, my_config.post_commit())
 
201
 
 
202
    def test_log_format_default(self):
 
203
        my_config = config.Config()
 
204
        self.assertEqual('long', my_config.log_format())
 
205
 
 
206
 
 
207
class TestConfigPath(TestCase):
 
208
 
 
209
    def setUp(self):
 
210
        super(TestConfigPath, self).setUp()
 
211
        self.old_home = os.environ.get('HOME', None)
 
212
        self.old_appdata = os.environ.get('APPDATA', None)
 
213
        os.environ['HOME'] = '/home/bogus'
 
214
        os.environ['APPDATA'] = \
 
215
            r'C:\Documents and Settings\bogus\Application Data'
 
216
 
 
217
    def tearDown(self):
 
218
        if self.old_home is None:
 
219
            del os.environ['HOME']
 
220
        else:
 
221
            os.environ['HOME'] = self.old_home
 
222
        if self.old_appdata is None:
 
223
            del os.environ['APPDATA']
 
224
        else:
 
225
            os.environ['APPDATA'] = self.old_appdata
 
226
        super(TestConfigPath, self).tearDown()
 
227
    
 
228
    def test_config_dir(self):
 
229
        if sys.platform == 'win32':
 
230
            self.assertEqual(config.config_dir(), 
 
231
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
 
232
        else:
 
233
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
 
234
 
 
235
    def test_config_filename(self):
 
236
        if sys.platform == 'win32':
 
237
            self.assertEqual(config.config_filename(), 
 
238
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
 
239
        else:
 
240
            self.assertEqual(config.config_filename(),
 
241
                             '/home/bogus/.bazaar/bazaar.conf')
 
242
 
 
243
    def test_branches_config_filename(self):
 
244
        if sys.platform == 'win32':
 
245
            self.assertEqual(config.branches_config_filename(), 
 
246
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
 
247
        else:
 
248
            self.assertEqual(config.branches_config_filename(),
 
249
                             '/home/bogus/.bazaar/branches.conf')
 
250
 
 
251
class TestIniConfig(TestCase):
551
252
 
552
253
    def test_contructs(self):
553
 
        config.IniBasedConfig()
 
254
        my_config = config.IniBasedConfig("nothing")
554
255
 
555
256
    def test_from_fp(self):
556
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
557
 
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
 
257
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
258
        my_config = config.IniBasedConfig(None)
 
259
        self.failUnless(
 
260
            isinstance(my_config._get_parser(file=config_file),
 
261
                        ConfigObj))
558
262
 
559
263
    def test_cached(self):
560
 
        my_config = config.IniBasedConfig.from_string(sample_config_text)
561
 
        parser = my_config._get_parser()
562
 
        self.assertTrue(my_config._get_parser() is parser)
563
 
 
564
 
    def _dummy_chown(self, path, uid, gid):
565
 
        self.path, self.uid, self.gid = path, uid, gid
566
 
 
567
 
    def test_ini_config_ownership(self):
568
 
        """Ensure that chown is happening during _write_config_file"""
569
 
        self.requireFeature(features.chown_feature)
570
 
        self.overrideAttr(os, 'chown', self._dummy_chown)
571
 
        self.path = self.uid = self.gid = None
572
 
        conf = config.IniBasedConfig(file_name='./foo.conf')
573
 
        conf._write_config_file()
574
 
        self.assertEqual(self.path, './foo.conf')
575
 
        self.assertTrue(isinstance(self.uid, int))
576
 
        self.assertTrue(isinstance(self.gid, int))
577
 
 
578
 
 
579
 
class TestIniConfigSaving(tests.TestCaseInTempDir):
580
 
 
581
 
    def test_cant_save_without_a_file_name(self):
582
 
        conf = config.IniBasedConfig()
583
 
        self.assertRaises(AssertionError, conf._write_config_file)
584
 
 
585
 
    def test_saved_with_content(self):
586
 
        content = b'foo = bar\n'
587
 
        config.IniBasedConfig.from_string(content, file_name='./test.conf',
588
 
                                          save=True)
589
 
        self.assertFileEqual(content, 'test.conf')
590
 
 
591
 
 
592
 
class TestIniConfigOptionExpansion(tests.TestCase):
593
 
    """Test option expansion from the IniConfig level.
594
 
 
595
 
    What we really want here is to test the Config level, but the class being
596
 
    abstract as far as storing values is concerned, this can't be done
597
 
    properly (yet).
598
 
    """
599
 
    # FIXME: This should be rewritten when all configs share a storage
600
 
    # implementation -- vila 2011-02-18
601
 
 
602
 
    def get_config(self, string=None):
603
 
        if string is None:
604
 
            string = b''
605
 
        c = config.IniBasedConfig.from_string(string)
606
 
        return c
607
 
 
608
 
    def assertExpansion(self, expected, conf, string, env=None):
609
 
        self.assertEqual(expected, conf.expand_options(string, env))
610
 
 
611
 
    def test_no_expansion(self):
612
 
        c = self.get_config('')
613
 
        self.assertExpansion('foo', c, 'foo')
614
 
 
615
 
    def test_env_adding_options(self):
616
 
        c = self.get_config('')
617
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
618
 
 
619
 
    def test_env_overriding_options(self):
620
 
        c = self.get_config('foo=baz')
621
 
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
622
 
 
623
 
    def test_simple_ref(self):
624
 
        c = self.get_config('foo=xxx')
625
 
        self.assertExpansion('xxx', c, '{foo}')
626
 
 
627
 
    def test_unknown_ref(self):
628
 
        c = self.get_config('')
629
 
        self.assertRaises(config.ExpandingUnknownOption,
630
 
                          c.expand_options, '{foo}')
631
 
 
632
 
    def test_indirect_ref(self):
633
 
        c = self.get_config('''
634
 
foo=xxx
635
 
bar={foo}
636
 
''')
637
 
        self.assertExpansion('xxx', c, '{bar}')
638
 
 
639
 
    def test_embedded_ref(self):
640
 
        c = self.get_config('''
641
 
foo=xxx
642
 
bar=foo
643
 
''')
644
 
        self.assertExpansion('xxx', c, '{{bar}}')
645
 
 
646
 
    def test_simple_loop(self):
647
 
        c = self.get_config('foo={foo}')
648
 
        self.assertRaises(config.OptionExpansionLoop, c.expand_options,
649
 
                          '{foo}')
650
 
 
651
 
    def test_indirect_loop(self):
652
 
        c = self.get_config('''
653
 
foo={bar}
654
 
bar={baz}
655
 
baz={foo}''')
656
 
        e = self.assertRaises(config.OptionExpansionLoop,
657
 
                              c.expand_options, '{foo}')
658
 
        self.assertEqual('foo->bar->baz', e.refs)
659
 
        self.assertEqual('{foo}', e.string)
660
 
 
661
 
    def test_list(self):
662
 
        conf = self.get_config('''
663
 
foo=start
664
 
bar=middle
665
 
baz=end
666
 
list={foo},{bar},{baz}
667
 
''')
668
 
        self.assertEqual(['start', 'middle', 'end'],
669
 
                         conf.get_user_option('list', expand=True))
670
 
 
671
 
    def test_cascading_list(self):
672
 
        conf = self.get_config('''
673
 
foo=start,{bar}
674
 
bar=middle,{baz}
675
 
baz=end
676
 
list={foo}
677
 
''')
678
 
        self.assertEqual(['start', 'middle', 'end'],
679
 
                         conf.get_user_option('list', expand=True))
680
 
 
681
 
    def test_pathological_hidden_list(self):
682
 
        conf = self.get_config('''
683
 
foo=bin
684
 
bar=go
685
 
start={foo
686
 
middle=},{
687
 
end=bar}
688
 
hidden={start}{middle}{end}
689
 
''')
690
 
        # Nope, it's either a string or a list, and the list wins as soon as a
691
 
        # ',' appears, so the string concatenation never occur.
692
 
        self.assertEqual(['{foo', '}', '{', 'bar}'],
693
 
                         conf.get_user_option('hidden', expand=True))
694
 
 
695
 
 
696
 
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
697
 
 
698
 
    def get_config(self, location, string=None):
699
 
        if string is None:
700
 
            string = ''
701
 
        # Since we don't save the config we won't strictly require to inherit
702
 
        # from TestCaseInTempDir, but an error occurs so quickly...
703
 
        c = config.LocationConfig.from_string(string, location)
704
 
        return c
705
 
 
706
 
    def test_dont_cross_unrelated_section(self):
707
 
        c = self.get_config('/another/branch/path', '''
708
 
[/one/branch/path]
709
 
foo = hello
710
 
bar = {foo}/2
711
 
 
712
 
[/another/branch/path]
713
 
bar = {foo}/2
714
 
''')
715
 
        self.assertRaises(config.ExpandingUnknownOption,
716
 
                          c.get_user_option, 'bar', expand=True)
717
 
 
718
 
    def test_cross_related_sections(self):
719
 
        c = self.get_config('/project/branch/path', '''
720
 
[/project]
721
 
foo = qu
722
 
 
723
 
[/project/branch/path]
724
 
bar = {foo}ux
725
 
''')
726
 
        self.assertEqual('quux', c.get_user_option('bar', expand=True))
727
 
 
728
 
 
729
 
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
730
 
 
731
 
    def test_cannot_reload_without_name(self):
732
 
        conf = config.IniBasedConfig.from_string(sample_config_text)
733
 
        self.assertRaises(AssertionError, conf.reload)
734
 
 
735
 
    def test_reload_see_new_value(self):
736
 
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
737
 
                                               file_name='./test/conf')
738
 
        c1._write_config_file()
739
 
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
740
 
                                               file_name='./test/conf')
741
 
        c2._write_config_file()
742
 
        self.assertEqual('vim', c1.get_user_option('editor'))
743
 
        self.assertEqual('emacs', c2.get_user_option('editor'))
744
 
        # Make sure we get the Right value
745
 
        c1.reload()
746
 
        self.assertEqual('emacs', c1.get_user_option('editor'))
747
 
 
748
 
 
749
 
class TestLockableConfig(tests.TestCaseInTempDir):
750
 
 
751
 
    scenarios = lockable_config_scenarios()
752
 
 
753
 
    # Set by load_tests
754
 
    config_class = None
755
 
    config_args = None
756
 
    config_section = None
757
 
 
758
 
    def setUp(self):
759
 
        super(TestLockableConfig, self).setUp()
760
 
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
761
 
        self.config = self.create_config(self._content)
762
 
 
763
 
    def get_existing_config(self):
764
 
        return self.config_class(*self.config_args)
765
 
 
766
 
    def create_config(self, content):
767
 
        kwargs = dict(save=True)
768
 
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
769
 
        return c
770
 
 
771
 
    def test_simple_read_access(self):
772
 
        self.assertEqual('1', self.config.get_user_option('one'))
773
 
 
774
 
    def test_simple_write_access(self):
775
 
        self.config.set_user_option('one', 'one')
776
 
        self.assertEqual('one', self.config.get_user_option('one'))
777
 
 
778
 
    def test_listen_to_the_last_speaker(self):
779
 
        c1 = self.config
780
 
        c2 = self.get_existing_config()
781
 
        c1.set_user_option('one', 'ONE')
782
 
        c2.set_user_option('two', 'TWO')
783
 
        self.assertEqual('ONE', c1.get_user_option('one'))
784
 
        self.assertEqual('TWO', c2.get_user_option('two'))
785
 
        # The second update respect the first one
786
 
        self.assertEqual('ONE', c2.get_user_option('one'))
787
 
 
788
 
    def test_last_speaker_wins(self):
789
 
        # If the same config is not shared, the same variable modified twice
790
 
        # can only see a single result.
791
 
        c1 = self.config
792
 
        c2 = self.get_existing_config()
793
 
        c1.set_user_option('one', 'c1')
794
 
        c2.set_user_option('one', 'c2')
795
 
        self.assertEqual('c2', c2._get_user_option('one'))
796
 
        # The first modification is still available until another refresh
797
 
        # occur
798
 
        self.assertEqual('c1', c1._get_user_option('one'))
799
 
        c1.set_user_option('two', 'done')
800
 
        self.assertEqual('c2', c1._get_user_option('one'))
801
 
 
802
 
    def test_writes_are_serialized(self):
803
 
        c1 = self.config
804
 
        c2 = self.get_existing_config()
805
 
 
806
 
        # We spawn a thread that will pause *during* the write
807
 
        before_writing = threading.Event()
808
 
        after_writing = threading.Event()
809
 
        writing_done = threading.Event()
810
 
        c1_orig = c1._write_config_file
811
 
 
812
 
        def c1_write_config_file():
813
 
            before_writing.set()
814
 
            c1_orig()
815
 
            # The lock is held. We wait for the main thread to decide when to
816
 
            # continue
817
 
            after_writing.wait()
818
 
        c1._write_config_file = c1_write_config_file
819
 
 
820
 
        def c1_set_option():
821
 
            c1.set_user_option('one', 'c1')
822
 
            writing_done.set()
823
 
        t1 = threading.Thread(target=c1_set_option)
824
 
        # Collect the thread after the test
825
 
        self.addCleanup(t1.join)
826
 
        # Be ready to unblock the thread if the test goes wrong
827
 
        self.addCleanup(after_writing.set)
828
 
        t1.start()
829
 
        before_writing.wait()
830
 
        self.assertTrue(c1._lock.is_held)
831
 
        self.assertRaises(errors.LockContention,
832
 
                          c2.set_user_option, 'one', 'c2')
833
 
        self.assertEqual('c1', c1.get_user_option('one'))
834
 
        # Let the lock be released
835
 
        after_writing.set()
836
 
        writing_done.wait()
837
 
        c2.set_user_option('one', 'c2')
838
 
        self.assertEqual('c2', c2.get_user_option('one'))
839
 
 
840
 
    def test_read_while_writing(self):
841
 
        c1 = self.config
842
 
        # We spawn a thread that will pause *during* the write
843
 
        ready_to_write = threading.Event()
844
 
        do_writing = threading.Event()
845
 
        writing_done = threading.Event()
846
 
        c1_orig = c1._write_config_file
847
 
 
848
 
        def c1_write_config_file():
849
 
            ready_to_write.set()
850
 
            # The lock is held. We wait for the main thread to decide when to
851
 
            # continue
852
 
            do_writing.wait()
853
 
            c1_orig()
854
 
            writing_done.set()
855
 
        c1._write_config_file = c1_write_config_file
856
 
 
857
 
        def c1_set_option():
858
 
            c1.set_user_option('one', 'c1')
859
 
        t1 = threading.Thread(target=c1_set_option)
860
 
        # Collect the thread after the test
861
 
        self.addCleanup(t1.join)
862
 
        # Be ready to unblock the thread if the test goes wrong
863
 
        self.addCleanup(do_writing.set)
864
 
        t1.start()
865
 
        # Ensure the thread is ready to write
866
 
        ready_to_write.wait()
867
 
        self.assertTrue(c1._lock.is_held)
868
 
        self.assertEqual('c1', c1.get_user_option('one'))
869
 
        # If we read during the write, we get the old value
870
 
        c2 = self.get_existing_config()
871
 
        self.assertEqual('1', c2.get_user_option('one'))
872
 
        # Let the writing occur and ensure it occurred
873
 
        do_writing.set()
874
 
        writing_done.wait()
875
 
        # Now we get the updated value
876
 
        c3 = self.get_existing_config()
877
 
        self.assertEqual('c1', c3.get_user_option('one'))
878
 
 
879
 
 
880
 
class TestGetUserOptionAs(TestIniConfig):
881
 
 
882
 
    def test_get_user_option_as_bool(self):
883
 
        conf, parser = self.make_config_parser("""
884
 
a_true_bool = true
885
 
a_false_bool = 0
886
 
an_invalid_bool = maybe
887
 
a_list = hmm, who knows ? # This is interpreted as a list !
888
 
""")
889
 
        get_bool = conf.get_user_option_as_bool
890
 
        self.assertEqual(True, get_bool('a_true_bool'))
891
 
        self.assertEqual(False, get_bool('a_false_bool'))
892
 
        warnings = []
893
 
 
894
 
        def warning(*args):
895
 
            warnings.append(args[0] % args[1:])
896
 
        self.overrideAttr(trace, 'warning', warning)
897
 
        msg = 'Value "%s" is not a boolean for "%s"'
898
 
        self.assertIs(None, get_bool('an_invalid_bool'))
899
 
        self.assertEqual(msg % ('maybe', 'an_invalid_bool'), warnings[0])
900
 
        warnings = []
901
 
        self.assertIs(None, get_bool('not_defined_in_this_config'))
902
 
        self.assertEqual([], warnings)
903
 
 
904
 
    def test_get_user_option_as_list(self):
905
 
        conf, parser = self.make_config_parser("""
906
 
a_list = a,b,c
907
 
length_1 = 1,
908
 
one_item = x
909
 
""")
910
 
        get_list = conf.get_user_option_as_list
911
 
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
912
 
        self.assertEqual(['1'], get_list('length_1'))
913
 
        self.assertEqual('x', conf.get_user_option('one_item'))
914
 
        # automatically cast to list
915
 
        self.assertEqual(['x'], get_list('one_item'))
916
 
 
917
 
 
918
 
class TestSupressWarning(TestIniConfig):
919
 
 
920
 
    def make_warnings_config(self, s):
921
 
        conf, parser = self.make_config_parser(s)
922
 
        return conf.suppress_warning
923
 
 
924
 
    def test_suppress_warning_unknown(self):
925
 
        suppress_warning = self.make_warnings_config('')
926
 
        self.assertEqual(False, suppress_warning('unknown_warning'))
927
 
 
928
 
    def test_suppress_warning_known(self):
929
 
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
930
 
        self.assertEqual(False, suppress_warning('c'))
931
 
        self.assertEqual(True, suppress_warning('a'))
932
 
        self.assertEqual(True, suppress_warning('b'))
933
 
 
934
 
 
935
 
class TestGetConfig(tests.TestCaseInTempDir):
 
264
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
265
        my_config = config.IniBasedConfig(None)
 
266
        parser = my_config._get_parser(file=config_file)
 
267
        self.failUnless(my_config._get_parser() is parser)
 
268
 
 
269
 
 
270
class TestGetConfig(TestCase):
936
271
 
937
272
    def test_constructs(self):
938
 
        config.GlobalConfig()
 
273
        my_config = config.GlobalConfig()
939
274
 
940
275
    def test_calls_read_filenames(self):
941
 
        # replace the class that is constructed, to check its parameters
 
276
        # replace the class that is constructured, to check its parameters
942
277
        oldparserclass = config.ConfigObj
943
278
        config.ConfigObj = InstrumentedConfigObj
944
279
        my_config = config.GlobalConfig()
946
281
            parser = my_config._get_parser()
947
282
        finally:
948
283
            config.ConfigObj = oldparserclass
949
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
950
 
        self.assertEqual(parser._calls, [('__init__', bedding.config_path(),
 
284
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
285
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
951
286
                                          'utf-8')])
952
287
 
953
288
 
954
 
class TestBranchConfig(tests.TestCaseWithTransport):
 
289
class TestBranchConfig(TestCaseInTempDir):
955
290
 
956
 
    def test_constructs_valid(self):
 
291
    def test_constructs(self):
957
292
        branch = FakeBranch()
958
293
        my_config = config.BranchConfig(branch)
959
 
        self.assertIsNot(None, my_config)
960
 
 
961
 
    def test_constructs_error(self):
962
294
        self.assertRaises(TypeError, config.BranchConfig)
963
295
 
964
296
    def test_get_location_config(self):
966
298
        my_config = config.BranchConfig(branch)
967
299
        location_config = my_config._get_location_config()
968
300
        self.assertEqual(branch.base, location_config.location)
969
 
        self.assertIs(location_config, my_config._get_location_config())
970
 
 
971
 
    def test_get_config(self):
972
 
        """The Branch.get_config method works properly"""
973
 
        b = controldir.ControlDir.create_standalone_workingtree('.').branch
974
 
        my_config = b.get_config()
975
 
        self.assertIs(my_config.get_user_option('wacky'), None)
976
 
        my_config.set_user_option('wacky', 'unlikely')
977
 
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
978
 
 
979
 
        # Ensure we get the same thing if we start again
980
 
        b2 = branch.Branch.open('.')
981
 
        my_config2 = b2.get_config()
982
 
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
983
 
 
984
 
    def test_has_explicit_nickname(self):
985
 
        b = self.make_branch('.')
986
 
        self.assertFalse(b.get_config().has_explicit_nickname())
987
 
        b.nick = 'foo'
988
 
        self.assertTrue(b.get_config().has_explicit_nickname())
989
 
 
990
 
    def test_config_url(self):
991
 
        """The Branch.get_config will use section that uses a local url"""
992
 
        branch = self.make_branch('branch')
993
 
        self.assertEqual('branch', branch.nick)
994
 
 
995
 
        local_url = urlutils.local_path_to_url('branch')
996
 
        conf = config.LocationConfig.from_string(
997
 
            '[%s]\nnickname = foobar' % (local_url,),
998
 
            local_url, save=True)
999
 
        self.assertIsNot(None, conf)
1000
 
        self.assertEqual('foobar', branch.nick)
1001
 
 
1002
 
    def test_config_local_path(self):
1003
 
        """The Branch.get_config will use a local system path"""
1004
 
        branch = self.make_branch('branch')
1005
 
        self.assertEqual('branch', branch.nick)
1006
 
 
1007
 
        local_path = osutils.getcwd().encode('utf8')
1008
 
        config.LocationConfig.from_string(
1009
 
            b'[%s/branch]\nnickname = barry' % (local_path,),
1010
 
            'branch', save=True)
1011
 
        # Now the branch will find its nick via the location config
1012
 
        self.assertEqual('barry', branch.nick)
1013
 
 
1014
 
    def test_config_creates_local(self):
1015
 
        """Creating a new entry in config uses a local path."""
1016
 
        branch = self.make_branch('branch', format='knit')
1017
 
        branch.set_push_location('http://foobar')
1018
 
        local_path = osutils.getcwd().encode('utf8')
1019
 
        # Surprisingly ConfigObj doesn't create a trailing newline
1020
 
        self.check_file_contents(bedding.locations_config_path(),
1021
 
                                 b'[%s/branch]\n'
1022
 
                                 b'push_location = http://foobar\n'
1023
 
                                 b'push_location:policy = norecurse\n'
1024
 
                                 % (local_path,))
1025
 
 
1026
 
    def test_autonick_urlencoded(self):
1027
 
        b = self.make_branch('!repo')
1028
 
        self.assertEqual('!repo', b.get_config().get_nickname())
1029
 
 
1030
 
    def test_autonick_uses_branch_name(self):
1031
 
        b = self.make_branch('foo', name='bar')
1032
 
        self.assertEqual('bar', b.get_config().get_nickname())
1033
 
 
1034
 
    def test_warn_if_masked(self):
1035
 
        warnings = []
1036
 
 
1037
 
        def warning(*args):
1038
 
            warnings.append(args[0] % args[1:])
1039
 
        self.overrideAttr(trace, 'warning', warning)
1040
 
 
1041
 
        def set_option(store, warn_masked=True):
1042
 
            warnings[:] = []
1043
 
            conf.set_user_option('example_option', repr(store), store=store,
1044
 
                                 warn_masked=warn_masked)
1045
 
 
1046
 
        def assertWarning(warning):
1047
 
            if warning is None:
1048
 
                self.assertEqual(0, len(warnings))
1049
 
            else:
1050
 
                self.assertEqual(1, len(warnings))
1051
 
                self.assertEqual(warning, warnings[0])
1052
 
        branch = self.make_branch('.')
1053
 
        conf = branch.get_config()
1054
 
        set_option(config.STORE_GLOBAL)
1055
 
        assertWarning(None)
1056
 
        set_option(config.STORE_BRANCH)
1057
 
        assertWarning(None)
1058
 
        set_option(config.STORE_GLOBAL)
1059
 
        assertWarning('Value "4" is masked by "3" from branch.conf')
1060
 
        set_option(config.STORE_GLOBAL, warn_masked=False)
1061
 
        assertWarning(None)
1062
 
        set_option(config.STORE_LOCATION)
1063
 
        assertWarning(None)
1064
 
        set_option(config.STORE_BRANCH)
1065
 
        assertWarning('Value "3" is masked by "0" from locations.conf')
1066
 
        set_option(config.STORE_BRANCH, warn_masked=False)
1067
 
        assertWarning(None)
1068
 
 
1069
 
 
1070
 
class TestGlobalConfigItems(tests.TestCaseInTempDir):
1071
 
 
1072
 
    def _get_empty_config(self):
 
301
        self.failUnless(location_config is my_config._get_location_config())
 
302
 
 
303
 
 
304
class TestGlobalConfigItems(TestCase):
 
305
 
 
306
    def test_user_id(self):
 
307
        config_file = StringIO(sample_config_text.encode('utf-8'))
1073
308
        my_config = config.GlobalConfig()
1074
 
        return my_config
1075
 
 
1076
 
    def _get_sample_config(self):
1077
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
1078
 
        return my_config
1079
 
 
1080
 
    def test_user_id(self):
1081
 
        my_config = config.GlobalConfig.from_string(sample_config_text)
 
309
        my_config._parser = my_config._get_parser(file=config_file)
1082
310
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1083
311
                         my_config._get_user_id())
1084
312
 
1085
313
    def test_absent_user_id(self):
 
314
        config_file = StringIO("")
1086
315
        my_config = config.GlobalConfig()
 
316
        my_config._parser = my_config._get_parser(file=config_file)
1087
317
        self.assertEqual(None, my_config._get_user_id())
1088
318
 
 
319
    def test_configured_editor(self):
 
320
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
321
        my_config = config.GlobalConfig()
 
322
        my_config._parser = my_config._get_parser(file=config_file)
 
323
        self.assertEqual("vim", my_config.get_editor())
 
324
 
 
325
    def test_signatures_always(self):
 
326
        config_file = StringIO(sample_always_signatures)
 
327
        my_config = config.GlobalConfig()
 
328
        my_config._parser = my_config._get_parser(file=config_file)
 
329
        self.assertEqual(config.CHECK_ALWAYS,
 
330
                         my_config.signature_checking())
 
331
        self.assertEqual(True, my_config.signature_needed())
 
332
 
 
333
    def test_signatures_if_possible(self):
 
334
        config_file = StringIO(sample_maybe_signatures)
 
335
        my_config = config.GlobalConfig()
 
336
        my_config._parser = my_config._get_parser(file=config_file)
 
337
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
338
                         my_config.signature_checking())
 
339
        self.assertEqual(False, my_config.signature_needed())
 
340
 
 
341
    def test_signatures_ignore(self):
 
342
        config_file = StringIO(sample_ignore_signatures)
 
343
        my_config = config.GlobalConfig()
 
344
        my_config._parser = my_config._get_parser(file=config_file)
 
345
        self.assertEqual(config.CHECK_NEVER,
 
346
                         my_config.signature_checking())
 
347
        self.assertEqual(False, my_config.signature_needed())
 
348
 
 
349
    def _get_sample_config(self):
 
350
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
351
        my_config = config.GlobalConfig()
 
352
        my_config._parser = my_config._get_parser(file=config_file)
 
353
        return my_config
 
354
 
 
355
    def test_gpg_signing_command(self):
 
356
        my_config = self._get_sample_config()
 
357
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
 
358
        self.assertEqual(False, my_config.signature_needed())
 
359
 
 
360
    def _get_empty_config(self):
 
361
        config_file = StringIO("")
 
362
        my_config = config.GlobalConfig()
 
363
        my_config._parser = my_config._get_parser(file=config_file)
 
364
        return my_config
 
365
 
 
366
    def test_gpg_signing_command_unset(self):
 
367
        my_config = self._get_empty_config()
 
368
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
369
 
1089
370
    def test_get_user_option_default(self):
1090
371
        my_config = self._get_empty_config()
1091
372
        self.assertEqual(None, my_config.get_user_option('no_option'))
1094
375
        my_config = self._get_sample_config()
1095
376
        self.assertEqual("something",
1096
377
                         my_config.get_user_option('user_global_option'))
 
378
        
 
379
    def test_post_commit_default(self):
 
380
        my_config = self._get_sample_config()
 
381
        self.assertEqual(None, my_config.post_commit())
1097
382
 
1098
 
    def test_configured_validate_signatures_in_log(self):
 
383
    def test_configured_logformat(self):
1099
384
        my_config = self._get_sample_config()
1100
 
        self.assertEqual(True, my_config.validate_signatures_in_log())
 
385
        self.assertEqual("short", my_config.log_format())
1101
386
 
1102
387
    def test_get_alias(self):
1103
388
        my_config = self._get_sample_config()
1104
389
        self.assertEqual('help', my_config.get_alias('h'))
1105
390
 
1106
 
    def test_get_aliases(self):
1107
 
        my_config = self._get_sample_config()
1108
 
        aliases = my_config.get_aliases()
1109
 
        self.assertEqual(2, len(aliases))
1110
 
        sorted_keys = sorted(aliases)
1111
 
        self.assertEqual('help', aliases[sorted_keys[0]])
1112
 
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1113
 
 
1114
391
    def test_get_no_alias(self):
1115
392
        my_config = self._get_sample_config()
1116
393
        self.assertEqual(None, my_config.get_alias('foo'))
1119
396
        my_config = self._get_sample_config()
1120
397
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1121
398
 
1122
 
    def test_get_change_editor(self):
1123
 
        my_config = self._get_sample_config()
1124
 
        change_editor = my_config.get_change_editor('old', 'new')
1125
 
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
1126
 
        self.assertEqual('vimdiff -of {new_path} {old_path}',
1127
 
                         ' '.join(change_editor.command_template))
1128
 
 
1129
 
    def test_get_no_change_editor(self):
1130
 
        my_config = self._get_empty_config()
1131
 
        change_editor = my_config.get_change_editor('old', 'new')
1132
 
        self.assertIs(None, change_editor)
1133
 
 
1134
 
    def test_get_merge_tools(self):
1135
 
        conf = self._get_sample_config()
1136
 
        tools = conf.get_merge_tools()
1137
 
        self.log(repr(tools))
1138
 
        self.assertEqual(
1139
 
            {u'funkytool': u'funkytool "arg with spaces" {this_temp}',
1140
 
             u'sometool': u'sometool {base} {this} {other} -o {result}',
1141
 
             u'newtool': u'"newtool with spaces" {this_temp}'},
1142
 
            tools)
1143
 
 
1144
 
    def test_get_merge_tools_empty(self):
1145
 
        conf = self._get_empty_config()
1146
 
        tools = conf.get_merge_tools()
1147
 
        self.assertEqual({}, tools)
1148
 
 
1149
 
    def test_find_merge_tool(self):
1150
 
        conf = self._get_sample_config()
1151
 
        cmdline = conf.find_merge_tool('sometool')
1152
 
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
1153
 
 
1154
 
    def test_find_merge_tool_not_found(self):
1155
 
        conf = self._get_sample_config()
1156
 
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1157
 
        self.assertIs(cmdline, None)
1158
 
 
1159
 
    def test_find_merge_tool_known(self):
1160
 
        conf = self._get_empty_config()
1161
 
        cmdline = conf.find_merge_tool('kdiff3')
1162
 
        self.assertEqual('kdiff3 {base} {this} {other} -o {result}', cmdline)
1163
 
 
1164
 
    def test_find_merge_tool_override_known(self):
1165
 
        conf = self._get_empty_config()
1166
 
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
1167
 
        cmdline = conf.find_merge_tool('kdiff3')
1168
 
        self.assertEqual('kdiff3 blah', cmdline)
1169
 
 
1170
 
 
1171
 
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1172
 
 
1173
 
    def test_empty(self):
1174
 
        my_config = config.GlobalConfig()
1175
 
        self.assertEqual(0, len(my_config.get_aliases()))
1176
 
 
1177
 
    def test_set_alias(self):
1178
 
        my_config = config.GlobalConfig()
1179
 
        alias_value = 'commit --strict'
1180
 
        my_config.set_alias('commit', alias_value)
1181
 
        new_config = config.GlobalConfig()
1182
 
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1183
 
 
1184
 
    def test_remove_alias(self):
1185
 
        my_config = config.GlobalConfig()
1186
 
        my_config.set_alias('commit', 'commit --strict')
1187
 
        # Now remove the alias again.
1188
 
        my_config.unset_alias('commit')
1189
 
        new_config = config.GlobalConfig()
1190
 
        self.assertIs(None, new_config.get_alias('commit'))
1191
 
 
1192
 
 
1193
 
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1194
 
 
1195
 
    def test_constructs_valid(self):
1196
 
        config.LocationConfig('http://example.com')
1197
 
 
1198
 
    def test_constructs_error(self):
 
399
class TestLocationConfig(TestCase):
 
400
 
 
401
    def test_constructs(self):
 
402
        my_config = config.LocationConfig('http://example.com')
1199
403
        self.assertRaises(TypeError, config.LocationConfig)
1200
404
 
1201
405
    def test_branch_calls_read_filenames(self):
1202
406
        # This is testing the correct file names are provided.
1203
407
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1204
408
        #
1205
 
        # replace the class that is constructed, to check its parameters
 
409
        # replace the class that is constructured, to check its parameters
1206
410
        oldparserclass = config.ConfigObj
1207
411
        config.ConfigObj = InstrumentedConfigObj
 
412
        my_config = config.LocationConfig('http://www.example.com')
1208
413
        try:
1209
 
            my_config = config.LocationConfig('http://www.example.com')
1210
414
            parser = my_config._get_parser()
1211
415
        finally:
1212
416
            config.ConfigObj = oldparserclass
1213
 
        self.assertIsInstance(parser, InstrumentedConfigObj)
 
417
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1214
418
        self.assertEqual(parser._calls,
1215
 
                         [('__init__', bedding.locations_config_path(),
1216
 
                           'utf-8')])
 
419
                         [('__init__', config.branches_config_filename())])
1217
420
 
1218
421
    def test_get_global_config(self):
1219
 
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
 
422
        my_config = config.LocationConfig('http://example.com')
1220
423
        global_config = my_config._get_global_config()
1221
 
        self.assertIsInstance(global_config, config.GlobalConfig)
1222
 
        self.assertIs(global_config, my_config._get_global_config())
1223
 
 
1224
 
    def assertLocationMatching(self, expected):
1225
 
        self.assertEqual(expected,
1226
 
                         list(self.my_location_config._get_matching_sections()))
1227
 
 
1228
 
    def test__get_matching_sections_no_match(self):
1229
 
        self.get_branch_config('/')
1230
 
        self.assertLocationMatching([])
1231
 
 
1232
 
    def test__get_matching_sections_exact(self):
1233
 
        self.get_branch_config('http://www.example.com')
1234
 
        self.assertLocationMatching([('http://www.example.com', '')])
1235
 
 
1236
 
    def test__get_matching_sections_suffix_does_not(self):
1237
 
        self.get_branch_config('http://www.example.com-com')
1238
 
        self.assertLocationMatching([])
1239
 
 
1240
 
    def test__get_matching_sections_subdir_recursive(self):
1241
 
        self.get_branch_config('http://www.example.com/com')
1242
 
        self.assertLocationMatching([('http://www.example.com', 'com')])
1243
 
 
1244
 
    def test__get_matching_sections_ignoreparent(self):
1245
 
        self.get_branch_config('http://www.example.com/ignoreparent')
1246
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1247
 
                                      '')])
1248
 
 
1249
 
    def test__get_matching_sections_ignoreparent_subdir(self):
1250
 
        self.get_branch_config(
1251
 
            'http://www.example.com/ignoreparent/childbranch')
1252
 
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1253
 
                                      'childbranch')])
1254
 
 
1255
 
    def test__get_matching_sections_subdir_trailing_slash(self):
1256
 
        self.get_branch_config('/b')
1257
 
        self.assertLocationMatching([('/b/', '')])
1258
 
 
1259
 
    def test__get_matching_sections_subdir_child(self):
1260
 
        self.get_branch_config('/a/foo')
1261
 
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
1262
 
 
1263
 
    def test__get_matching_sections_subdir_child_child(self):
1264
 
        self.get_branch_config('/a/foo/bar')
1265
 
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
1266
 
 
1267
 
    def test__get_matching_sections_trailing_slash_with_children(self):
1268
 
        self.get_branch_config('/a/')
1269
 
        self.assertLocationMatching([('/a/', '')])
1270
 
 
1271
 
    def test__get_matching_sections_explicit_over_glob(self):
1272
 
        # XXX: 2006-09-08 jamesh
1273
 
        # This test only passes because ord('c') > ord('*').  If there
1274
 
        # was a config section for '/a/?', it would get precedence
1275
 
        # over '/a/c'.
1276
 
        self.get_branch_config('/a/c')
1277
 
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
1278
 
 
1279
 
    def test__get_option_policy_normal(self):
1280
 
        self.get_branch_config('http://www.example.com')
1281
 
        self.assertEqual(
1282
 
            self.my_location_config._get_config_policy(
1283
 
                'http://www.example.com', 'normal_option'),
1284
 
            config.POLICY_NONE)
1285
 
 
1286
 
    def test__get_option_policy_norecurse(self):
1287
 
        self.get_branch_config('http://www.example.com')
1288
 
        self.assertEqual(
1289
 
            self.my_location_config._get_option_policy(
1290
 
                'http://www.example.com', 'norecurse_option'),
1291
 
            config.POLICY_NORECURSE)
1292
 
        # Test old recurse=False setting:
1293
 
        self.assertEqual(
1294
 
            self.my_location_config._get_option_policy(
1295
 
                'http://www.example.com/norecurse', 'normal_option'),
1296
 
            config.POLICY_NORECURSE)
1297
 
 
1298
 
    def test__get_option_policy_normal(self):
1299
 
        self.get_branch_config('http://www.example.com')
1300
 
        self.assertEqual(
1301
 
            self.my_location_config._get_option_policy(
1302
 
                'http://www.example.com', 'appendpath_option'),
1303
 
            config.POLICY_APPENDPATH)
1304
 
 
1305
 
    def test__get_options_with_policy(self):
1306
 
        self.get_branch_config('/dir/subdir',
1307
 
                               location_config="""\
1308
 
[/dir]
1309
 
other_url = /other-dir
1310
 
other_url:policy = appendpath
1311
 
[/dir/subdir]
1312
 
other_url = /other-subdir
1313
 
""")
1314
 
        self.assertOptions(
1315
 
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1316
 
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1317
 
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
1318
 
            self.my_location_config)
 
424
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
425
        self.failUnless(global_config is my_config._get_global_config())
 
426
 
 
427
    def test__get_section_no_match(self):
 
428
        self.get_location_config('/')
 
429
        self.assertEqual(None, self.my_config._get_section())
 
430
        
 
431
    def test__get_section_exact(self):
 
432
        self.get_location_config('http://www.example.com')
 
433
        self.assertEqual('http://www.example.com',
 
434
                         self.my_config._get_section())
 
435
   
 
436
    def test__get_section_suffix_does_not(self):
 
437
        self.get_location_config('http://www.example.com-com')
 
438
        self.assertEqual(None, self.my_config._get_section())
 
439
 
 
440
    def test__get_section_subdir_recursive(self):
 
441
        self.get_location_config('http://www.example.com/com')
 
442
        self.assertEqual('http://www.example.com',
 
443
                         self.my_config._get_section())
 
444
 
 
445
    def test__get_section_subdir_matches(self):
 
446
        self.get_location_config('http://www.example.com/useglobal')
 
447
        self.assertEqual('http://www.example.com/useglobal',
 
448
                         self.my_config._get_section())
 
449
 
 
450
    def test__get_section_subdir_nonrecursive(self):
 
451
        self.get_location_config(
 
452
            'http://www.example.com/useglobal/childbranch')
 
453
        self.assertEqual('http://www.example.com',
 
454
                         self.my_config._get_section())
 
455
 
 
456
    def test__get_section_subdir_trailing_slash(self):
 
457
        self.get_location_config('/b')
 
458
        self.assertEqual('/b/', self.my_config._get_section())
 
459
 
 
460
    def test__get_section_subdir_child(self):
 
461
        self.get_location_config('/a/foo')
 
462
        self.assertEqual('/a/*', self.my_config._get_section())
 
463
 
 
464
    def test__get_section_subdir_child_child(self):
 
465
        self.get_location_config('/a/foo/bar')
 
466
        self.assertEqual('/a/', self.my_config._get_section())
 
467
 
 
468
    def test__get_section_trailing_slash_with_children(self):
 
469
        self.get_location_config('/a/')
 
470
        self.assertEqual('/a/', self.my_config._get_section())
 
471
 
 
472
    def test__get_section_explicit_over_glob(self):
 
473
        self.get_location_config('/a/c')
 
474
        self.assertEqual('/a/c', self.my_config._get_section())
 
475
 
 
476
    def get_location_config(self, location, global_config=None):
 
477
        if global_config is None:
 
478
            global_file = StringIO(sample_config_text)
 
479
        else:
 
480
            global_file = StringIO(global_config)
 
481
        branches_file = StringIO(sample_branches_text)
 
482
        self.my_config = config.LocationConfig(location)
 
483
        self.my_config._get_parser(branches_file)
 
484
        self.my_config._get_global_config()._get_parser(global_file)
1319
485
 
1320
486
    def test_location_without_username(self):
1321
 
        self.get_branch_config('http://www.example.com/ignoreparent')
1322
 
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
487
        self.get_location_config('http://www.example.com/useglobal')
 
488
        self.assertEqual('Robert Collins <robertc@example.com>',
1323
489
                         self.my_config.username())
1324
490
 
1325
491
    def test_location_not_listed(self):
1326
 
        """Test that the global username is used when no location matches"""
1327
 
        self.get_branch_config('/home/robertc/sources')
1328
 
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
492
        self.get_location_config('/home/robertc/sources')
 
493
        self.assertEqual('Robert Collins <robertc@example.com>',
1329
494
                         self.my_config.username())
1330
495
 
1331
496
    def test_overriding_location(self):
1332
 
        self.get_branch_config('http://www.example.com/foo')
 
497
        self.get_location_config('http://www.example.com/foo')
1333
498
        self.assertEqual('Robert Collins <robertc@example.org>',
1334
499
                         self.my_config.username())
1335
500
 
 
501
    def test_signatures_not_set(self):
 
502
        self.get_location_config('http://www.example.com',
 
503
                                 global_config=sample_ignore_signatures)
 
504
        self.assertEqual(config.CHECK_NEVER,
 
505
                         self.my_config.signature_checking())
 
506
 
 
507
    def test_signatures_never(self):
 
508
        self.get_location_config('/a/c')
 
509
        self.assertEqual(config.CHECK_NEVER,
 
510
                         self.my_config.signature_checking())
 
511
        
 
512
    def test_signatures_when_available(self):
 
513
        self.get_location_config('/a/', global_config=sample_ignore_signatures)
 
514
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
515
                         self.my_config.signature_checking())
 
516
        
 
517
    def test_signatures_always(self):
 
518
        self.get_location_config('/b')
 
519
        self.assertEqual(config.CHECK_ALWAYS,
 
520
                         self.my_config.signature_checking())
 
521
        
 
522
    def test_gpg_signing_command(self):
 
523
        self.get_location_config('/b')
 
524
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
525
 
 
526
    def test_gpg_signing_command_missing(self):
 
527
        self.get_location_config('/a')
 
528
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
529
 
1336
530
    def test_get_user_option_global(self):
1337
 
        self.get_branch_config('/a')
 
531
        self.get_location_config('/a')
1338
532
        self.assertEqual('something',
1339
533
                         self.my_config.get_user_option('user_global_option'))
1340
534
 
1341
535
    def test_get_user_option_local(self):
1342
 
        self.get_branch_config('/a')
 
536
        self.get_location_config('/a')
1343
537
        self.assertEqual('local',
1344
538
                         self.my_config.get_user_option('user_local_option'))
1345
 
 
1346
 
    def test_get_user_option_appendpath(self):
1347
 
        # returned as is for the base path:
1348
 
        self.get_branch_config('http://www.example.com')
1349
 
        self.assertEqual('append',
1350
 
                         self.my_config.get_user_option('appendpath_option'))
1351
 
        # Extra path components get appended:
1352
 
        self.get_branch_config('http://www.example.com/a/b/c')
1353
 
        self.assertEqual('append/a/b/c',
1354
 
                         self.my_config.get_user_option('appendpath_option'))
1355
 
        # Overriden for http://www.example.com/dir, where it is a
1356
 
        # normal option:
1357
 
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1358
 
        self.assertEqual('normal',
1359
 
                         self.my_config.get_user_option('appendpath_option'))
1360
 
 
1361
 
    def test_get_user_option_norecurse(self):
1362
 
        self.get_branch_config('http://www.example.com')
1363
 
        self.assertEqual('norecurse',
1364
 
                         self.my_config.get_user_option('norecurse_option'))
1365
 
        self.get_branch_config('http://www.example.com/dir')
1366
 
        self.assertEqual(None,
1367
 
                         self.my_config.get_user_option('norecurse_option'))
1368
 
        # http://www.example.com/norecurse is a recurse=False section
1369
 
        # that redefines normal_option.  Subdirectories do not pick up
1370
 
        # this redefinition.
1371
 
        self.get_branch_config('http://www.example.com/norecurse')
1372
 
        self.assertEqual('norecurse',
1373
 
                         self.my_config.get_user_option('normal_option'))
1374
 
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1375
 
        self.assertEqual('normal',
1376
 
                         self.my_config.get_user_option('normal_option'))
1377
 
 
1378
 
    def test_set_user_option_norecurse(self):
1379
 
        self.get_branch_config('http://www.example.com')
1380
 
        self.my_config.set_user_option('foo', 'bar',
1381
 
                                       store=config.STORE_LOCATION_NORECURSE)
1382
 
        self.assertEqual(
1383
 
            self.my_location_config._get_option_policy(
1384
 
                'http://www.example.com', 'foo'),
1385
 
            config.POLICY_NORECURSE)
1386
 
 
1387
 
    def test_set_user_option_appendpath(self):
1388
 
        self.get_branch_config('http://www.example.com')
1389
 
        self.my_config.set_user_option('foo', 'bar',
1390
 
                                       store=config.STORE_LOCATION_APPENDPATH)
1391
 
        self.assertEqual(
1392
 
            self.my_location_config._get_option_policy(
1393
 
                'http://www.example.com', 'foo'),
1394
 
            config.POLICY_APPENDPATH)
1395
 
 
1396
 
    def test_set_user_option_change_policy(self):
1397
 
        self.get_branch_config('http://www.example.com')
1398
 
        self.my_config.set_user_option('norecurse_option', 'normal',
1399
 
                                       store=config.STORE_LOCATION)
1400
 
        self.assertEqual(
1401
 
            self.my_location_config._get_option_policy(
1402
 
                'http://www.example.com', 'norecurse_option'),
1403
 
            config.POLICY_NONE)
1404
 
 
1405
 
    def get_branch_config(self, location, global_config=None,
1406
 
                          location_config=None):
1407
 
        my_branch = FakeBranch(location)
 
539
        
 
540
    def test_post_commit_default(self):
 
541
        self.get_location_config('/a/c')
 
542
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
543
                         self.my_config.post_commit())
 
544
 
 
545
 
 
546
class TestLocationConfig(TestCaseInTempDir):
 
547
 
 
548
    def get_location_config(self, location, global_config=None):
1408
549
        if global_config is None:
1409
 
            global_config = sample_config_text
1410
 
        if location_config is None:
1411
 
            location_config = sample_branches_text
1412
 
 
1413
 
        config.GlobalConfig.from_string(global_config, save=True)
1414
 
        config.LocationConfig.from_string(location_config, my_branch.base,
1415
 
                                          save=True)
1416
 
        my_config = config.BranchConfig(my_branch)
1417
 
        self.my_config = my_config
1418
 
        self.my_location_config = my_config._get_location_config()
1419
 
 
1420
 
    def test_set_user_setting_sets_and_saves2(self):
1421
 
        self.get_branch_config('/a/c')
1422
 
        self.assertIs(self.my_config.get_user_option('foo'), None)
1423
 
        self.my_config.set_user_option('foo', 'bar')
1424
 
        self.assertEqual(
1425
 
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1426
 
            b'foo = bar')
1427
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
1428
 
        self.my_config.set_user_option('foo', 'baz',
1429
 
                                       store=config.STORE_LOCATION)
1430
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1431
 
        self.my_config.set_user_option('foo', 'qux')
1432
 
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1433
 
 
1434
 
    def test_get_bzr_remote_path(self):
1435
 
        my_config = config.LocationConfig('/a/c')
1436
 
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1437
 
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1438
 
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1439
 
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1440
 
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1441
 
 
1442
 
 
1443
 
precedence_global = b'option = global'
1444
 
precedence_branch = b'option = branch'
1445
 
precedence_location = b"""
1446
 
[http://]
1447
 
recurse = true
1448
 
option = recurse
1449
 
[http://example.com/specific]
1450
 
option = exact
1451
 
"""
1452
 
 
1453
 
 
1454
 
class TestBranchConfigItems(tests.TestCaseInTempDir):
1455
 
 
1456
 
    def get_branch_config(self, global_config=None, location=None,
1457
 
                          location_config=None, branch_data_config=None):
1458
 
        my_branch = FakeBranch(location)
1459
 
        if global_config is not None:
1460
 
            config.GlobalConfig.from_string(global_config, save=True)
1461
 
        if location_config is not None:
1462
 
            config.LocationConfig.from_string(location_config, my_branch.base,
1463
 
                                              save=True)
1464
 
        my_config = config.BranchConfig(my_branch)
1465
 
        if branch_data_config is not None:
1466
 
            my_config.branch.control_files.files['branch.conf'] = \
1467
 
                branch_data_config
1468
 
        return my_config
 
550
            global_file = StringIO(sample_config_text.encode('utf-8'))
 
551
        else:
 
552
            global_file = StringIO(global_config.encode('utf-8'))
 
553
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
 
554
        self.my_config = config.LocationConfig(location)
 
555
        self.my_config._get_parser(branches_file)
 
556
        self.my_config._get_global_config()._get_parser(global_file)
 
557
 
 
558
    def test_set_user_setting_sets_and_saves(self):
 
559
        self.get_location_config('/a/c')
 
560
        record = InstrumentedConfigObj("foo")
 
561
        self.my_config._parser = record
 
562
 
 
563
        real_mkdir = os.mkdir
 
564
        self.created = False
 
565
        def checked_mkdir(path, mode=0777):
 
566
            self.log('making directory: %s', path)
 
567
            real_mkdir(path, mode)
 
568
            self.created = True
 
569
 
 
570
        os.mkdir = checked_mkdir
 
571
        try:
 
572
            self.my_config.set_user_option('foo', 'bar')
 
573
        finally:
 
574
            os.mkdir = real_mkdir
 
575
 
 
576
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
 
577
        self.assertEqual([('__contains__', '/a/c'),
 
578
                          ('__contains__', '/a/c/'),
 
579
                          ('__setitem__', '/a/c', {}),
 
580
                          ('__getitem__', '/a/c'),
 
581
                          ('__setitem__', 'foo', 'bar'),
 
582
                          ('write',)],
 
583
                         record._calls[1:])
 
584
 
 
585
 
 
586
class TestBranchConfigItems(TestCase):
1469
587
 
1470
588
    def test_user_id(self):
1471
589
        branch = FakeBranch()
1472
590
        my_config = config.BranchConfig(branch)
1473
 
        self.assertIsNot(None, my_config.username())
1474
 
        my_config.branch.control_files.files['email'] = "John"
1475
 
        my_config.set_user_option('email',
1476
 
                                  "Robert Collins <robertc@example.org>")
1477
 
        self.assertEqual("Robert Collins <robertc@example.org>",
1478
 
                         my_config.username())
1479
 
 
1480
 
    def test_BRZ_EMAIL_OVERRIDES(self):
1481
 
        self.overrideEnv('BRZ_EMAIL', "Robert Collins <robertc@example.org>")
1482
 
        branch = FakeBranch()
1483
 
        my_config = config.BranchConfig(branch)
1484
 
        self.assertEqual("Robert Collins <robertc@example.org>",
1485
 
                         my_config.username())
1486
 
 
1487
 
    def test_BRZ_EMAIL_OVERRIDES(self):
1488
 
        self.overrideEnv('BZR_EMAIL', "Robert Collins <robertc@example.org>")
1489
 
        branch = FakeBranch()
1490
 
        my_config = config.BranchConfig(branch)
1491
 
        self.assertEqual("Robert Collins <robertc@example.org>",
1492
 
                         my_config.username())
 
591
        self.assertEqual("Robert Collins <robertc@example.net>",
 
592
                         my_config._get_user_id())
 
593
        branch.control_files.email = "John"
 
594
        self.assertEqual("John", my_config._get_user_id())
 
595
 
 
596
    def test_not_set_in_branch(self):
 
597
        branch = FakeBranch()
 
598
        my_config = config.BranchConfig(branch)
 
599
        branch.control_files.email = None
 
600
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
601
        (my_config._get_location_config().
 
602
            _get_global_config()._get_parser(config_file))
 
603
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
604
                         my_config._get_user_id())
 
605
        branch.control_files.email = "John"
 
606
        self.assertEqual("John", my_config._get_user_id())
 
607
 
 
608
    def test_BZREMAIL_OVERRIDES(self):
 
609
        os.environ['BZREMAIL'] = "Robert Collins <robertc@example.org>"
 
610
        branch = FakeBranch()
 
611
        my_config = config.BranchConfig(branch)
 
612
        self.assertEqual("Robert Collins <robertc@example.org>",
 
613
                         my_config.username())
 
614
    
 
615
    def test_signatures_forced(self):
 
616
        branch = FakeBranch()
 
617
        my_config = config.BranchConfig(branch)
 
618
        config_file = StringIO(sample_always_signatures)
 
619
        (my_config._get_location_config().
 
620
            _get_global_config()._get_parser(config_file))
 
621
        self.assertEqual(config.CHECK_ALWAYS, my_config.signature_checking())
 
622
 
 
623
    def test_gpg_signing_command(self):
 
624
        branch = FakeBranch()
 
625
        my_config = config.BranchConfig(branch)
 
626
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
627
        (my_config._get_location_config().
 
628
            _get_global_config()._get_parser(config_file))
 
629
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1493
630
 
1494
631
    def test_get_user_option_global(self):
1495
 
        my_config = self.get_branch_config(global_config=sample_config_text)
 
632
        branch = FakeBranch()
 
633
        my_config = config.BranchConfig(branch)
 
634
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
635
        (my_config._get_location_config().
 
636
            _get_global_config()._get_parser(config_file))
1496
637
        self.assertEqual('something',
1497
638
                         my_config.get_user_option('user_global_option'))
1498
639
 
1499
 
    def test_config_precedence(self):
1500
 
        # FIXME: eager test, luckily no persitent config file makes it fail
1501
 
        # -- vila 20100716
1502
 
        my_config = self.get_branch_config(global_config=precedence_global)
1503
 
        self.assertEqual(my_config.get_user_option('option'), 'global')
1504
 
        my_config = self.get_branch_config(global_config=precedence_global,
1505
 
                                           branch_data_config=precedence_branch)
1506
 
        self.assertEqual(my_config.get_user_option('option'), 'branch')
1507
 
        my_config = self.get_branch_config(
1508
 
            global_config=precedence_global,
1509
 
            branch_data_config=precedence_branch,
1510
 
            location_config=precedence_location)
1511
 
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
1512
 
        my_config = self.get_branch_config(
1513
 
            global_config=precedence_global,
1514
 
            branch_data_config=precedence_branch,
1515
 
            location_config=precedence_location,
1516
 
            location='http://example.com/specific')
1517
 
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1518
 
 
1519
 
 
1520
 
class TestMailAddressExtraction(tests.TestCase):
 
640
    def test_post_commit_default(self):
 
641
        branch = FakeBranch()
 
642
        branch.base='/a/c'
 
643
        my_config = config.BranchConfig(branch)
 
644
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
645
        (my_config._get_location_config().
 
646
            _get_global_config()._get_parser(config_file))
 
647
        branch_file = StringIO(sample_branches_text)
 
648
        my_config._get_location_config()._get_parser(branch_file)
 
649
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
650
                         my_config.post_commit())
 
651
 
 
652
 
 
653
class TestMailAddressExtraction(TestCase):
1521
654
 
1522
655
    def test_extract_email_address(self):
1523
656
        self.assertEqual('jane@test.com',
1524
657
                         config.extract_email_address('Jane <jane@test.com>'))
1525
 
        self.assertRaises(config.NoEmailInUsername,
 
658
        self.assertRaises(errors.BzrError,
1526
659
                          config.extract_email_address, 'Jane Tester')
1527
 
 
1528
 
    def test_parse_username(self):
1529
 
        self.assertEqual(('', 'jdoe@example.com'),
1530
 
                         config.parse_username('jdoe@example.com'))
1531
 
        self.assertEqual(('', 'jdoe@example.com'),
1532
 
                         config.parse_username('<jdoe@example.com>'))
1533
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1534
 
                         config.parse_username('John Doe <jdoe@example.com>'))
1535
 
        self.assertEqual(('John Doe', ''),
1536
 
                         config.parse_username('John Doe'))
1537
 
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1538
 
                         config.parse_username('John Doe jdoe@example.com'))
1539
 
 
1540
 
 
1541
 
class TestTreeConfig(tests.TestCaseWithTransport):
1542
 
 
1543
 
    def test_get_value(self):
1544
 
        """Test that retreiving a value from a section is possible"""
1545
 
        branch = self.make_branch('.')
1546
 
        tree_config = config.TreeConfig(branch)
1547
 
        tree_config.set_option('value', 'key', 'SECTION')
1548
 
        tree_config.set_option('value2', 'key2')
1549
 
        tree_config.set_option('value3-top', 'key3')
1550
 
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1551
 
        value = tree_config.get_option('key', 'SECTION')
1552
 
        self.assertEqual(value, 'value')
1553
 
        value = tree_config.get_option('key2')
1554
 
        self.assertEqual(value, 'value2')
1555
 
        self.assertEqual(tree_config.get_option('non-existant'), None)
1556
 
        value = tree_config.get_option('non-existant', 'SECTION')
1557
 
        self.assertEqual(value, None)
1558
 
        value = tree_config.get_option('non-existant', default='default')
1559
 
        self.assertEqual(value, 'default')
1560
 
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1561
 
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1562
 
        self.assertEqual(value, 'default')
1563
 
        value = tree_config.get_option('key3')
1564
 
        self.assertEqual(value, 'value3-top')
1565
 
        value = tree_config.get_option('key3', 'SECTION')
1566
 
        self.assertEqual(value, 'value3-section')
1567
 
 
1568
 
 
1569
 
class TestTransportConfig(tests.TestCaseWithTransport):
1570
 
 
1571
 
    def test_load_utf8(self):
1572
 
        """Ensure we can load an utf8-encoded file."""
1573
 
        t = self.get_transport()
1574
 
        unicode_user = u'b\N{Euro Sign}ar'
1575
 
        unicode_content = u'user=%s' % (unicode_user,)
1576
 
        utf8_content = unicode_content.encode('utf8')
1577
 
        # Store the raw content in the config file
1578
 
        t.put_bytes('foo.conf', utf8_content)
1579
 
        conf = config.TransportConfig(t, 'foo.conf')
1580
 
        self.assertEqual(unicode_user, conf.get_option('user'))
1581
 
 
1582
 
    def test_load_non_ascii(self):
1583
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
1584
 
        t = self.get_transport()
1585
 
        t.put_bytes('foo.conf', b'user=foo\n#\xff\n')
1586
 
        conf = config.TransportConfig(t, 'foo.conf')
1587
 
        self.assertRaises(config.ConfigContentError, conf._get_configobj)
1588
 
 
1589
 
    def test_load_erroneous_content(self):
1590
 
        """Ensure we display a proper error on content that can't be parsed."""
1591
 
        t = self.get_transport()
1592
 
        t.put_bytes('foo.conf', b'[open_section\n')
1593
 
        conf = config.TransportConfig(t, 'foo.conf')
1594
 
        self.assertRaises(config.ParseConfigError, conf._get_configobj)
1595
 
 
1596
 
    def test_load_permission_denied(self):
1597
 
        """Ensure we get an empty config file if the file is inaccessible."""
1598
 
        warnings = []
1599
 
 
1600
 
        def warning(*args):
1601
 
            warnings.append(args[0] % args[1:])
1602
 
        self.overrideAttr(trace, 'warning', warning)
1603
 
 
1604
 
        class DenyingTransport(object):
1605
 
 
1606
 
            def __init__(self, base):
1607
 
                self.base = base
1608
 
 
1609
 
            def get_bytes(self, relpath):
1610
 
                raise errors.PermissionDenied(relpath, "")
1611
 
 
1612
 
        cfg = config.TransportConfig(
1613
 
            DenyingTransport("nonexisting://"), 'control.conf')
1614
 
        self.assertIs(None, cfg.get_option('non-existant', 'SECTION'))
1615
 
        self.assertEqual(
1616
 
            warnings,
1617
 
            [u'Permission denied while trying to open configuration file '
1618
 
             u'nonexisting:///control.conf.'])
1619
 
 
1620
 
    def test_get_value(self):
1621
 
        """Test that retreiving a value from a section is possible"""
1622
 
        bzrdir_config = config.TransportConfig(self.get_transport('.'),
1623
 
                                               'control.conf')
1624
 
        bzrdir_config.set_option('value', 'key', 'SECTION')
1625
 
        bzrdir_config.set_option('value2', 'key2')
1626
 
        bzrdir_config.set_option('value3-top', 'key3')
1627
 
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1628
 
        value = bzrdir_config.get_option('key', 'SECTION')
1629
 
        self.assertEqual(value, 'value')
1630
 
        value = bzrdir_config.get_option('key2')
1631
 
        self.assertEqual(value, 'value2')
1632
 
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1633
 
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1634
 
        self.assertEqual(value, None)
1635
 
        value = bzrdir_config.get_option('non-existant', default='default')
1636
 
        self.assertEqual(value, 'default')
1637
 
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1638
 
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1639
 
                                         default='default')
1640
 
        self.assertEqual(value, 'default')
1641
 
        value = bzrdir_config.get_option('key3')
1642
 
        self.assertEqual(value, 'value3-top')
1643
 
        value = bzrdir_config.get_option('key3', 'SECTION')
1644
 
        self.assertEqual(value, 'value3-section')
1645
 
 
1646
 
    def test_set_unset_default_stack_on(self):
1647
 
        my_dir = self.make_controldir('.')
1648
 
        bzrdir_config = config.BzrDirConfig(my_dir)
1649
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1650
 
        bzrdir_config.set_default_stack_on('Foo')
1651
 
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1652
 
                         'default_stack_on'))
1653
 
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1654
 
        bzrdir_config.set_default_stack_on(None)
1655
 
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1656
 
 
1657
 
 
1658
 
class TestOldConfigHooks(tests.TestCaseWithTransport):
1659
 
 
1660
 
    def setUp(self):
1661
 
        super(TestOldConfigHooks, self).setUp()
1662
 
        create_configs_with_file_option(self)
1663
 
 
1664
 
    def assertGetHook(self, conf, name, value):
1665
 
        calls = []
1666
 
 
1667
 
        def hook(*args):
1668
 
            calls.append(args)
1669
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
1670
 
        self.addCleanup(
1671
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
1672
 
        self.assertLength(0, calls)
1673
 
        actual_value = conf.get_user_option(name)
1674
 
        self.assertEqual(value, actual_value)
1675
 
        self.assertLength(1, calls)
1676
 
        self.assertEqual((conf, name, value), calls[0])
1677
 
 
1678
 
    def test_get_hook_breezy(self):
1679
 
        self.assertGetHook(self.breezy_config, 'file', 'breezy')
1680
 
 
1681
 
    def test_get_hook_locations(self):
1682
 
        self.assertGetHook(self.locations_config, 'file', 'locations')
1683
 
 
1684
 
    def test_get_hook_branch(self):
1685
 
        # Since locations masks branch, we define a different option
1686
 
        self.branch_config.set_user_option('file2', 'branch')
1687
 
        self.assertGetHook(self.branch_config, 'file2', 'branch')
1688
 
 
1689
 
    def assertSetHook(self, conf, name, value):
1690
 
        calls = []
1691
 
 
1692
 
        def hook(*args):
1693
 
            calls.append(args)
1694
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
1695
 
        self.addCleanup(
1696
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
1697
 
        self.assertLength(0, calls)
1698
 
        conf.set_user_option(name, value)
1699
 
        self.assertLength(1, calls)
1700
 
        # We can't assert the conf object below as different configs use
1701
 
        # different means to implement set_user_option and we care only about
1702
 
        # coverage here.
1703
 
        self.assertEqual((name, value), calls[0][1:])
1704
 
 
1705
 
    def test_set_hook_breezy(self):
1706
 
        self.assertSetHook(self.breezy_config, 'foo', 'breezy')
1707
 
 
1708
 
    def test_set_hook_locations(self):
1709
 
        self.assertSetHook(self.locations_config, 'foo', 'locations')
1710
 
 
1711
 
    def test_set_hook_branch(self):
1712
 
        self.assertSetHook(self.branch_config, 'foo', 'branch')
1713
 
 
1714
 
    def assertRemoveHook(self, conf, name, section_name=None):
1715
 
        calls = []
1716
 
 
1717
 
        def hook(*args):
1718
 
            calls.append(args)
1719
 
        config.OldConfigHooks.install_named_hook('remove', hook, None)
1720
 
        self.addCleanup(
1721
 
            config.OldConfigHooks.uninstall_named_hook, 'remove', None)
1722
 
        self.assertLength(0, calls)
1723
 
        conf.remove_user_option(name, section_name)
1724
 
        self.assertLength(1, calls)
1725
 
        # We can't assert the conf object below as different configs use
1726
 
        # different means to implement remove_user_option and we care only about
1727
 
        # coverage here.
1728
 
        self.assertEqual((name,), calls[0][1:])
1729
 
 
1730
 
    def test_remove_hook_breezy(self):
1731
 
        self.assertRemoveHook(self.breezy_config, 'file')
1732
 
 
1733
 
    def test_remove_hook_locations(self):
1734
 
        self.assertRemoveHook(self.locations_config, 'file',
1735
 
                              self.locations_config.location)
1736
 
 
1737
 
    def test_remove_hook_branch(self):
1738
 
        self.assertRemoveHook(self.branch_config, 'file')
1739
 
 
1740
 
    def assertLoadHook(self, name, conf_class, *conf_args):
1741
 
        calls = []
1742
 
 
1743
 
        def hook(*args):
1744
 
            calls.append(args)
1745
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
1746
 
        self.addCleanup(
1747
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
1748
 
        self.assertLength(0, calls)
1749
 
        # Build a config
1750
 
        conf = conf_class(*conf_args)
1751
 
        # Access an option to trigger a load
1752
 
        conf.get_user_option(name)
1753
 
        self.assertLength(1, calls)
1754
 
        # Since we can't assert about conf, we just use the number of calls ;-/
1755
 
 
1756
 
    def test_load_hook_breezy(self):
1757
 
        self.assertLoadHook('file', config.GlobalConfig)
1758
 
 
1759
 
    def test_load_hook_locations(self):
1760
 
        self.assertLoadHook('file', config.LocationConfig, self.tree.basedir)
1761
 
 
1762
 
    def test_load_hook_branch(self):
1763
 
        self.assertLoadHook('file', config.BranchConfig, self.tree.branch)
1764
 
 
1765
 
    def assertSaveHook(self, conf):
1766
 
        calls = []
1767
 
 
1768
 
        def hook(*args):
1769
 
            calls.append(args)
1770
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
1771
 
        self.addCleanup(
1772
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
1773
 
        self.assertLength(0, calls)
1774
 
        # Setting an option triggers a save
1775
 
        conf.set_user_option('foo', 'bar')
1776
 
        self.assertLength(1, calls)
1777
 
        # Since we can't assert about conf, we just use the number of calls ;-/
1778
 
 
1779
 
    def test_save_hook_breezy(self):
1780
 
        self.assertSaveHook(self.breezy_config)
1781
 
 
1782
 
    def test_save_hook_locations(self):
1783
 
        self.assertSaveHook(self.locations_config)
1784
 
 
1785
 
    def test_save_hook_branch(self):
1786
 
        self.assertSaveHook(self.branch_config)
1787
 
 
1788
 
 
1789
 
class TestOldConfigHooksForRemote(tests.TestCaseWithTransport):
1790
 
    """Tests config hooks for remote configs.
1791
 
 
1792
 
    No tests for the remove hook as this is not implemented there.
1793
 
    """
1794
 
 
1795
 
    def setUp(self):
1796
 
        super(TestOldConfigHooksForRemote, self).setUp()
1797
 
        self.transport_server = test_server.SmartTCPServer_for_testing
1798
 
        create_configs_with_file_option(self)
1799
 
 
1800
 
    def assertGetHook(self, conf, name, value):
1801
 
        calls = []
1802
 
 
1803
 
        def hook(*args):
1804
 
            calls.append(args)
1805
 
        config.OldConfigHooks.install_named_hook('get', hook, None)
1806
 
        self.addCleanup(
1807
 
            config.OldConfigHooks.uninstall_named_hook, 'get', None)
1808
 
        self.assertLength(0, calls)
1809
 
        actual_value = conf.get_option(name)
1810
 
        self.assertEqual(value, actual_value)
1811
 
        self.assertLength(1, calls)
1812
 
        self.assertEqual((conf, name, value), calls[0])
1813
 
 
1814
 
    def test_get_hook_remote_branch(self):
1815
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1816
 
        self.assertGetHook(remote_branch._get_config(), 'file', 'branch')
1817
 
 
1818
 
    def test_get_hook_remote_bzrdir(self):
1819
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1820
 
        conf = remote_bzrdir._get_config()
1821
 
        conf.set_option('remotedir', 'file')
1822
 
        self.assertGetHook(conf, 'file', 'remotedir')
1823
 
 
1824
 
    def assertSetHook(self, conf, name, value):
1825
 
        calls = []
1826
 
 
1827
 
        def hook(*args):
1828
 
            calls.append(args)
1829
 
        config.OldConfigHooks.install_named_hook('set', hook, None)
1830
 
        self.addCleanup(
1831
 
            config.OldConfigHooks.uninstall_named_hook, 'set', None)
1832
 
        self.assertLength(0, calls)
1833
 
        conf.set_option(value, name)
1834
 
        self.assertLength(1, calls)
1835
 
        # We can't assert the conf object below as different configs use
1836
 
        # different means to implement set_user_option and we care only about
1837
 
        # coverage here.
1838
 
        self.assertEqual((name, value), calls[0][1:])
1839
 
 
1840
 
    def test_set_hook_remote_branch(self):
1841
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1842
 
        self.addCleanup(remote_branch.lock_write().unlock)
1843
 
        self.assertSetHook(remote_branch._get_config(), 'file', 'remote')
1844
 
 
1845
 
    def test_set_hook_remote_bzrdir(self):
1846
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1847
 
        self.addCleanup(remote_branch.lock_write().unlock)
1848
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1849
 
        self.assertSetHook(remote_bzrdir._get_config(), 'file', 'remotedir')
1850
 
 
1851
 
    def assertLoadHook(self, expected_nb_calls, name, conf_class, *conf_args):
1852
 
        calls = []
1853
 
 
1854
 
        def hook(*args):
1855
 
            calls.append(args)
1856
 
        config.OldConfigHooks.install_named_hook('load', hook, None)
1857
 
        self.addCleanup(
1858
 
            config.OldConfigHooks.uninstall_named_hook, 'load', None)
1859
 
        self.assertLength(0, calls)
1860
 
        # Build a config
1861
 
        conf = conf_class(*conf_args)
1862
 
        # Access an option to trigger a load
1863
 
        conf.get_option(name)
1864
 
        self.assertLength(expected_nb_calls, calls)
1865
 
        # Since we can't assert about conf, we just use the number of calls ;-/
1866
 
 
1867
 
    def test_load_hook_remote_branch(self):
1868
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1869
 
        self.assertLoadHook(
1870
 
            1, 'file', remote.RemoteBranchConfig, remote_branch)
1871
 
 
1872
 
    def test_load_hook_remote_bzrdir(self):
1873
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1874
 
        # The config file doesn't exist, set an option to force its creation
1875
 
        conf = remote_bzrdir._get_config()
1876
 
        conf.set_option('remotedir', 'file')
1877
 
        # We get one call for the server and one call for the client, this is
1878
 
        # caused by the differences in implementations betwen
1879
 
        # SmartServerBzrDirRequestConfigFile (in smart/bzrdir.py) and
1880
 
        # SmartServerBranchGetConfigFile (in smart/branch.py)
1881
 
        self.assertLoadHook(
1882
 
            2, 'file', remote.RemoteBzrDirConfig, remote_bzrdir)
1883
 
 
1884
 
    def assertSaveHook(self, conf):
1885
 
        calls = []
1886
 
 
1887
 
        def hook(*args):
1888
 
            calls.append(args)
1889
 
        config.OldConfigHooks.install_named_hook('save', hook, None)
1890
 
        self.addCleanup(
1891
 
            config.OldConfigHooks.uninstall_named_hook, 'save', None)
1892
 
        self.assertLength(0, calls)
1893
 
        # Setting an option triggers a save
1894
 
        conf.set_option('foo', 'bar')
1895
 
        self.assertLength(1, calls)
1896
 
        # Since we can't assert about conf, we just use the number of calls ;-/
1897
 
 
1898
 
    def test_save_hook_remote_branch(self):
1899
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1900
 
        self.addCleanup(remote_branch.lock_write().unlock)
1901
 
        self.assertSaveHook(remote_branch._get_config())
1902
 
 
1903
 
    def test_save_hook_remote_bzrdir(self):
1904
 
        remote_branch = branch.Branch.open(self.get_url('tree'))
1905
 
        self.addCleanup(remote_branch.lock_write().unlock)
1906
 
        remote_bzrdir = controldir.ControlDir.open(self.get_url('tree'))
1907
 
        self.assertSaveHook(remote_bzrdir._get_config())
1908
 
 
1909
 
 
1910
 
class TestOptionNames(tests.TestCase):
1911
 
 
1912
 
    def is_valid(self, name):
1913
 
        return config._option_ref_re.match('{%s}' % name) is not None
1914
 
 
1915
 
    def test_valid_names(self):
1916
 
        self.assertTrue(self.is_valid('foo'))
1917
 
        self.assertTrue(self.is_valid('foo.bar'))
1918
 
        self.assertTrue(self.is_valid('f1'))
1919
 
        self.assertTrue(self.is_valid('_'))
1920
 
        self.assertTrue(self.is_valid('__bar__'))
1921
 
        self.assertTrue(self.is_valid('a_'))
1922
 
        self.assertTrue(self.is_valid('a1'))
1923
 
        # Don't break bzr-svn for no good reason
1924
 
        self.assertTrue(self.is_valid('guessed-layout'))
1925
 
 
1926
 
    def test_invalid_names(self):
1927
 
        self.assertFalse(self.is_valid(' foo'))
1928
 
        self.assertFalse(self.is_valid('foo '))
1929
 
        self.assertFalse(self.is_valid('1'))
1930
 
        self.assertFalse(self.is_valid('1,2'))
1931
 
        self.assertFalse(self.is_valid('foo$'))
1932
 
        self.assertFalse(self.is_valid('!foo'))
1933
 
        self.assertFalse(self.is_valid('foo.'))
1934
 
        self.assertFalse(self.is_valid('foo..bar'))
1935
 
        self.assertFalse(self.is_valid('{}'))
1936
 
        self.assertFalse(self.is_valid('{a}'))
1937
 
        self.assertFalse(self.is_valid('a\n'))
1938
 
        self.assertFalse(self.is_valid('-'))
1939
 
        self.assertFalse(self.is_valid('-a'))
1940
 
        self.assertFalse(self.is_valid('a-'))
1941
 
        self.assertFalse(self.is_valid('a--a'))
1942
 
 
1943
 
    def assertSingleGroup(self, reference):
1944
 
        # the regexp is used with split and as such should match the reference
1945
 
        # *only*, if more groups needs to be defined, (?:...) should be used.
1946
 
        m = config._option_ref_re.match('{a}')
1947
 
        self.assertLength(1, m.groups())
1948
 
 
1949
 
    def test_valid_references(self):
1950
 
        self.assertSingleGroup('{a}')
1951
 
        self.assertSingleGroup('{{a}}')
1952
 
 
1953
 
 
1954
 
class TestOption(tests.TestCase):
1955
 
 
1956
 
    def test_default_value(self):
1957
 
        opt = config.Option('foo', default='bar')
1958
 
        self.assertEqual('bar', opt.get_default())
1959
 
 
1960
 
    def test_callable_default_value(self):
1961
 
        def bar_as_unicode():
1962
 
            return u'bar'
1963
 
        opt = config.Option('foo', default=bar_as_unicode)
1964
 
        self.assertEqual('bar', opt.get_default())
1965
 
 
1966
 
    def test_default_value_from_env(self):
1967
 
        opt = config.Option('foo', default='bar', default_from_env=['FOO'])
1968
 
        self.overrideEnv('FOO', 'quux')
1969
 
        # Env variable provides a default taking over the option one
1970
 
        self.assertEqual('quux', opt.get_default())
1971
 
 
1972
 
    def test_first_default_value_from_env_wins(self):
1973
 
        opt = config.Option('foo', default='bar',
1974
 
                            default_from_env=['NO_VALUE', 'FOO', 'BAZ'])
1975
 
        self.overrideEnv('FOO', 'foo')
1976
 
        self.overrideEnv('BAZ', 'baz')
1977
 
        # The first env var set wins
1978
 
        self.assertEqual('foo', opt.get_default())
1979
 
 
1980
 
    def test_not_supported_list_default_value(self):
1981
 
        self.assertRaises(AssertionError, config.Option, 'foo', default=[1])
1982
 
 
1983
 
    def test_not_supported_object_default_value(self):
1984
 
        self.assertRaises(AssertionError, config.Option, 'foo',
1985
 
                          default=object())
1986
 
 
1987
 
    def test_not_supported_callable_default_value_not_unicode(self):
1988
 
        def bar_not_unicode():
1989
 
            return b'bar'
1990
 
        opt = config.Option('foo', default=bar_not_unicode)
1991
 
        self.assertRaises(AssertionError, opt.get_default)
1992
 
 
1993
 
    def test_get_help_topic(self):
1994
 
        opt = config.Option('foo')
1995
 
        self.assertEqual('foo', opt.get_help_topic())
1996
 
 
1997
 
 
1998
 
class TestOptionConverter(tests.TestCase):
1999
 
 
2000
 
    def assertConverted(self, expected, opt, value):
2001
 
        self.assertEqual(expected, opt.convert_from_unicode(None, value))
2002
 
 
2003
 
    def assertCallsWarning(self, opt, value):
2004
 
        warnings = []
2005
 
 
2006
 
        def warning(*args):
2007
 
            warnings.append(args[0] % args[1:])
2008
 
        self.overrideAttr(trace, 'warning', warning)
2009
 
        self.assertEqual(None, opt.convert_from_unicode(None, value))
2010
 
        self.assertLength(1, warnings)
2011
 
        self.assertEqual(
2012
 
            'Value "%s" is not valid for "%s"' % (value, opt.name),
2013
 
            warnings[0])
2014
 
 
2015
 
    def assertCallsError(self, opt, value):
2016
 
        self.assertRaises(config.ConfigOptionValueError,
2017
 
                          opt.convert_from_unicode, None, value)
2018
 
 
2019
 
    def assertConvertInvalid(self, opt, invalid_value):
2020
 
        opt.invalid = None
2021
 
        self.assertEqual(None, opt.convert_from_unicode(None, invalid_value))
2022
 
        opt.invalid = 'warning'
2023
 
        self.assertCallsWarning(opt, invalid_value)
2024
 
        opt.invalid = 'error'
2025
 
        self.assertCallsError(opt, invalid_value)
2026
 
 
2027
 
 
2028
 
class TestOptionWithBooleanConverter(TestOptionConverter):
2029
 
 
2030
 
    def get_option(self):
2031
 
        return config.Option('foo', help='A boolean.',
2032
 
                             from_unicode=config.bool_from_store)
2033
 
 
2034
 
    def test_convert_invalid(self):
2035
 
        opt = self.get_option()
2036
 
        # A string that is not recognized as a boolean
2037
 
        self.assertConvertInvalid(opt, u'invalid-boolean')
2038
 
        # A list of strings is never recognized as a boolean
2039
 
        self.assertConvertInvalid(opt, [u'not', u'a', u'boolean'])
2040
 
 
2041
 
    def test_convert_valid(self):
2042
 
        opt = self.get_option()
2043
 
        self.assertConverted(True, opt, u'True')
2044
 
        self.assertConverted(True, opt, u'1')
2045
 
        self.assertConverted(False, opt, u'False')
2046
 
 
2047
 
 
2048
 
class TestOptionWithIntegerConverter(TestOptionConverter):
2049
 
 
2050
 
    def get_option(self):
2051
 
        return config.Option('foo', help='An integer.',
2052
 
                             from_unicode=config.int_from_store)
2053
 
 
2054
 
    def test_convert_invalid(self):
2055
 
        opt = self.get_option()
2056
 
        # A string that is not recognized as an integer
2057
 
        self.assertConvertInvalid(opt, u'forty-two')
2058
 
        # A list of strings is never recognized as an integer
2059
 
        self.assertConvertInvalid(opt, [u'a', u'list'])
2060
 
 
2061
 
    def test_convert_valid(self):
2062
 
        opt = self.get_option()
2063
 
        self.assertConverted(16, opt, u'16')
2064
 
 
2065
 
 
2066
 
class TestOptionWithSIUnitConverter(TestOptionConverter):
2067
 
 
2068
 
    def get_option(self):
2069
 
        return config.Option('foo', help='An integer in SI units.',
2070
 
                             from_unicode=config.int_SI_from_store)
2071
 
 
2072
 
    def test_convert_invalid(self):
2073
 
        opt = self.get_option()
2074
 
        self.assertConvertInvalid(opt, u'not-a-unit')
2075
 
        self.assertConvertInvalid(opt, u'Gb')  # Forgot the value
2076
 
        self.assertConvertInvalid(opt, u'1b')  # Forgot the unit
2077
 
        self.assertConvertInvalid(opt, u'1GG')
2078
 
        self.assertConvertInvalid(opt, u'1Mbb')
2079
 
        self.assertConvertInvalid(opt, u'1MM')
2080
 
 
2081
 
    def test_convert_valid(self):
2082
 
        opt = self.get_option()
2083
 
        self.assertConverted(int(5e3), opt, u'5kb')
2084
 
        self.assertConverted(int(5e6), opt, u'5M')
2085
 
        self.assertConverted(int(5e6), opt, u'5MB')
2086
 
        self.assertConverted(int(5e9), opt, u'5g')
2087
 
        self.assertConverted(int(5e9), opt, u'5gB')
2088
 
        self.assertConverted(100, opt, u'100')
2089
 
 
2090
 
 
2091
 
class TestListOption(TestOptionConverter):
2092
 
 
2093
 
    def get_option(self):
2094
 
        return config.ListOption('foo', help='A list.')
2095
 
 
2096
 
    def test_convert_invalid(self):
2097
 
        opt = self.get_option()
2098
 
        # We don't even try to convert a list into a list, we only expect
2099
 
        # strings
2100
 
        self.assertConvertInvalid(opt, [1])
2101
 
        # No string is invalid as all forms can be converted to a list
2102
 
 
2103
 
    def test_convert_valid(self):
2104
 
        opt = self.get_option()
2105
 
        # An empty string is an empty list
2106
 
        self.assertConverted([], opt, '')  # Using a bare str() just in case
2107
 
        self.assertConverted([], opt, u'')
2108
 
        # A boolean
2109
 
        self.assertConverted([u'True'], opt, u'True')
2110
 
        # An integer
2111
 
        self.assertConverted([u'42'], opt, u'42')
2112
 
        # A single string
2113
 
        self.assertConverted([u'bar'], opt, u'bar')
2114
 
 
2115
 
 
2116
 
class TestRegistryOption(TestOptionConverter):
2117
 
 
2118
 
    def get_option(self, registry):
2119
 
        return config.RegistryOption('foo', registry,
2120
 
                                     help='A registry option.')
2121
 
 
2122
 
    def test_convert_invalid(self):
2123
 
        registry = _mod_registry.Registry()
2124
 
        opt = self.get_option(registry)
2125
 
        self.assertConvertInvalid(opt, [1])
2126
 
        self.assertConvertInvalid(opt, u"notregistered")
2127
 
 
2128
 
    def test_convert_valid(self):
2129
 
        registry = _mod_registry.Registry()
2130
 
        registry.register("someval", 1234)
2131
 
        opt = self.get_option(registry)
2132
 
        # Using a bare str() just in case
2133
 
        self.assertConverted(1234, opt, "someval")
2134
 
        self.assertConverted(1234, opt, u'someval')
2135
 
        self.assertConverted(None, opt, None)
2136
 
 
2137
 
    def test_help(self):
2138
 
        registry = _mod_registry.Registry()
2139
 
        registry.register("someval", 1234, help="some option")
2140
 
        registry.register("dunno", 1234, help="some other option")
2141
 
        opt = self.get_option(registry)
2142
 
        self.assertEqual(
2143
 
            'A registry option.\n'
2144
 
            '\n'
2145
 
            'The following values are supported:\n'
2146
 
            ' dunno - some other option\n'
2147
 
            ' someval - some option\n',
2148
 
            opt.help)
2149
 
 
2150
 
    def test_get_help_text(self):
2151
 
        registry = _mod_registry.Registry()
2152
 
        registry.register("someval", 1234, help="some option")
2153
 
        registry.register("dunno", 1234, help="some other option")
2154
 
        opt = self.get_option(registry)
2155
 
        self.assertEqual(
2156
 
            'A registry option.\n'
2157
 
            '\n'
2158
 
            'The following values are supported:\n'
2159
 
            ' dunno - some other option\n'
2160
 
            ' someval - some option\n',
2161
 
            opt.get_help_text())
2162
 
 
2163
 
 
2164
 
class TestOptionRegistry(tests.TestCase):
2165
 
 
2166
 
    def setUp(self):
2167
 
        super(TestOptionRegistry, self).setUp()
2168
 
        # Always start with an empty registry
2169
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2170
 
        self.registry = config.option_registry
2171
 
 
2172
 
    def test_register(self):
2173
 
        opt = config.Option('foo')
2174
 
        self.registry.register(opt)
2175
 
        self.assertIs(opt, self.registry.get('foo'))
2176
 
 
2177
 
    def test_registered_help(self):
2178
 
        opt = config.Option('foo', help='A simple option')
2179
 
        self.registry.register(opt)
2180
 
        self.assertEqual('A simple option', self.registry.get_help('foo'))
2181
 
 
2182
 
    def test_dont_register_illegal_name(self):
2183
 
        self.assertRaises(config.IllegalOptionName,
2184
 
                          self.registry.register, config.Option(' foo'))
2185
 
        self.assertRaises(config.IllegalOptionName,
2186
 
                          self.registry.register, config.Option('bar,'))
2187
 
 
2188
 
    lazy_option = config.Option('lazy_foo', help='Lazy help')
2189
 
 
2190
 
    def test_register_lazy(self):
2191
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2192
 
                                    'TestOptionRegistry.lazy_option')
2193
 
        self.assertIs(self.lazy_option, self.registry.get('lazy_foo'))
2194
 
 
2195
 
    def test_registered_lazy_help(self):
2196
 
        self.registry.register_lazy('lazy_foo', self.__module__,
2197
 
                                    'TestOptionRegistry.lazy_option')
2198
 
        self.assertEqual('Lazy help', self.registry.get_help('lazy_foo'))
2199
 
 
2200
 
    def test_dont_lazy_register_illegal_name(self):
2201
 
        # This is where the root cause of http://pad.lv/1235099 is better
2202
 
        # understood: 'register_lazy' doc string mentions that key should match
2203
 
        # the option name which indirectly requires that the option name is a
2204
 
        # valid python identifier. We violate that rule here (using a key that
2205
 
        # doesn't match the option name) to test the option name checking.
2206
 
        self.assertRaises(config.IllegalOptionName,
2207
 
                          self.registry.register_lazy, ' foo', self.__module__,
2208
 
                          'TestOptionRegistry.lazy_option')
2209
 
        self.assertRaises(config.IllegalOptionName,
2210
 
                          self.registry.register_lazy, '1,2', self.__module__,
2211
 
                          'TestOptionRegistry.lazy_option')
2212
 
 
2213
 
 
2214
 
class TestRegisteredOptions(tests.TestCase):
2215
 
    """All registered options should verify some constraints."""
2216
 
 
2217
 
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
2218
 
                 in config.option_registry.iteritems()]
2219
 
 
2220
 
    def setUp(self):
2221
 
        super(TestRegisteredOptions, self).setUp()
2222
 
        self.registry = config.option_registry
2223
 
 
2224
 
    def test_proper_name(self):
2225
 
        # An option should be registered under its own name, this can't be
2226
 
        # checked at registration time for the lazy ones.
2227
 
        self.assertEqual(self.option_name, self.option.name)
2228
 
 
2229
 
    def test_help_is_set(self):
2230
 
        option_help = self.registry.get_help(self.option_name)
2231
 
        # Come on, think about the user, he really wants to know what the
2232
 
        # option is about
2233
 
        self.assertIsNot(None, option_help)
2234
 
        self.assertNotEqual('', option_help)
2235
 
 
2236
 
 
2237
 
class TestSection(tests.TestCase):
2238
 
 
2239
 
    # FIXME: Parametrize so that all sections produced by Stores run these
2240
 
    # tests -- vila 2011-04-01
2241
 
 
2242
 
    def test_get_a_value(self):
2243
 
        a_dict = dict(foo='bar')
2244
 
        section = config.Section('myID', a_dict)
2245
 
        self.assertEqual('bar', section.get('foo'))
2246
 
 
2247
 
    def test_get_unknown_option(self):
2248
 
        a_dict = dict()
2249
 
        section = config.Section(None, a_dict)
2250
 
        self.assertEqual('out of thin air',
2251
 
                         section.get('foo', 'out of thin air'))
2252
 
 
2253
 
    def test_options_is_shared(self):
2254
 
        a_dict = dict()
2255
 
        section = config.Section(None, a_dict)
2256
 
        self.assertIs(a_dict, section.options)
2257
 
 
2258
 
 
2259
 
class TestMutableSection(tests.TestCase):
2260
 
 
2261
 
    scenarios = [('mutable',
2262
 
                  {'get_section':
2263
 
                   lambda opts: config.MutableSection('myID', opts)},),
2264
 
                 ]
2265
 
 
2266
 
    def test_set(self):
2267
 
        a_dict = dict(foo='bar')
2268
 
        section = self.get_section(a_dict)
2269
 
        section.set('foo', 'new_value')
2270
 
        self.assertEqual('new_value', section.get('foo'))
2271
 
        # The change appears in the shared section
2272
 
        self.assertEqual('new_value', a_dict.get('foo'))
2273
 
        # We keep track of the change
2274
 
        self.assertTrue('foo' in section.orig)
2275
 
        self.assertEqual('bar', section.orig.get('foo'))
2276
 
 
2277
 
    def test_set_preserve_original_once(self):
2278
 
        a_dict = dict(foo='bar')
2279
 
        section = self.get_section(a_dict)
2280
 
        section.set('foo', 'first_value')
2281
 
        section.set('foo', 'second_value')
2282
 
        # We keep track of the original value
2283
 
        self.assertTrue('foo' in section.orig)
2284
 
        self.assertEqual('bar', section.orig.get('foo'))
2285
 
 
2286
 
    def test_remove(self):
2287
 
        a_dict = dict(foo='bar')
2288
 
        section = self.get_section(a_dict)
2289
 
        section.remove('foo')
2290
 
        # We get None for unknown options via the default value
2291
 
        self.assertEqual(None, section.get('foo'))
2292
 
        # Or we just get the default value
2293
 
        self.assertEqual('unknown', section.get('foo', 'unknown'))
2294
 
        self.assertFalse('foo' in section.options)
2295
 
        # We keep track of the deletion
2296
 
        self.assertTrue('foo' in section.orig)
2297
 
        self.assertEqual('bar', section.orig.get('foo'))
2298
 
 
2299
 
    def test_remove_new_option(self):
2300
 
        a_dict = dict()
2301
 
        section = self.get_section(a_dict)
2302
 
        section.set('foo', 'bar')
2303
 
        section.remove('foo')
2304
 
        self.assertFalse('foo' in section.options)
2305
 
        # The option didn't exist initially so it we need to keep track of it
2306
 
        # with a special value
2307
 
        self.assertTrue('foo' in section.orig)
2308
 
        self.assertEqual(config._NewlyCreatedOption, section.orig['foo'])
2309
 
 
2310
 
 
2311
 
class TestCommandLineStore(tests.TestCase):
2312
 
 
2313
 
    def setUp(self):
2314
 
        super(TestCommandLineStore, self).setUp()
2315
 
        self.store = config.CommandLineStore()
2316
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
2317
 
 
2318
 
    def get_section(self):
2319
 
        """Get the unique section for the command line overrides."""
2320
 
        sections = list(self.store.get_sections())
2321
 
        self.assertLength(1, sections)
2322
 
        store, section = sections[0]
2323
 
        self.assertEqual(self.store, store)
2324
 
        return section
2325
 
 
2326
 
    def test_no_override(self):
2327
 
        self.store._from_cmdline([])
2328
 
        section = self.get_section()
2329
 
        self.assertLength(0, list(section.iter_option_names()))
2330
 
 
2331
 
    def test_simple_override(self):
2332
 
        self.store._from_cmdline(['a=b'])
2333
 
        section = self.get_section()
2334
 
        self.assertEqual('b', section.get('a'))
2335
 
 
2336
 
    def test_list_override(self):
2337
 
        opt = config.ListOption('l')
2338
 
        config.option_registry.register(opt)
2339
 
        self.store._from_cmdline(['l=1,2,3'])
2340
 
        val = self.get_section().get('l')
2341
 
        self.assertEqual('1,2,3', val)
2342
 
        # Reminder: lists should be registered as such explicitely, otherwise
2343
 
        # the conversion needs to be done afterwards.
2344
 
        self.assertEqual(['1', '2', '3'],
2345
 
                         opt.convert_from_unicode(self.store, val))
2346
 
 
2347
 
    def test_multiple_overrides(self):
2348
 
        self.store._from_cmdline(['a=b', 'x=y'])
2349
 
        section = self.get_section()
2350
 
        self.assertEqual('b', section.get('a'))
2351
 
        self.assertEqual('y', section.get('x'))
2352
 
 
2353
 
    def test_wrong_syntax(self):
2354
 
        self.assertRaises(errors.BzrCommandError,
2355
 
                          self.store._from_cmdline, ['a=b', 'c'])
2356
 
 
2357
 
 
2358
 
class TestStoreMinimalAPI(tests.TestCaseWithTransport):
2359
 
 
2360
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2361
 
                 in config.test_store_builder_registry.iteritems()] + [
2362
 
        ('cmdline', {'get_store': lambda test: config.CommandLineStore()})]
2363
 
 
2364
 
    def test_id(self):
2365
 
        store = self.get_store(self)
2366
 
        if isinstance(store, config.TransportIniFileStore):
2367
 
            raise tests.TestNotApplicable(
2368
 
                "%s is not a concrete Store implementation"
2369
 
                " so it doesn't need an id" % (store.__class__.__name__,))
2370
 
        self.assertIsNot(None, store.id)
2371
 
 
2372
 
 
2373
 
class TestStore(tests.TestCaseWithTransport):
2374
 
 
2375
 
    def assertSectionContent(self, expected, store_and_section):
2376
 
        """Assert that some options have the proper values in a section."""
2377
 
        _, section = store_and_section
2378
 
        expected_name, expected_options = expected
2379
 
        self.assertEqual(expected_name, section.id)
2380
 
        self.assertEqual(
2381
 
            expected_options,
2382
 
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2383
 
 
2384
 
 
2385
 
class TestReadonlyStore(TestStore):
2386
 
 
2387
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2388
 
                 in config.test_store_builder_registry.iteritems()]
2389
 
 
2390
 
    def test_building_delays_load(self):
2391
 
        store = self.get_store(self)
2392
 
        self.assertEqual(False, store.is_loaded())
2393
 
        store._load_from_string(b'')
2394
 
        self.assertEqual(True, store.is_loaded())
2395
 
 
2396
 
    def test_get_no_sections_for_empty(self):
2397
 
        store = self.get_store(self)
2398
 
        store._load_from_string(b'')
2399
 
        self.assertEqual([], list(store.get_sections()))
2400
 
 
2401
 
    def test_get_default_section(self):
2402
 
        store = self.get_store(self)
2403
 
        store._load_from_string(b'foo=bar')
2404
 
        sections = list(store.get_sections())
2405
 
        self.assertLength(1, sections)
2406
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2407
 
 
2408
 
    def test_get_named_section(self):
2409
 
        store = self.get_store(self)
2410
 
        store._load_from_string(b'[baz]\nfoo=bar')
2411
 
        sections = list(store.get_sections())
2412
 
        self.assertLength(1, sections)
2413
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2414
 
 
2415
 
    def test_load_from_string_fails_for_non_empty_store(self):
2416
 
        store = self.get_store(self)
2417
 
        store._load_from_string(b'foo=bar')
2418
 
        self.assertRaises(AssertionError, store._load_from_string, b'bar=baz')
2419
 
 
2420
 
 
2421
 
class TestStoreQuoting(TestStore):
2422
 
 
2423
 
    scenarios = [(key, {'get_store': builder}) for key, builder
2424
 
                 in config.test_store_builder_registry.iteritems()]
2425
 
 
2426
 
    def setUp(self):
2427
 
        super(TestStoreQuoting, self).setUp()
2428
 
        self.store = self.get_store(self)
2429
 
        # We need a loaded store but any content will do
2430
 
        self.store._load_from_string(b'')
2431
 
 
2432
 
    def assertIdempotent(self, s):
2433
 
        """Assert that quoting an unquoted string is a no-op and vice-versa.
2434
 
 
2435
 
        What matters here is that option values, as they appear in a store, can
2436
 
        be safely round-tripped out of the store and back.
2437
 
 
2438
 
        :param s: A string, quoted if required.
2439
 
        """
2440
 
        self.assertEqual(s, self.store.quote(self.store.unquote(s)))
2441
 
        self.assertEqual(s, self.store.unquote(self.store.quote(s)))
2442
 
 
2443
 
    def test_empty_string(self):
2444
 
        if isinstance(self.store, config.IniFileStore):
2445
 
            # configobj._quote doesn't handle empty values
2446
 
            self.assertRaises(AssertionError,
2447
 
                              self.assertIdempotent, '')
2448
 
        else:
2449
 
            self.assertIdempotent('')
2450
 
        # But quoted empty strings are ok
2451
 
        self.assertIdempotent('""')
2452
 
 
2453
 
    def test_embedded_spaces(self):
2454
 
        self.assertIdempotent('" a b c "')
2455
 
 
2456
 
    def test_embedded_commas(self):
2457
 
        self.assertIdempotent('" a , b c "')
2458
 
 
2459
 
    def test_simple_comma(self):
2460
 
        if isinstance(self.store, config.IniFileStore):
2461
 
            # configobj requires that lists are special-cased
2462
 
            self.assertRaises(AssertionError,
2463
 
                              self.assertIdempotent, ',')
2464
 
        else:
2465
 
            self.assertIdempotent(',')
2466
 
        # When a single comma is required, quoting is also required
2467
 
        self.assertIdempotent('","')
2468
 
 
2469
 
    def test_list(self):
2470
 
        if isinstance(self.store, config.IniFileStore):
2471
 
            # configobj requires that lists are special-cased
2472
 
            self.assertRaises(AssertionError,
2473
 
                              self.assertIdempotent, 'a,b')
2474
 
        else:
2475
 
            self.assertIdempotent('a,b')
2476
 
 
2477
 
 
2478
 
class TestDictFromStore(tests.TestCase):
2479
 
 
2480
 
    def test_unquote_not_string(self):
2481
 
        conf = config.MemoryStack(b'x=2\n[a_section]\na=1\n')
2482
 
        value = conf.get('a_section')
2483
 
        # Urgh, despite 'conf' asking for the no-name section, we get the
2484
 
        # content of another section as a dict o_O
2485
 
        self.assertEqual({'a': '1'}, value)
2486
 
        unquoted = conf.store.unquote(value)
2487
 
        # Which cannot be unquoted but shouldn't crash either (the use cases
2488
 
        # are getting the value or displaying it. In the later case, '%s' will
2489
 
        # do).
2490
 
        self.assertEqual({'a': '1'}, unquoted)
2491
 
        self.assertIn('%s' % (unquoted,), ("{u'a': u'1'}", "{'a': '1'}"))
2492
 
 
2493
 
 
2494
 
class TestIniFileStoreContent(tests.TestCaseWithTransport):
2495
 
    """Simulate loading a config store with content of various encodings.
2496
 
 
2497
 
    All files produced by bzr are in utf8 content.
2498
 
 
2499
 
    Users may modify them manually and end up with a file that can't be
2500
 
    loaded. We need to issue proper error messages in this case.
2501
 
    """
2502
 
 
2503
 
    invalid_utf8_char = b'\xff'
2504
 
 
2505
 
    def test_load_utf8(self):
2506
 
        """Ensure we can load an utf8-encoded file."""
2507
 
        t = self.get_transport()
2508
 
        # From http://pad.lv/799212
2509
 
        unicode_user = u'b\N{Euro Sign}ar'
2510
 
        unicode_content = u'user=%s' % (unicode_user,)
2511
 
        utf8_content = unicode_content.encode('utf8')
2512
 
        # Store the raw content in the config file
2513
 
        t.put_bytes('foo.conf', utf8_content)
2514
 
        store = config.TransportIniFileStore(t, 'foo.conf')
2515
 
        store.load()
2516
 
        stack = config.Stack([store.get_sections], store)
2517
 
        self.assertEqual(unicode_user, stack.get('user'))
2518
 
 
2519
 
    def test_load_non_ascii(self):
2520
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2521
 
        t = self.get_transport()
2522
 
        t.put_bytes('foo.conf', b'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2523
 
        store = config.TransportIniFileStore(t, 'foo.conf')
2524
 
        self.assertRaises(config.ConfigContentError, store.load)
2525
 
 
2526
 
    def test_load_erroneous_content(self):
2527
 
        """Ensure we display a proper error on content that can't be parsed."""
2528
 
        t = self.get_transport()
2529
 
        t.put_bytes('foo.conf', b'[open_section\n')
2530
 
        store = config.TransportIniFileStore(t, 'foo.conf')
2531
 
        self.assertRaises(config.ParseConfigError, store.load)
2532
 
 
2533
 
    def test_load_permission_denied(self):
2534
 
        """Ensure we get warned when trying to load an inaccessible file."""
2535
 
        warnings = []
2536
 
 
2537
 
        def warning(*args):
2538
 
            warnings.append(args[0] % args[1:])
2539
 
        self.overrideAttr(trace, 'warning', warning)
2540
 
 
2541
 
        t = self.get_transport()
2542
 
 
2543
 
        def get_bytes(relpath):
2544
 
            raise errors.PermissionDenied(relpath, "")
2545
 
        t.get_bytes = get_bytes
2546
 
        store = config.TransportIniFileStore(t, 'foo.conf')
2547
 
        self.assertRaises(errors.PermissionDenied, store.load)
2548
 
        self.assertEqual(
2549
 
            warnings,
2550
 
            [u'Permission denied while trying to load configuration store %s.'
2551
 
             % store.external_url()])
2552
 
 
2553
 
 
2554
 
class TestIniConfigContent(tests.TestCaseWithTransport):
2555
 
    """Simulate loading a IniBasedConfig with content of various encodings.
2556
 
 
2557
 
    All files produced by bzr are in utf8 content.
2558
 
 
2559
 
    Users may modify them manually and end up with a file that can't be
2560
 
    loaded. We need to issue proper error messages in this case.
2561
 
    """
2562
 
 
2563
 
    invalid_utf8_char = b'\xff'
2564
 
 
2565
 
    def test_load_utf8(self):
2566
 
        """Ensure we can load an utf8-encoded file."""
2567
 
        # From http://pad.lv/799212
2568
 
        unicode_user = u'b\N{Euro Sign}ar'
2569
 
        unicode_content = u'user=%s' % (unicode_user,)
2570
 
        utf8_content = unicode_content.encode('utf8')
2571
 
        # Store the raw content in the config file
2572
 
        with open('foo.conf', 'wb') as f:
2573
 
            f.write(utf8_content)
2574
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2575
 
        self.assertEqual(unicode_user, conf.get_user_option('user'))
2576
 
 
2577
 
    def test_load_badly_encoded_content(self):
2578
 
        """Ensure we display a proper error on non-ascii, non utf-8 content."""
2579
 
        with open('foo.conf', 'wb') as f:
2580
 
            f.write(b'user=foo\n#%s\n' % (self.invalid_utf8_char,))
2581
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2582
 
        self.assertRaises(config.ConfigContentError, conf._get_parser)
2583
 
 
2584
 
    def test_load_erroneous_content(self):
2585
 
        """Ensure we display a proper error on content that can't be parsed."""
2586
 
        with open('foo.conf', 'wb') as f:
2587
 
            f.write(b'[open_section\n')
2588
 
        conf = config.IniBasedConfig(file_name='foo.conf')
2589
 
        self.assertRaises(config.ParseConfigError, conf._get_parser)
2590
 
 
2591
 
 
2592
 
class TestMutableStore(TestStore):
2593
 
 
2594
 
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2595
 
                 in config.test_store_builder_registry.iteritems()]
2596
 
 
2597
 
    def setUp(self):
2598
 
        super(TestMutableStore, self).setUp()
2599
 
        self.transport = self.get_transport()
2600
 
 
2601
 
    def has_store(self, store):
2602
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
2603
 
                                               store.external_url())
2604
 
        return self.transport.has(store_basename)
2605
 
 
2606
 
    def test_save_empty_creates_no_file(self):
2607
 
        # FIXME: There should be a better way than relying on the test
2608
 
        # parametrization to identify branch.conf -- vila 2011-0526
2609
 
        if self.store_id in ('branch', 'remote_branch'):
2610
 
            raise tests.TestNotApplicable(
2611
 
                'branch.conf is *always* created when a branch is initialized')
2612
 
        store = self.get_store(self)
2613
 
        store.save()
2614
 
        self.assertEqual(False, self.has_store(store))
2615
 
 
2616
 
    def test_mutable_section_shared(self):
2617
 
        store = self.get_store(self)
2618
 
        store._load_from_string(b'foo=bar\n')
2619
 
        # FIXME: There should be a better way than relying on the test
2620
 
        # parametrization to identify branch.conf -- vila 2011-0526
2621
 
        if self.store_id in ('branch', 'remote_branch'):
2622
 
            # branch stores requires write locked branches
2623
 
            self.addCleanup(store.branch.lock_write().unlock)
2624
 
        section1 = store.get_mutable_section(None)
2625
 
        section2 = store.get_mutable_section(None)
2626
 
        # If we get different sections, different callers won't share the
2627
 
        # modification
2628
 
        self.assertIs(section1, section2)
2629
 
 
2630
 
    def test_save_emptied_succeeds(self):
2631
 
        store = self.get_store(self)
2632
 
        store._load_from_string(b'foo=bar\n')
2633
 
        # FIXME: There should be a better way than relying on the test
2634
 
        # parametrization to identify branch.conf -- vila 2011-0526
2635
 
        if self.store_id in ('branch', 'remote_branch'):
2636
 
            # branch stores requires write locked branches
2637
 
            self.addCleanup(store.branch.lock_write().unlock)
2638
 
        section = store.get_mutable_section(None)
2639
 
        section.remove('foo')
2640
 
        store.save()
2641
 
        self.assertEqual(True, self.has_store(store))
2642
 
        modified_store = self.get_store(self)
2643
 
        sections = list(modified_store.get_sections())
2644
 
        self.assertLength(0, sections)
2645
 
 
2646
 
    def test_save_with_content_succeeds(self):
2647
 
        # FIXME: There should be a better way than relying on the test
2648
 
        # parametrization to identify branch.conf -- vila 2011-0526
2649
 
        if self.store_id in ('branch', 'remote_branch'):
2650
 
            raise tests.TestNotApplicable(
2651
 
                'branch.conf is *always* created when a branch is initialized')
2652
 
        store = self.get_store(self)
2653
 
        store._load_from_string(b'foo=bar\n')
2654
 
        self.assertEqual(False, self.has_store(store))
2655
 
        store.save()
2656
 
        self.assertEqual(True, self.has_store(store))
2657
 
        modified_store = self.get_store(self)
2658
 
        sections = list(modified_store.get_sections())
2659
 
        self.assertLength(1, sections)
2660
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2661
 
 
2662
 
    def test_set_option_in_empty_store(self):
2663
 
        store = self.get_store(self)
2664
 
        # FIXME: There should be a better way than relying on the test
2665
 
        # parametrization to identify branch.conf -- vila 2011-0526
2666
 
        if self.store_id in ('branch', 'remote_branch'):
2667
 
            # branch stores requires write locked branches
2668
 
            self.addCleanup(store.branch.lock_write().unlock)
2669
 
        section = store.get_mutable_section(None)
2670
 
        section.set('foo', 'bar')
2671
 
        store.save()
2672
 
        modified_store = self.get_store(self)
2673
 
        sections = list(modified_store.get_sections())
2674
 
        self.assertLength(1, sections)
2675
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2676
 
 
2677
 
    def test_set_option_in_default_section(self):
2678
 
        store = self.get_store(self)
2679
 
        store._load_from_string(b'')
2680
 
        # FIXME: There should be a better way than relying on the test
2681
 
        # parametrization to identify branch.conf -- vila 2011-0526
2682
 
        if self.store_id in ('branch', 'remote_branch'):
2683
 
            # branch stores requires write locked branches
2684
 
            self.addCleanup(store.branch.lock_write().unlock)
2685
 
        section = store.get_mutable_section(None)
2686
 
        section.set('foo', 'bar')
2687
 
        store.save()
2688
 
        modified_store = self.get_store(self)
2689
 
        sections = list(modified_store.get_sections())
2690
 
        self.assertLength(1, sections)
2691
 
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2692
 
 
2693
 
    def test_set_option_in_named_section(self):
2694
 
        store = self.get_store(self)
2695
 
        store._load_from_string(b'')
2696
 
        # FIXME: There should be a better way than relying on the test
2697
 
        # parametrization to identify branch.conf -- vila 2011-0526
2698
 
        if self.store_id in ('branch', 'remote_branch'):
2699
 
            # branch stores requires write locked branches
2700
 
            self.addCleanup(store.branch.lock_write().unlock)
2701
 
        section = store.get_mutable_section('baz')
2702
 
        section.set('foo', 'bar')
2703
 
        store.save()
2704
 
        modified_store = self.get_store(self)
2705
 
        sections = list(modified_store.get_sections())
2706
 
        self.assertLength(1, sections)
2707
 
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2708
 
 
2709
 
    def test_load_hook(self):
2710
 
        # First, we need to ensure that the store exists
2711
 
        store = self.get_store(self)
2712
 
        # FIXME: There should be a better way than relying on the test
2713
 
        # parametrization to identify branch.conf -- vila 2011-0526
2714
 
        if self.store_id in ('branch', 'remote_branch'):
2715
 
            # branch stores requires write locked branches
2716
 
            self.addCleanup(store.branch.lock_write().unlock)
2717
 
        section = store.get_mutable_section('baz')
2718
 
        section.set('foo', 'bar')
2719
 
        store.save()
2720
 
        # Now we can try to load it
2721
 
        store = self.get_store(self)
2722
 
        calls = []
2723
 
 
2724
 
        def hook(*args):
2725
 
            calls.append(args)
2726
 
        config.ConfigHooks.install_named_hook('load', hook, None)
2727
 
        self.assertLength(0, calls)
2728
 
        store.load()
2729
 
        self.assertLength(1, calls)
2730
 
        self.assertEqual((store,), calls[0])
2731
 
 
2732
 
    def test_save_hook(self):
2733
 
        calls = []
2734
 
 
2735
 
        def hook(*args):
2736
 
            calls.append(args)
2737
 
        config.ConfigHooks.install_named_hook('save', hook, None)
2738
 
        self.assertLength(0, calls)
2739
 
        store = self.get_store(self)
2740
 
        # FIXME: There should be a better way than relying on the test
2741
 
        # parametrization to identify branch.conf -- vila 2011-0526
2742
 
        if self.store_id in ('branch', 'remote_branch'):
2743
 
            # branch stores requires write locked branches
2744
 
            self.addCleanup(store.branch.lock_write().unlock)
2745
 
        section = store.get_mutable_section('baz')
2746
 
        section.set('foo', 'bar')
2747
 
        store.save()
2748
 
        self.assertLength(1, calls)
2749
 
        self.assertEqual((store,), calls[0])
2750
 
 
2751
 
    def test_set_mark_dirty(self):
2752
 
        stack = config.MemoryStack(b'')
2753
 
        self.assertLength(0, stack.store.dirty_sections)
2754
 
        stack.set('foo', 'baz')
2755
 
        self.assertLength(1, stack.store.dirty_sections)
2756
 
        self.assertTrue(stack.store._need_saving())
2757
 
 
2758
 
    def test_remove_mark_dirty(self):
2759
 
        stack = config.MemoryStack(b'foo=bar')
2760
 
        self.assertLength(0, stack.store.dirty_sections)
2761
 
        stack.remove('foo')
2762
 
        self.assertLength(1, stack.store.dirty_sections)
2763
 
        self.assertTrue(stack.store._need_saving())
2764
 
 
2765
 
 
2766
 
class TestStoreSaveChanges(tests.TestCaseWithTransport):
2767
 
    """Tests that config changes are kept in memory and saved on-demand."""
2768
 
 
2769
 
    def setUp(self):
2770
 
        super(TestStoreSaveChanges, self).setUp()
2771
 
        self.transport = self.get_transport()
2772
 
        # Most of the tests involve two stores pointing to the same persistent
2773
 
        # storage to observe the effects of concurrent changes
2774
 
        self.st1 = config.TransportIniFileStore(self.transport, 'foo.conf')
2775
 
        self.st2 = config.TransportIniFileStore(self.transport, 'foo.conf')
2776
 
        self.warnings = []
2777
 
 
2778
 
        def warning(*args):
2779
 
            self.warnings.append(args[0] % args[1:])
2780
 
        self.overrideAttr(trace, 'warning', warning)
2781
 
 
2782
 
    def has_store(self, store):
2783
 
        store_basename = urlutils.relative_url(self.transport.external_url(),
2784
 
                                               store.external_url())
2785
 
        return self.transport.has(store_basename)
2786
 
 
2787
 
    def get_stack(self, store):
2788
 
        # Any stack will do as long as it uses the right store, just a single
2789
 
        # no-name section is enough
2790
 
        return config.Stack([store.get_sections], store)
2791
 
 
2792
 
    def test_no_changes_no_save(self):
2793
 
        s = self.get_stack(self.st1)
2794
 
        s.store.save_changes()
2795
 
        self.assertEqual(False, self.has_store(self.st1))
2796
 
 
2797
 
    def test_unrelated_concurrent_update(self):
2798
 
        s1 = self.get_stack(self.st1)
2799
 
        s2 = self.get_stack(self.st2)
2800
 
        s1.set('foo', 'bar')
2801
 
        s2.set('baz', 'quux')
2802
 
        s1.store.save()
2803
 
        # Changes don't propagate magically
2804
 
        self.assertEqual(None, s1.get('baz'))
2805
 
        s2.store.save_changes()
2806
 
        self.assertEqual('quux', s2.get('baz'))
2807
 
        # Changes are acquired when saving
2808
 
        self.assertEqual('bar', s2.get('foo'))
2809
 
        # Since there is no overlap, no warnings are emitted
2810
 
        self.assertLength(0, self.warnings)
2811
 
 
2812
 
    def test_concurrent_update_modified(self):
2813
 
        s1 = self.get_stack(self.st1)
2814
 
        s2 = self.get_stack(self.st2)
2815
 
        s1.set('foo', 'bar')
2816
 
        s2.set('foo', 'baz')
2817
 
        s1.store.save()
2818
 
        # Last speaker wins
2819
 
        s2.store.save_changes()
2820
 
        self.assertEqual('baz', s2.get('foo'))
2821
 
        # But the user get a warning
2822
 
        self.assertLength(1, self.warnings)
2823
 
        warning = self.warnings[0]
2824
 
        self.assertStartsWith(warning, 'Option foo in section None')
2825
 
        self.assertEndsWith(warning, 'was changed from <CREATED> to bar.'
2826
 
                            ' The baz value will be saved.')
2827
 
 
2828
 
    def test_concurrent_deletion(self):
2829
 
        self.st1._load_from_string(b'foo=bar')
2830
 
        self.st1.save()
2831
 
        s1 = self.get_stack(self.st1)
2832
 
        s2 = self.get_stack(self.st2)
2833
 
        s1.remove('foo')
2834
 
        s2.remove('foo')
2835
 
        s1.store.save_changes()
2836
 
        # No warning yet
2837
 
        self.assertLength(0, self.warnings)
2838
 
        s2.store.save_changes()
2839
 
        # Now we get one
2840
 
        self.assertLength(1, self.warnings)
2841
 
        warning = self.warnings[0]
2842
 
        self.assertStartsWith(warning, 'Option foo in section None')
2843
 
        self.assertEndsWith(warning, 'was changed from bar to <CREATED>.'
2844
 
                            ' The <DELETED> value will be saved.')
2845
 
 
2846
 
 
2847
 
class TestQuotingIniFileStore(tests.TestCaseWithTransport):
2848
 
 
2849
 
    def get_store(self):
2850
 
        return config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2851
 
 
2852
 
    def test_get_quoted_string(self):
2853
 
        store = self.get_store()
2854
 
        store._load_from_string(b'foo= " abc "')
2855
 
        stack = config.Stack([store.get_sections])
2856
 
        self.assertEqual(' abc ', stack.get('foo'))
2857
 
 
2858
 
    def test_set_quoted_string(self):
2859
 
        store = self.get_store()
2860
 
        stack = config.Stack([store.get_sections], store)
2861
 
        stack.set('foo', ' a b c ')
2862
 
        store.save()
2863
 
        self.assertFileEqual(b'foo = " a b c "' +
2864
 
                             os.linesep.encode('ascii'), 'foo.conf')
2865
 
 
2866
 
 
2867
 
class TestTransportIniFileStore(TestStore):
2868
 
 
2869
 
    def test_loading_unknown_file_fails(self):
2870
 
        store = config.TransportIniFileStore(self.get_transport(),
2871
 
                                             'I-do-not-exist')
2872
 
        self.assertRaises(errors.NoSuchFile, store.load)
2873
 
 
2874
 
    def test_invalid_content(self):
2875
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2876
 
        self.assertEqual(False, store.is_loaded())
2877
 
        exc = self.assertRaises(
2878
 
            config.ParseConfigError, store._load_from_string,
2879
 
            b'this is invalid !')
2880
 
        self.assertEndsWith(exc.filename, 'foo.conf')
2881
 
        # And the load failed
2882
 
        self.assertEqual(False, store.is_loaded())
2883
 
 
2884
 
    def test_get_embedded_sections(self):
2885
 
        # A more complicated example (which also shows that section names and
2886
 
        # option names share the same name space...)
2887
 
        # FIXME: This should be fixed by forbidding dicts as values ?
2888
 
        # -- vila 2011-04-05
2889
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
2890
 
        store._load_from_string(b'''
2891
 
foo=bar
2892
 
l=1,2
2893
 
[DEFAULT]
2894
 
foo_in_DEFAULT=foo_DEFAULT
2895
 
[bar]
2896
 
foo_in_bar=barbar
2897
 
[baz]
2898
 
foo_in_baz=barbaz
2899
 
[[qux]]
2900
 
foo_in_qux=quux
2901
 
''')
2902
 
        sections = list(store.get_sections())
2903
 
        self.assertLength(4, sections)
2904
 
        # The default section has no name.
2905
 
        # List values are provided as strings and need to be explicitly
2906
 
        # converted by specifying from_unicode=list_from_store at option
2907
 
        # registration
2908
 
        self.assertSectionContent((None, {'foo': 'bar', 'l': u'1,2'}),
2909
 
                                  sections[0])
2910
 
        self.assertSectionContent(
2911
 
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2912
 
        self.assertSectionContent(
2913
 
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
2914
 
        # sub sections are provided as embedded dicts.
2915
 
        self.assertSectionContent(
2916
 
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2917
 
            sections[3])
2918
 
 
2919
 
 
2920
 
class TestLockableIniFileStore(TestStore):
2921
 
 
2922
 
    def test_create_store_in_created_dir(self):
2923
 
        self.assertPathDoesNotExist('dir')
2924
 
        t = self.get_transport('dir/subdir')
2925
 
        store = config.LockableIniFileStore(t, 'foo.conf')
2926
 
        store.get_mutable_section(None).set('foo', 'bar')
2927
 
        store.save()
2928
 
        self.assertPathExists('dir/subdir')
2929
 
 
2930
 
 
2931
 
class TestConcurrentStoreUpdates(TestStore):
2932
 
    """Test that Stores properly handle conccurent updates.
2933
 
 
2934
 
    New Store implementation may fail some of these tests but until such
2935
 
    implementations exist it's hard to properly filter them from the scenarios
2936
 
    applied here. If you encounter such a case, contact the bzr devs.
2937
 
    """
2938
 
 
2939
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
2940
 
                 in config.test_stack_builder_registry.iteritems()]
2941
 
 
2942
 
    def setUp(self):
2943
 
        super(TestConcurrentStoreUpdates, self).setUp()
2944
 
        self.stack = self.get_stack(self)
2945
 
        if not isinstance(self.stack, config._CompatibleStack):
2946
 
            raise tests.TestNotApplicable(
2947
 
                '%s is not meant to be compatible with the old config design'
2948
 
                % (self.stack,))
2949
 
        self.stack.set('one', '1')
2950
 
        self.stack.set('two', '2')
2951
 
        # Flush the store
2952
 
        self.stack.store.save()
2953
 
 
2954
 
    def test_simple_read_access(self):
2955
 
        self.assertEqual('1', self.stack.get('one'))
2956
 
 
2957
 
    def test_simple_write_access(self):
2958
 
        self.stack.set('one', 'one')
2959
 
        self.assertEqual('one', self.stack.get('one'))
2960
 
 
2961
 
    def test_listen_to_the_last_speaker(self):
2962
 
        c1 = self.stack
2963
 
        c2 = self.get_stack(self)
2964
 
        c1.set('one', 'ONE')
2965
 
        c2.set('two', 'TWO')
2966
 
        self.assertEqual('ONE', c1.get('one'))
2967
 
        self.assertEqual('TWO', c2.get('two'))
2968
 
        # The second update respect the first one
2969
 
        self.assertEqual('ONE', c2.get('one'))
2970
 
 
2971
 
    def test_last_speaker_wins(self):
2972
 
        # If the same config is not shared, the same variable modified twice
2973
 
        # can only see a single result.
2974
 
        c1 = self.stack
2975
 
        c2 = self.get_stack(self)
2976
 
        c1.set('one', 'c1')
2977
 
        c2.set('one', 'c2')
2978
 
        self.assertEqual('c2', c2.get('one'))
2979
 
        # The first modification is still available until another refresh
2980
 
        # occur
2981
 
        self.assertEqual('c1', c1.get('one'))
2982
 
        c1.set('two', 'done')
2983
 
        self.assertEqual('c2', c1.get('one'))
2984
 
 
2985
 
    def test_writes_are_serialized(self):
2986
 
        c1 = self.stack
2987
 
        c2 = self.get_stack(self)
2988
 
 
2989
 
        # We spawn a thread that will pause *during* the config saving.
2990
 
        before_writing = threading.Event()
2991
 
        after_writing = threading.Event()
2992
 
        writing_done = threading.Event()
2993
 
        c1_save_without_locking_orig = c1.store.save_without_locking
2994
 
 
2995
 
        def c1_save_without_locking():
2996
 
            before_writing.set()
2997
 
            c1_save_without_locking_orig()
2998
 
            # The lock is held. We wait for the main thread to decide when to
2999
 
            # continue
3000
 
            after_writing.wait()
3001
 
        c1.store.save_without_locking = c1_save_without_locking
3002
 
 
3003
 
        def c1_set():
3004
 
            c1.set('one', 'c1')
3005
 
            writing_done.set()
3006
 
        t1 = threading.Thread(target=c1_set)
3007
 
        # Collect the thread after the test
3008
 
        self.addCleanup(t1.join)
3009
 
        # Be ready to unblock the thread if the test goes wrong
3010
 
        self.addCleanup(after_writing.set)
3011
 
        t1.start()
3012
 
        before_writing.wait()
3013
 
        self.assertRaises(errors.LockContention,
3014
 
                          c2.set, 'one', 'c2')
3015
 
        self.assertEqual('c1', c1.get('one'))
3016
 
        # Let the lock be released
3017
 
        after_writing.set()
3018
 
        writing_done.wait()
3019
 
        c2.set('one', 'c2')
3020
 
        self.assertEqual('c2', c2.get('one'))
3021
 
 
3022
 
    def test_read_while_writing(self):
3023
 
        c1 = self.stack
3024
 
        # We spawn a thread that will pause *during* the write
3025
 
        ready_to_write = threading.Event()
3026
 
        do_writing = threading.Event()
3027
 
        writing_done = threading.Event()
3028
 
        # We override the _save implementation so we know the store is locked
3029
 
        c1_save_without_locking_orig = c1.store.save_without_locking
3030
 
 
3031
 
        def c1_save_without_locking():
3032
 
            ready_to_write.set()
3033
 
            # The lock is held. We wait for the main thread to decide when to
3034
 
            # continue
3035
 
            do_writing.wait()
3036
 
            c1_save_without_locking_orig()
3037
 
            writing_done.set()
3038
 
        c1.store.save_without_locking = c1_save_without_locking
3039
 
 
3040
 
        def c1_set():
3041
 
            c1.set('one', 'c1')
3042
 
        t1 = threading.Thread(target=c1_set)
3043
 
        # Collect the thread after the test
3044
 
        self.addCleanup(t1.join)
3045
 
        # Be ready to unblock the thread if the test goes wrong
3046
 
        self.addCleanup(do_writing.set)
3047
 
        t1.start()
3048
 
        # Ensure the thread is ready to write
3049
 
        ready_to_write.wait()
3050
 
        self.assertEqual('c1', c1.get('one'))
3051
 
        # If we read during the write, we get the old value
3052
 
        c2 = self.get_stack(self)
3053
 
        self.assertEqual('1', c2.get('one'))
3054
 
        # Let the writing occur and ensure it occurred
3055
 
        do_writing.set()
3056
 
        writing_done.wait()
3057
 
        # Now we get the updated value
3058
 
        c3 = self.get_stack(self)
3059
 
        self.assertEqual('c1', c3.get('one'))
3060
 
 
3061
 
    # FIXME: It may be worth looking into removing the lock dir when it's not
3062
 
    # needed anymore and look at possible fallouts for concurrent lockers. This
3063
 
    # will matter if/when we use config files outside of breezy directories
3064
 
    # (.config/breezy or .bzr) -- vila 20110-04-111
3065
 
 
3066
 
 
3067
 
class TestSectionMatcher(TestStore):
3068
 
 
3069
 
    scenarios = [('location', {'matcher': config.LocationMatcher}),
3070
 
                 ('id', {'matcher': config.NameMatcher}), ]
3071
 
 
3072
 
    def setUp(self):
3073
 
        super(TestSectionMatcher, self).setUp()
3074
 
        # Any simple store is good enough
3075
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3076
 
 
3077
 
    def test_no_matches_for_empty_stores(self):
3078
 
        store = self.get_store(self)
3079
 
        store._load_from_string(b'')
3080
 
        matcher = self.matcher(store, '/bar')
3081
 
        self.assertEqual([], list(matcher.get_sections()))
3082
 
 
3083
 
    def test_build_doesnt_load_store(self):
3084
 
        store = self.get_store(self)
3085
 
        self.matcher(store, '/bar')
3086
 
        self.assertFalse(store.is_loaded())
3087
 
 
3088
 
 
3089
 
class TestLocationSection(tests.TestCase):
3090
 
 
3091
 
    def get_section(self, options, extra_path):
3092
 
        section = config.Section('foo', options)
3093
 
        return config.LocationSection(section, extra_path)
3094
 
 
3095
 
    def test_simple_option(self):
3096
 
        section = self.get_section({'foo': 'bar'}, '')
3097
 
        self.assertEqual('bar', section.get('foo'))
3098
 
 
3099
 
    def test_option_with_extra_path(self):
3100
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
3101
 
                                   'baz')
3102
 
        self.assertEqual('bar/baz', section.get('foo'))
3103
 
 
3104
 
    def test_invalid_policy(self):
3105
 
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
3106
 
                                   'baz')
3107
 
        # invalid policies are ignored
3108
 
        self.assertEqual('bar', section.get('foo'))
3109
 
 
3110
 
 
3111
 
class TestLocationMatcher(TestStore):
3112
 
 
3113
 
    def setUp(self):
3114
 
        super(TestLocationMatcher, self).setUp()
3115
 
        # Any simple store is good enough
3116
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3117
 
 
3118
 
    def test_unrelated_section_excluded(self):
3119
 
        store = self.get_store(self)
3120
 
        store._load_from_string(b'''
3121
 
[/foo]
3122
 
section=/foo
3123
 
[/foo/baz]
3124
 
section=/foo/baz
3125
 
[/foo/bar]
3126
 
section=/foo/bar
3127
 
[/foo/bar/baz]
3128
 
section=/foo/bar/baz
3129
 
[/quux/quux]
3130
 
section=/quux/quux
3131
 
''')
3132
 
        self.assertEqual(['/foo', '/foo/baz', '/foo/bar', '/foo/bar/baz',
3133
 
                          '/quux/quux'],
3134
 
                         [section.id for _, section in store.get_sections()])
3135
 
        matcher = config.LocationMatcher(store, '/foo/bar/quux')
3136
 
        sections = [section for _, section in matcher.get_sections()]
3137
 
        self.assertEqual(['/foo/bar', '/foo'],
3138
 
                         [section.id for section in sections])
3139
 
        self.assertEqual(['quux', 'bar/quux'],
3140
 
                         [section.extra_path for section in sections])
3141
 
 
3142
 
    def test_more_specific_sections_first(self):
3143
 
        store = self.get_store(self)
3144
 
        store._load_from_string(b'''
3145
 
[/foo]
3146
 
section=/foo
3147
 
[/foo/bar]
3148
 
section=/foo/bar
3149
 
''')
3150
 
        self.assertEqual(['/foo', '/foo/bar'],
3151
 
                         [section.id for _, section in store.get_sections()])
3152
 
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
3153
 
        sections = [section for _, section in matcher.get_sections()]
3154
 
        self.assertEqual(['/foo/bar', '/foo'],
3155
 
                         [section.id for section in sections])
3156
 
        self.assertEqual(['baz', 'bar/baz'],
3157
 
                         [section.extra_path for section in sections])
3158
 
 
3159
 
    def test_appendpath_in_no_name_section(self):
3160
 
        # It's a bit weird to allow appendpath in a no-name section, but
3161
 
        # someone may found a use for it
3162
 
        store = self.get_store(self)
3163
 
        store._load_from_string(b'''
3164
 
foo=bar
3165
 
foo:policy = appendpath
3166
 
''')
3167
 
        matcher = config.LocationMatcher(store, 'dir/subdir')
3168
 
        sections = list(matcher.get_sections())
3169
 
        self.assertLength(1, sections)
3170
 
        self.assertEqual('bar/dir/subdir', sections[0][1].get('foo'))
3171
 
 
3172
 
    def test_file_urls_are_normalized(self):
3173
 
        store = self.get_store(self)
3174
 
        if sys.platform == 'win32':
3175
 
            expected_url = 'file:///C:/dir/subdir'
3176
 
            expected_location = 'C:/dir/subdir'
3177
 
        else:
3178
 
            expected_url = 'file:///dir/subdir'
3179
 
            expected_location = '/dir/subdir'
3180
 
        matcher = config.LocationMatcher(store, expected_url)
3181
 
        self.assertEqual(expected_location, matcher.location)
3182
 
 
3183
 
    def test_branch_name_colo(self):
3184
 
        store = self.get_store(self)
3185
 
        store._load_from_string(dedent("""\
3186
 
            [/]
3187
 
            push_location=my{branchname}
3188
 
        """).encode('ascii'))
3189
 
        matcher = config.LocationMatcher(store, 'file:///,branch=example%3c')
3190
 
        self.assertEqual('example<', matcher.branch_name)
3191
 
        ((_, section),) = matcher.get_sections()
3192
 
        self.assertEqual('example<', section.locals['branchname'])
3193
 
 
3194
 
    def test_branch_name_basename(self):
3195
 
        store = self.get_store(self)
3196
 
        store._load_from_string(dedent("""\
3197
 
            [/]
3198
 
            push_location=my{branchname}
3199
 
        """).encode('ascii'))
3200
 
        matcher = config.LocationMatcher(store, 'file:///parent/example%3c')
3201
 
        self.assertEqual('example<', matcher.branch_name)
3202
 
        ((_, section),) = matcher.get_sections()
3203
 
        self.assertEqual('example<', section.locals['branchname'])
3204
 
 
3205
 
 
3206
 
class TestStartingPathMatcher(TestStore):
3207
 
 
3208
 
    def setUp(self):
3209
 
        super(TestStartingPathMatcher, self).setUp()
3210
 
        # Any simple store is good enough
3211
 
        self.store = config.IniFileStore()
3212
 
 
3213
 
    def assertSectionIDs(self, expected, location, content):
3214
 
        self.store._load_from_string(content)
3215
 
        matcher = config.StartingPathMatcher(self.store, location)
3216
 
        sections = list(matcher.get_sections())
3217
 
        self.assertLength(len(expected), sections)
3218
 
        self.assertEqual(expected, [section.id for _, section in sections])
3219
 
        return sections
3220
 
 
3221
 
    def test_empty(self):
3222
 
        self.assertSectionIDs([], self.get_url(), b'')
3223
 
 
3224
 
    def test_url_vs_local_paths(self):
3225
 
        # The matcher location is an url and the section names are local paths
3226
 
        self.assertSectionIDs(['/foo/bar', '/foo'],
3227
 
                              'file:///foo/bar/baz', b'''\
3228
 
[/foo]
3229
 
[/foo/bar]
3230
 
''')
3231
 
 
3232
 
    def test_local_path_vs_url(self):
3233
 
        # The matcher location is a local path and the section names are urls
3234
 
        self.assertSectionIDs(['file:///foo/bar', 'file:///foo'],
3235
 
                              '/foo/bar/baz', b'''\
3236
 
[file:///foo]
3237
 
[file:///foo/bar]
3238
 
''')
3239
 
 
3240
 
    def test_no_name_section_included_when_present(self):
3241
 
        # Note that other tests will cover the case where the no-name section
3242
 
        # is empty and as such, not included.
3243
 
        sections = self.assertSectionIDs(['/foo/bar', '/foo', None],
3244
 
                                         '/foo/bar/baz', b'''\
3245
 
option = defined so the no-name section exists
3246
 
[/foo]
3247
 
[/foo/bar]
3248
 
''')
3249
 
        self.assertEqual(['baz', 'bar/baz', '/foo/bar/baz'],
3250
 
                         [s.locals['relpath'] for _, s in sections])
3251
 
 
3252
 
    def test_order_reversed(self):
3253
 
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', b'''\
3254
 
[/foo]
3255
 
[/foo/bar]
3256
 
''')
3257
 
 
3258
 
    def test_unrelated_section_excluded(self):
3259
 
        self.assertSectionIDs(['/foo/bar', '/foo'], '/foo/bar/baz', b'''\
3260
 
[/foo]
3261
 
[/foo/qux]
3262
 
[/foo/bar]
3263
 
''')
3264
 
 
3265
 
    def test_glob_included(self):
3266
 
        sections = self.assertSectionIDs(['/foo/*/baz', '/foo/b*', '/foo'],
3267
 
                                         '/foo/bar/baz', b'''\
3268
 
[/foo]
3269
 
[/foo/qux]
3270
 
[/foo/b*]
3271
 
[/foo/*/baz]
3272
 
''')
3273
 
        # Note that 'baz' as a relpath for /foo/b* is not fully correct, but
3274
 
        # nothing really is... as far using {relpath} to append it to something
3275
 
        # else, this seems good enough though.
3276
 
        self.assertEqual(['', 'baz', 'bar/baz'],
3277
 
                         [s.locals['relpath'] for _, s in sections])
3278
 
 
3279
 
    def test_respect_order(self):
3280
 
        self.assertSectionIDs(['/foo', '/foo/b*', '/foo/*/baz'],
3281
 
                              '/foo/bar/baz', b'''\
3282
 
[/foo/*/baz]
3283
 
[/foo/qux]
3284
 
[/foo/b*]
3285
 
[/foo]
3286
 
''')
3287
 
 
3288
 
 
3289
 
class TestNameMatcher(TestStore):
3290
 
 
3291
 
    def setUp(self):
3292
 
        super(TestNameMatcher, self).setUp()
3293
 
        self.matcher = config.NameMatcher
3294
 
        # Any simple store is good enough
3295
 
        self.get_store = config.test_store_builder_registry.get('configobj')
3296
 
 
3297
 
    def get_matching_sections(self, name):
3298
 
        store = self.get_store(self)
3299
 
        store._load_from_string(b'''
3300
 
[foo]
3301
 
option=foo
3302
 
[foo/baz]
3303
 
option=foo/baz
3304
 
[bar]
3305
 
option=bar
3306
 
''')
3307
 
        matcher = self.matcher(store, name)
3308
 
        return list(matcher.get_sections())
3309
 
 
3310
 
    def test_matching(self):
3311
 
        sections = self.get_matching_sections('foo')
3312
 
        self.assertLength(1, sections)
3313
 
        self.assertSectionContent(('foo', {'option': 'foo'}), sections[0])
3314
 
 
3315
 
    def test_not_matching(self):
3316
 
        sections = self.get_matching_sections('baz')
3317
 
        self.assertLength(0, sections)
3318
 
 
3319
 
 
3320
 
class TestBaseStackGet(tests.TestCase):
3321
 
 
3322
 
    def setUp(self):
3323
 
        super(TestBaseStackGet, self).setUp()
3324
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3325
 
 
3326
 
    def test_get_first_definition(self):
3327
 
        store1 = config.IniFileStore()
3328
 
        store1._load_from_string(b'foo=bar')
3329
 
        store2 = config.IniFileStore()
3330
 
        store2._load_from_string(b'foo=baz')
3331
 
        conf = config.Stack([store1.get_sections, store2.get_sections])
3332
 
        self.assertEqual('bar', conf.get('foo'))
3333
 
 
3334
 
    def test_get_with_registered_default_value(self):
3335
 
        config.option_registry.register(config.Option('foo', default='bar'))
3336
 
        conf_stack = config.Stack([])
3337
 
        self.assertEqual('bar', conf_stack.get('foo'))
3338
 
 
3339
 
    def test_get_without_registered_default_value(self):
3340
 
        config.option_registry.register(config.Option('foo'))
3341
 
        conf_stack = config.Stack([])
3342
 
        self.assertEqual(None, conf_stack.get('foo'))
3343
 
 
3344
 
    def test_get_without_default_value_for_not_registered(self):
3345
 
        conf_stack = config.Stack([])
3346
 
        self.assertEqual(None, conf_stack.get('foo'))
3347
 
 
3348
 
    def test_get_for_empty_section_callable(self):
3349
 
        conf_stack = config.Stack([lambda: []])
3350
 
        self.assertEqual(None, conf_stack.get('foo'))
3351
 
 
3352
 
    def test_get_for_broken_callable(self):
3353
 
        # Trying to use and invalid callable raises an exception on first use
3354
 
        conf_stack = config.Stack([object])
3355
 
        self.assertRaises(TypeError, conf_stack.get, 'foo')
3356
 
 
3357
 
 
3358
 
class TestStackWithSimpleStore(tests.TestCase):
3359
 
 
3360
 
    def setUp(self):
3361
 
        super(TestStackWithSimpleStore, self).setUp()
3362
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3363
 
        self.registry = config.option_registry
3364
 
 
3365
 
    def get_conf(self, content=None):
3366
 
        return config.MemoryStack(content)
3367
 
 
3368
 
    def test_override_value_from_env(self):
3369
 
        self.overrideEnv('FOO', None)
3370
 
        self.registry.register(
3371
 
            config.Option('foo', default='bar', override_from_env=['FOO']))
3372
 
        self.overrideEnv('FOO', 'quux')
3373
 
        # Env variable provides a default taking over the option one
3374
 
        conf = self.get_conf(b'foo=store')
3375
 
        self.assertEqual('quux', conf.get('foo'))
3376
 
 
3377
 
    def test_first_override_value_from_env_wins(self):
3378
 
        self.overrideEnv('NO_VALUE', None)
3379
 
        self.overrideEnv('FOO', None)
3380
 
        self.overrideEnv('BAZ', None)
3381
 
        self.registry.register(
3382
 
            config.Option('foo', default='bar',
3383
 
                          override_from_env=['NO_VALUE', 'FOO', 'BAZ']))
3384
 
        self.overrideEnv('FOO', 'foo')
3385
 
        self.overrideEnv('BAZ', 'baz')
3386
 
        # The first env var set wins
3387
 
        conf = self.get_conf(b'foo=store')
3388
 
        self.assertEqual('foo', conf.get('foo'))
3389
 
 
3390
 
 
3391
 
class TestMemoryStack(tests.TestCase):
3392
 
 
3393
 
    def test_get(self):
3394
 
        conf = config.MemoryStack(b'foo=bar')
3395
 
        self.assertEqual('bar', conf.get('foo'))
3396
 
 
3397
 
    def test_set(self):
3398
 
        conf = config.MemoryStack(b'foo=bar')
3399
 
        conf.set('foo', 'baz')
3400
 
        self.assertEqual('baz', conf.get('foo'))
3401
 
 
3402
 
    def test_no_content(self):
3403
 
        conf = config.MemoryStack()
3404
 
        # No content means no loading
3405
 
        self.assertFalse(conf.store.is_loaded())
3406
 
        self.assertRaises(NotImplementedError, conf.get, 'foo')
3407
 
        # But a content can still be provided
3408
 
        conf.store._load_from_string(b'foo=bar')
3409
 
        self.assertEqual('bar', conf.get('foo'))
3410
 
 
3411
 
 
3412
 
class TestStackIterSections(tests.TestCase):
3413
 
 
3414
 
    def test_empty_stack(self):
3415
 
        conf = config.Stack([])
3416
 
        sections = list(conf.iter_sections())
3417
 
        self.assertLength(0, sections)
3418
 
 
3419
 
    def test_empty_store(self):
3420
 
        store = config.IniFileStore()
3421
 
        store._load_from_string(b'')
3422
 
        conf = config.Stack([store.get_sections])
3423
 
        sections = list(conf.iter_sections())
3424
 
        self.assertLength(0, sections)
3425
 
 
3426
 
    def test_simple_store(self):
3427
 
        store = config.IniFileStore()
3428
 
        store._load_from_string(b'foo=bar')
3429
 
        conf = config.Stack([store.get_sections])
3430
 
        tuples = list(conf.iter_sections())
3431
 
        self.assertLength(1, tuples)
3432
 
        (found_store, found_section) = tuples[0]
3433
 
        self.assertIs(store, found_store)
3434
 
 
3435
 
    def test_two_stores(self):
3436
 
        store1 = config.IniFileStore()
3437
 
        store1._load_from_string(b'foo=bar')
3438
 
        store2 = config.IniFileStore()
3439
 
        store2._load_from_string(b'bar=qux')
3440
 
        conf = config.Stack([store1.get_sections, store2.get_sections])
3441
 
        tuples = list(conf.iter_sections())
3442
 
        self.assertLength(2, tuples)
3443
 
        self.assertIs(store1, tuples[0][0])
3444
 
        self.assertIs(store2, tuples[1][0])
3445
 
 
3446
 
 
3447
 
class TestStackWithTransport(tests.TestCaseWithTransport):
3448
 
 
3449
 
    scenarios = [(key, {'get_stack': builder}) for key, builder
3450
 
                 in config.test_stack_builder_registry.iteritems()]
3451
 
 
3452
 
 
3453
 
class TestConcreteStacks(TestStackWithTransport):
3454
 
 
3455
 
    def test_build_stack(self):
3456
 
        # Just a smoke test to help debug builders
3457
 
        self.get_stack(self)
3458
 
 
3459
 
 
3460
 
class TestStackGet(TestStackWithTransport):
3461
 
 
3462
 
    def setUp(self):
3463
 
        super(TestStackGet, self).setUp()
3464
 
        self.conf = self.get_stack(self)
3465
 
 
3466
 
    def test_get_for_empty_stack(self):
3467
 
        self.assertEqual(None, self.conf.get('foo'))
3468
 
 
3469
 
    def test_get_hook(self):
3470
 
        self.conf.set('foo', 'bar')
3471
 
        calls = []
3472
 
 
3473
 
        def hook(*args):
3474
 
            calls.append(args)
3475
 
        config.ConfigHooks.install_named_hook('get', hook, None)
3476
 
        self.assertLength(0, calls)
3477
 
        value = self.conf.get('foo')
3478
 
        self.assertEqual('bar', value)
3479
 
        self.assertLength(1, calls)
3480
 
        self.assertEqual((self.conf, 'foo', 'bar'), calls[0])
3481
 
 
3482
 
 
3483
 
class TestStackGetWithConverter(tests.TestCase):
3484
 
 
3485
 
    def setUp(self):
3486
 
        super(TestStackGetWithConverter, self).setUp()
3487
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3488
 
        self.registry = config.option_registry
3489
 
 
3490
 
    def get_conf(self, content=None):
3491
 
        return config.MemoryStack(content)
3492
 
 
3493
 
    def register_bool_option(self, name, default=None, default_from_env=None):
3494
 
        b = config.Option(name, help='A boolean.',
3495
 
                          default=default, default_from_env=default_from_env,
3496
 
                          from_unicode=config.bool_from_store)
3497
 
        self.registry.register(b)
3498
 
 
3499
 
    def test_get_default_bool_None(self):
3500
 
        self.register_bool_option('foo')
3501
 
        conf = self.get_conf(b'')
3502
 
        self.assertEqual(None, conf.get('foo'))
3503
 
 
3504
 
    def test_get_default_bool_True(self):
3505
 
        self.register_bool_option('foo', u'True')
3506
 
        conf = self.get_conf(b'')
3507
 
        self.assertEqual(True, conf.get('foo'))
3508
 
 
3509
 
    def test_get_default_bool_False(self):
3510
 
        self.register_bool_option('foo', False)
3511
 
        conf = self.get_conf(b'')
3512
 
        self.assertEqual(False, conf.get('foo'))
3513
 
 
3514
 
    def test_get_default_bool_False_as_string(self):
3515
 
        self.register_bool_option('foo', u'False')
3516
 
        conf = self.get_conf(b'')
3517
 
        self.assertEqual(False, conf.get('foo'))
3518
 
 
3519
 
    def test_get_default_bool_from_env_converted(self):
3520
 
        self.register_bool_option('foo', u'True', default_from_env=['FOO'])
3521
 
        self.overrideEnv('FOO', 'False')
3522
 
        conf = self.get_conf(b'')
3523
 
        self.assertEqual(False, conf.get('foo'))
3524
 
 
3525
 
    def test_get_default_bool_when_conversion_fails(self):
3526
 
        self.register_bool_option('foo', default='True')
3527
 
        conf = self.get_conf(b'foo=invalid boolean')
3528
 
        self.assertEqual(True, conf.get('foo'))
3529
 
 
3530
 
    def register_integer_option(self, name,
3531
 
                                default=None, default_from_env=None):
3532
 
        i = config.Option(name, help='An integer.',
3533
 
                          default=default, default_from_env=default_from_env,
3534
 
                          from_unicode=config.int_from_store)
3535
 
        self.registry.register(i)
3536
 
 
3537
 
    def test_get_default_integer_None(self):
3538
 
        self.register_integer_option('foo')
3539
 
        conf = self.get_conf(b'')
3540
 
        self.assertEqual(None, conf.get('foo'))
3541
 
 
3542
 
    def test_get_default_integer(self):
3543
 
        self.register_integer_option('foo', 42)
3544
 
        conf = self.get_conf(b'')
3545
 
        self.assertEqual(42, conf.get('foo'))
3546
 
 
3547
 
    def test_get_default_integer_as_string(self):
3548
 
        self.register_integer_option('foo', u'42')
3549
 
        conf = self.get_conf(b'')
3550
 
        self.assertEqual(42, conf.get('foo'))
3551
 
 
3552
 
    def test_get_default_integer_from_env(self):
3553
 
        self.register_integer_option('foo', default_from_env=['FOO'])
3554
 
        self.overrideEnv('FOO', '18')
3555
 
        conf = self.get_conf(b'')
3556
 
        self.assertEqual(18, conf.get('foo'))
3557
 
 
3558
 
    def test_get_default_integer_when_conversion_fails(self):
3559
 
        self.register_integer_option('foo', default='12')
3560
 
        conf = self.get_conf(b'foo=invalid integer')
3561
 
        self.assertEqual(12, conf.get('foo'))
3562
 
 
3563
 
    def register_list_option(self, name, default=None, default_from_env=None):
3564
 
        l = config.ListOption(name, help='A list.', default=default,
3565
 
                              default_from_env=default_from_env)
3566
 
        self.registry.register(l)
3567
 
 
3568
 
    def test_get_default_list_None(self):
3569
 
        self.register_list_option('foo')
3570
 
        conf = self.get_conf(b'')
3571
 
        self.assertEqual(None, conf.get('foo'))
3572
 
 
3573
 
    def test_get_default_list_empty(self):
3574
 
        self.register_list_option('foo', '')
3575
 
        conf = self.get_conf(b'')
3576
 
        self.assertEqual([], conf.get('foo'))
3577
 
 
3578
 
    def test_get_default_list_from_env(self):
3579
 
        self.register_list_option('foo', default_from_env=['FOO'])
3580
 
        self.overrideEnv('FOO', '')
3581
 
        conf = self.get_conf(b'')
3582
 
        self.assertEqual([], conf.get('foo'))
3583
 
 
3584
 
    def test_get_with_list_converter_no_item(self):
3585
 
        self.register_list_option('foo', None)
3586
 
        conf = self.get_conf(b'foo=,')
3587
 
        self.assertEqual([], conf.get('foo'))
3588
 
 
3589
 
    def test_get_with_list_converter_many_items(self):
3590
 
        self.register_list_option('foo', None)
3591
 
        conf = self.get_conf(b'foo=m,o,r,e')
3592
 
        self.assertEqual(['m', 'o', 'r', 'e'], conf.get('foo'))
3593
 
 
3594
 
    def test_get_with_list_converter_embedded_spaces_many_items(self):
3595
 
        self.register_list_option('foo', None)
3596
 
        conf = self.get_conf(b'foo=" bar", "baz "')
3597
 
        self.assertEqual([' bar', 'baz '], conf.get('foo'))
3598
 
 
3599
 
    def test_get_with_list_converter_stripped_spaces_many_items(self):
3600
 
        self.register_list_option('foo', None)
3601
 
        conf = self.get_conf(b'foo= bar ,  baz ')
3602
 
        self.assertEqual(['bar', 'baz'], conf.get('foo'))
3603
 
 
3604
 
 
3605
 
class TestIterOptionRefs(tests.TestCase):
3606
 
    """iter_option_refs is a bit unusual, document some cases."""
3607
 
 
3608
 
    def assertRefs(self, expected, string):
3609
 
        self.assertEqual(expected, list(config.iter_option_refs(string)))
3610
 
 
3611
 
    def test_empty(self):
3612
 
        self.assertRefs([(False, '')], '')
3613
 
 
3614
 
    def test_no_refs(self):
3615
 
        self.assertRefs([(False, 'foo bar')], 'foo bar')
3616
 
 
3617
 
    def test_single_ref(self):
3618
 
        self.assertRefs([(False, ''), (True, '{foo}'), (False, '')], '{foo}')
3619
 
 
3620
 
    def test_broken_ref(self):
3621
 
        self.assertRefs([(False, '{foo')], '{foo')
3622
 
 
3623
 
    def test_embedded_ref(self):
3624
 
        self.assertRefs([(False, '{'), (True, '{foo}'), (False, '}')],
3625
 
                        '{{foo}}')
3626
 
 
3627
 
    def test_two_refs(self):
3628
 
        self.assertRefs([(False, ''), (True, '{foo}'),
3629
 
                         (False, ''), (True, '{bar}'),
3630
 
                         (False, ''), ],
3631
 
                        '{foo}{bar}')
3632
 
 
3633
 
    def test_newline_in_refs_are_not_matched(self):
3634
 
        self.assertRefs([(False, '{\nxx}{xx\n}{{\n}}')], '{\nxx}{xx\n}{{\n}}')
3635
 
 
3636
 
 
3637
 
class TestStackExpandOptions(tests.TestCaseWithTransport):
3638
 
 
3639
 
    def setUp(self):
3640
 
        super(TestStackExpandOptions, self).setUp()
3641
 
        self.overrideAttr(config, 'option_registry', config.OptionRegistry())
3642
 
        self.registry = config.option_registry
3643
 
        store = config.TransportIniFileStore(self.get_transport(), 'foo.conf')
3644
 
        self.conf = config.Stack([store.get_sections], store)
3645
 
 
3646
 
    def assertExpansion(self, expected, string, env=None):
3647
 
        self.assertEqual(expected, self.conf.expand_options(string, env))
3648
 
 
3649
 
    def test_no_expansion(self):
3650
 
        self.assertExpansion('foo', 'foo')
3651
 
 
3652
 
    def test_expand_default_value(self):
3653
 
        self.conf.store._load_from_string(b'bar=baz')
3654
 
        self.registry.register(config.Option('foo', default=u'{bar}'))
3655
 
        self.assertEqual('baz', self.conf.get('foo', expand=True))
3656
 
 
3657
 
    def test_expand_default_from_env(self):
3658
 
        self.conf.store._load_from_string(b'bar=baz')
3659
 
        self.registry.register(config.Option('foo', default_from_env=['FOO']))
3660
 
        self.overrideEnv('FOO', '{bar}')
3661
 
        self.assertEqual('baz', self.conf.get('foo', expand=True))
3662
 
 
3663
 
    def test_expand_default_on_failed_conversion(self):
3664
 
        self.conf.store._load_from_string(b'baz=bogus\nbar=42\nfoo={baz}')
3665
 
        self.registry.register(
3666
 
            config.Option('foo', default=u'{bar}',
3667
 
                          from_unicode=config.int_from_store))
3668
 
        self.assertEqual(42, self.conf.get('foo', expand=True))
3669
 
 
3670
 
    def test_env_adding_options(self):
3671
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3672
 
 
3673
 
    def test_env_overriding_options(self):
3674
 
        self.conf.store._load_from_string(b'foo=baz')
3675
 
        self.assertExpansion('bar', '{foo}', {'foo': 'bar'})
3676
 
 
3677
 
    def test_simple_ref(self):
3678
 
        self.conf.store._load_from_string(b'foo=xxx')
3679
 
        self.assertExpansion('xxx', '{foo}')
3680
 
 
3681
 
    def test_unknown_ref(self):
3682
 
        self.assertRaises(config.ExpandingUnknownOption,
3683
 
                          self.conf.expand_options, '{foo}')
3684
 
 
3685
 
    def test_illegal_def_is_ignored(self):
3686
 
        self.assertExpansion('{1,2}', '{1,2}')
3687
 
        self.assertExpansion('{ }', '{ }')
3688
 
        self.assertExpansion('${Foo,f}', '${Foo,f}')
3689
 
 
3690
 
    def test_indirect_ref(self):
3691
 
        self.conf.store._load_from_string(b'''
3692
 
foo=xxx
3693
 
bar={foo}
3694
 
''')
3695
 
        self.assertExpansion('xxx', '{bar}')
3696
 
 
3697
 
    def test_embedded_ref(self):
3698
 
        self.conf.store._load_from_string(b'''
3699
 
foo=xxx
3700
 
bar=foo
3701
 
''')
3702
 
        self.assertExpansion('xxx', '{{bar}}')
3703
 
 
3704
 
    def test_simple_loop(self):
3705
 
        self.conf.store._load_from_string(b'foo={foo}')
3706
 
        self.assertRaises(config.OptionExpansionLoop,
3707
 
                          self.conf.expand_options, '{foo}')
3708
 
 
3709
 
    def test_indirect_loop(self):
3710
 
        self.conf.store._load_from_string(b'''
3711
 
foo={bar}
3712
 
bar={baz}
3713
 
baz={foo}''')
3714
 
        e = self.assertRaises(config.OptionExpansionLoop,
3715
 
                              self.conf.expand_options, '{foo}')
3716
 
        self.assertEqual('foo->bar->baz', e.refs)
3717
 
        self.assertEqual('{foo}', e.string)
3718
 
 
3719
 
    def test_list(self):
3720
 
        self.conf.store._load_from_string(b'''
3721
 
foo=start
3722
 
bar=middle
3723
 
baz=end
3724
 
list={foo},{bar},{baz}
3725
 
''')
3726
 
        self.registry.register(
3727
 
            config.ListOption('list'))
3728
 
        self.assertEqual(['start', 'middle', 'end'],
3729
 
                         self.conf.get('list', expand=True))
3730
 
 
3731
 
    def test_cascading_list(self):
3732
 
        self.conf.store._load_from_string(b'''
3733
 
foo=start,{bar}
3734
 
bar=middle,{baz}
3735
 
baz=end
3736
 
list={foo}
3737
 
''')
3738
 
        self.registry.register(config.ListOption('list'))
3739
 
        # Register an intermediate option as a list to ensure no conversion
3740
 
        # happen while expanding. Conversion should only occur for the original
3741
 
        # option ('list' here).
3742
 
        self.registry.register(config.ListOption('baz'))
3743
 
        self.assertEqual(['start', 'middle', 'end'],
3744
 
                         self.conf.get('list', expand=True))
3745
 
 
3746
 
    def test_pathologically_hidden_list(self):
3747
 
        self.conf.store._load_from_string(b'''
3748
 
foo=bin
3749
 
bar=go
3750
 
start={foo
3751
 
middle=},{
3752
 
end=bar}
3753
 
hidden={start}{middle}{end}
3754
 
''')
3755
 
        # What matters is what the registration says, the conversion happens
3756
 
        # only after all expansions have been performed
3757
 
        self.registry.register(config.ListOption('hidden'))
3758
 
        self.assertEqual(['bin', 'go'],
3759
 
                         self.conf.get('hidden', expand=True))
3760
 
 
3761
 
 
3762
 
class TestStackCrossSectionsExpand(tests.TestCaseWithTransport):
3763
 
 
3764
 
    def setUp(self):
3765
 
        super(TestStackCrossSectionsExpand, self).setUp()
3766
 
 
3767
 
    def get_config(self, location, string):
3768
 
        if string is None:
3769
 
            string = b''
3770
 
        # Since we don't save the config we won't strictly require to inherit
3771
 
        # from TestCaseInTempDir, but an error occurs so quickly...
3772
 
        c = config.LocationStack(location)
3773
 
        c.store._load_from_string(string)
3774
 
        return c
3775
 
 
3776
 
    def test_dont_cross_unrelated_section(self):
3777
 
        c = self.get_config('/another/branch/path', b'''
3778
 
[/one/branch/path]
3779
 
foo = hello
3780
 
bar = {foo}/2
3781
 
 
3782
 
[/another/branch/path]
3783
 
bar = {foo}/2
3784
 
''')
3785
 
        self.assertRaises(config.ExpandingUnknownOption,
3786
 
                          c.get, 'bar', expand=True)
3787
 
 
3788
 
    def test_cross_related_sections(self):
3789
 
        c = self.get_config('/project/branch/path', b'''
3790
 
[/project]
3791
 
foo = qu
3792
 
 
3793
 
[/project/branch/path]
3794
 
bar = {foo}ux
3795
 
''')
3796
 
        self.assertEqual('quux', c.get('bar', expand=True))
3797
 
 
3798
 
 
3799
 
class TestStackCrossStoresExpand(tests.TestCaseWithTransport):
3800
 
 
3801
 
    def test_cross_global_locations(self):
3802
 
        l_store = config.LocationStore()
3803
 
        l_store._load_from_string(b'''
3804
 
[/branch]
3805
 
lfoo = loc-foo
3806
 
lbar = {gbar}
3807
 
''')
3808
 
        l_store.save()
3809
 
        g_store = config.GlobalStore()
3810
 
        g_store._load_from_string(b'''
3811
 
[DEFAULT]
3812
 
gfoo = {lfoo}
3813
 
gbar = glob-bar
3814
 
''')
3815
 
        g_store.save()
3816
 
        stack = config.LocationStack('/branch')
3817
 
        self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3818
 
        self.assertEqual('loc-foo', stack.get('gfoo', expand=True))
3819
 
 
3820
 
 
3821
 
class TestStackExpandSectionLocals(tests.TestCaseWithTransport):
3822
 
 
3823
 
    def test_expand_locals_empty(self):
3824
 
        l_store = config.LocationStore()
3825
 
        l_store._load_from_string(b'''
3826
 
[/home/user/project]
3827
 
base = {basename}
3828
 
rel = {relpath}
3829
 
''')
3830
 
        l_store.save()
3831
 
        stack = config.LocationStack('/home/user/project/')
3832
 
        self.assertEqual('', stack.get('base', expand=True))
3833
 
        self.assertEqual('', stack.get('rel', expand=True))
3834
 
 
3835
 
    def test_expand_basename_locally(self):
3836
 
        l_store = config.LocationStore()
3837
 
        l_store._load_from_string(b'''
3838
 
[/home/user/project]
3839
 
bfoo = {basename}
3840
 
''')
3841
 
        l_store.save()
3842
 
        stack = config.LocationStack('/home/user/project/branch')
3843
 
        self.assertEqual('branch', stack.get('bfoo', expand=True))
3844
 
 
3845
 
    def test_expand_basename_locally_longer_path(self):
3846
 
        l_store = config.LocationStore()
3847
 
        l_store._load_from_string(b'''
3848
 
[/home/user]
3849
 
bfoo = {basename}
3850
 
''')
3851
 
        l_store.save()
3852
 
        stack = config.LocationStack('/home/user/project/dir/branch')
3853
 
        self.assertEqual('branch', stack.get('bfoo', expand=True))
3854
 
 
3855
 
    def test_expand_relpath_locally(self):
3856
 
        l_store = config.LocationStore()
3857
 
        l_store._load_from_string(b'''
3858
 
[/home/user/project]
3859
 
lfoo = loc-foo/{relpath}
3860
 
''')
3861
 
        l_store.save()
3862
 
        stack = config.LocationStack('/home/user/project/branch')
3863
 
        self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3864
 
 
3865
 
    def test_expand_relpath_unknonw_in_global(self):
3866
 
        g_store = config.GlobalStore()
3867
 
        g_store._load_from_string(b'''
3868
 
[DEFAULT]
3869
 
gfoo = {relpath}
3870
 
''')
3871
 
        g_store.save()
3872
 
        stack = config.LocationStack('/home/user/project/branch')
3873
 
        self.assertRaises(config.ExpandingUnknownOption,
3874
 
                          stack.get, 'gfoo', expand=True)
3875
 
 
3876
 
    def test_expand_local_option_locally(self):
3877
 
        l_store = config.LocationStore()
3878
 
        l_store._load_from_string(b'''
3879
 
[/home/user/project]
3880
 
lfoo = loc-foo/{relpath}
3881
 
lbar = {gbar}
3882
 
''')
3883
 
        l_store.save()
3884
 
        g_store = config.GlobalStore()
3885
 
        g_store._load_from_string(b'''
3886
 
[DEFAULT]
3887
 
gfoo = {lfoo}
3888
 
gbar = glob-bar
3889
 
''')
3890
 
        g_store.save()
3891
 
        stack = config.LocationStack('/home/user/project/branch')
3892
 
        self.assertEqual('glob-bar', stack.get('lbar', expand=True))
3893
 
        self.assertEqual('loc-foo/branch', stack.get('gfoo', expand=True))
3894
 
 
3895
 
    def test_locals_dont_leak(self):
3896
 
        """Make sure we chose the right local in presence of several sections.
3897
 
        """
3898
 
        l_store = config.LocationStore()
3899
 
        l_store._load_from_string(b'''
3900
 
[/home/user]
3901
 
lfoo = loc-foo/{relpath}
3902
 
[/home/user/project]
3903
 
lfoo = loc-foo/{relpath}
3904
 
''')
3905
 
        l_store.save()
3906
 
        stack = config.LocationStack('/home/user/project/branch')
3907
 
        self.assertEqual('loc-foo/branch', stack.get('lfoo', expand=True))
3908
 
        stack = config.LocationStack('/home/user/bar/baz')
3909
 
        self.assertEqual('loc-foo/bar/baz', stack.get('lfoo', expand=True))
3910
 
 
3911
 
 
3912
 
class TestStackSet(TestStackWithTransport):
3913
 
 
3914
 
    def test_simple_set(self):
3915
 
        conf = self.get_stack(self)
3916
 
        self.assertEqual(None, conf.get('foo'))
3917
 
        conf.set('foo', 'baz')
3918
 
        # Did we get it back ?
3919
 
        self.assertEqual('baz', conf.get('foo'))
3920
 
 
3921
 
    def test_set_creates_a_new_section(self):
3922
 
        conf = self.get_stack(self)
3923
 
        conf.set('foo', 'baz')
3924
 
        self.assertEqual, 'baz', conf.get('foo')
3925
 
 
3926
 
    def test_set_hook(self):
3927
 
        calls = []
3928
 
 
3929
 
        def hook(*args):
3930
 
            calls.append(args)
3931
 
        config.ConfigHooks.install_named_hook('set', hook, None)
3932
 
        self.assertLength(0, calls)
3933
 
        conf = self.get_stack(self)
3934
 
        conf.set('foo', 'bar')
3935
 
        self.assertLength(1, calls)
3936
 
        self.assertEqual((conf, 'foo', 'bar'), calls[0])
3937
 
 
3938
 
 
3939
 
class TestStackRemove(TestStackWithTransport):
3940
 
 
3941
 
    def test_remove_existing(self):
3942
 
        conf = self.get_stack(self)
3943
 
        conf.set('foo', 'bar')
3944
 
        self.assertEqual('bar', conf.get('foo'))
3945
 
        conf.remove('foo')
3946
 
        # Did we get it back ?
3947
 
        self.assertEqual(None, conf.get('foo'))
3948
 
 
3949
 
    def test_remove_unknown(self):
3950
 
        conf = self.get_stack(self)
3951
 
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
3952
 
 
3953
 
    def test_remove_hook(self):
3954
 
        calls = []
3955
 
 
3956
 
        def hook(*args):
3957
 
            calls.append(args)
3958
 
        config.ConfigHooks.install_named_hook('remove', hook, None)
3959
 
        self.assertLength(0, calls)
3960
 
        conf = self.get_stack(self)
3961
 
        conf.set('foo', 'bar')
3962
 
        conf.remove('foo')
3963
 
        self.assertLength(1, calls)
3964
 
        self.assertEqual((conf, 'foo'), calls[0])
3965
 
 
3966
 
 
3967
 
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
3968
 
 
3969
 
    def setUp(self):
3970
 
        super(TestConfigGetOptions, self).setUp()
3971
 
        create_configs(self)
3972
 
 
3973
 
    def test_no_variable(self):
3974
 
        # Using branch should query branch, locations and breezy
3975
 
        self.assertOptions([], self.branch_config)
3976
 
 
3977
 
    def test_option_in_breezy(self):
3978
 
        self.breezy_config.set_user_option('file', 'breezy')
3979
 
        self.assertOptions([('file', 'breezy', 'DEFAULT', 'breezy')],
3980
 
                           self.breezy_config)
3981
 
 
3982
 
    def test_option_in_locations(self):
3983
 
        self.locations_config.set_user_option('file', 'locations')
3984
 
        self.assertOptions(
3985
 
            [('file', 'locations', self.tree.basedir, 'locations')],
3986
 
            self.locations_config)
3987
 
 
3988
 
    def test_option_in_branch(self):
3989
 
        self.branch_config.set_user_option('file', 'branch')
3990
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
3991
 
                           self.branch_config)
3992
 
 
3993
 
    def test_option_in_breezy_and_branch(self):
3994
 
        self.breezy_config.set_user_option('file', 'breezy')
3995
 
        self.branch_config.set_user_option('file', 'branch')
3996
 
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
3997
 
                            ('file', 'breezy', 'DEFAULT', 'breezy'), ],
3998
 
                           self.branch_config)
3999
 
 
4000
 
    def test_option_in_branch_and_locations(self):
4001
 
        # Hmm, locations override branch :-/
4002
 
        self.locations_config.set_user_option('file', 'locations')
4003
 
        self.branch_config.set_user_option('file', 'branch')
4004
 
        self.assertOptions(
4005
 
            [('file', 'locations', self.tree.basedir, 'locations'),
4006
 
             ('file', 'branch', 'DEFAULT', 'branch'), ],
4007
 
            self.branch_config)
4008
 
 
4009
 
    def test_option_in_breezy_locations_and_branch(self):
4010
 
        self.breezy_config.set_user_option('file', 'breezy')
4011
 
        self.locations_config.set_user_option('file', 'locations')
4012
 
        self.branch_config.set_user_option('file', 'branch')
4013
 
        self.assertOptions(
4014
 
            [('file', 'locations', self.tree.basedir, 'locations'),
4015
 
             ('file', 'branch', 'DEFAULT', 'branch'),
4016
 
             ('file', 'breezy', 'DEFAULT', 'breezy'), ],
4017
 
            self.branch_config)
4018
 
 
4019
 
 
4020
 
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
4021
 
 
4022
 
    def setUp(self):
4023
 
        super(TestConfigRemoveOption, self).setUp()
4024
 
        create_configs_with_file_option(self)
4025
 
 
4026
 
    def test_remove_in_locations(self):
4027
 
        self.locations_config.remove_user_option('file', self.tree.basedir)
4028
 
        self.assertOptions(
4029
 
            [('file', 'branch', 'DEFAULT', 'branch'),
4030
 
             ('file', 'breezy', 'DEFAULT', 'breezy'), ],
4031
 
            self.branch_config)
4032
 
 
4033
 
    def test_remove_in_branch(self):
4034
 
        self.branch_config.remove_user_option('file')
4035
 
        self.assertOptions(
4036
 
            [('file', 'locations', self.tree.basedir, 'locations'),
4037
 
             ('file', 'breezy', 'DEFAULT', 'breezy'), ],
4038
 
            self.branch_config)
4039
 
 
4040
 
    def test_remove_in_breezy(self):
4041
 
        self.breezy_config.remove_user_option('file')
4042
 
        self.assertOptions(
4043
 
            [('file', 'locations', self.tree.basedir, 'locations'),
4044
 
             ('file', 'branch', 'DEFAULT', 'branch'), ],
4045
 
            self.branch_config)
4046
 
 
4047
 
 
4048
 
class TestConfigGetSections(tests.TestCaseWithTransport):
4049
 
 
4050
 
    def setUp(self):
4051
 
        super(TestConfigGetSections, self).setUp()
4052
 
        create_configs(self)
4053
 
 
4054
 
    def assertSectionNames(self, expected, conf, name=None):
4055
 
        """Check which sections are returned for a given config.
4056
 
 
4057
 
        If fallback configurations exist their sections can be included.
4058
 
 
4059
 
        :param expected: A list of section names.
4060
 
 
4061
 
        :param conf: The configuration that will be queried.
4062
 
 
4063
 
        :param name: An optional section name that will be passed to
4064
 
            get_sections().
4065
 
        """
4066
 
        sections = list(conf._get_sections(name))
4067
 
        self.assertLength(len(expected), sections)
4068
 
        self.assertEqual(expected, [n for n, _, _ in sections])
4069
 
 
4070
 
    def test_breezy_default_section(self):
4071
 
        self.assertSectionNames(['DEFAULT'], self.breezy_config)
4072
 
 
4073
 
    def test_locations_default_section(self):
4074
 
        # No sections are defined in an empty file
4075
 
        self.assertSectionNames([], self.locations_config)
4076
 
 
4077
 
    def test_locations_named_section(self):
4078
 
        self.locations_config.set_user_option('file', 'locations')
4079
 
        self.assertSectionNames([self.tree.basedir], self.locations_config)
4080
 
 
4081
 
    def test_locations_matching_sections(self):
4082
 
        loc_config = self.locations_config
4083
 
        loc_config.set_user_option('file', 'locations')
4084
 
        # We need to cheat a bit here to create an option in sections above and
4085
 
        # below the 'location' one.
4086
 
        parser = loc_config._get_parser()
4087
 
        # locations.cong deals with '/' ignoring native os.sep
4088
 
        location_names = self.tree.basedir.split('/')
4089
 
        parent = '/'.join(location_names[:-1])
4090
 
        child = '/'.join(location_names + ['child'])
4091
 
        parser[parent] = {}
4092
 
        parser[parent]['file'] = 'parent'
4093
 
        parser[child] = {}
4094
 
        parser[child]['file'] = 'child'
4095
 
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
4096
 
 
4097
 
    def test_branch_data_default_section(self):
4098
 
        self.assertSectionNames([None],
4099
 
                                self.branch_config._get_branch_data_config())
4100
 
 
4101
 
    def test_branch_default_sections(self):
4102
 
        # No sections are defined in an empty locations file
4103
 
        self.assertSectionNames([None, 'DEFAULT'],
4104
 
                                self.branch_config)
4105
 
        # Unless we define an option
4106
 
        self.branch_config._get_location_config().set_user_option(
4107
 
            'file', 'locations')
4108
 
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
4109
 
                                self.branch_config)
4110
 
 
4111
 
    def test_breezy_named_section(self):
4112
 
        # We need to cheat as the API doesn't give direct access to sections
4113
 
        # other than DEFAULT.
4114
 
        self.breezy_config.set_alias('breezy', 'bzr')
4115
 
        self.assertSectionNames(['ALIASES'], self.breezy_config, 'ALIASES')
4116
 
 
4117
 
 
4118
 
class TestSharedStores(tests.TestCaseInTempDir):
4119
 
 
4120
 
    def test_breezy_conf_shared(self):
4121
 
        g1 = config.GlobalStack()
4122
 
        g2 = config.GlobalStack()
4123
 
        # The two stacks share the same store
4124
 
        self.assertIs(g1.store, g2.store)
4125
 
 
4126
 
 
4127
 
class TestAuthenticationConfigFilePermissions(tests.TestCaseInTempDir):
4128
 
    """Test warning for permissions of authentication.conf."""
4129
 
 
4130
 
    def setUp(self):
4131
 
        super(TestAuthenticationConfigFilePermissions, self).setUp()
4132
 
        self.path = osutils.pathjoin(self.test_dir, 'authentication.conf')
4133
 
        with open(self.path, 'wb') as f:
4134
 
            f.write(b"""[broken]
4135
 
scheme=ftp
4136
 
user=joe
4137
 
port=port # Error: Not an int
4138
 
""")
4139
 
        self.overrideAttr(bedding, 'authentication_config_path',
4140
 
                          lambda: self.path)
4141
 
        osutils.chmod_if_possible(self.path, 0o755)
4142
 
 
4143
 
    def test_check_warning(self):
4144
 
        conf = config.AuthenticationConfig()
4145
 
        self.assertEqual(conf._filename, self.path)
4146
 
        self.assertContainsRe(self.get_log(),
4147
 
                              'Saved passwords may be accessible by other users.')
4148
 
 
4149
 
    def test_check_suppressed_warning(self):
4150
 
        global_config = config.GlobalConfig()
4151
 
        global_config.set_user_option('suppress_warnings',
4152
 
                                      'insecure_permissions')
4153
 
        conf = config.AuthenticationConfig()
4154
 
        self.assertEqual(conf._filename, self.path)
4155
 
        self.assertNotContainsRe(self.get_log(),
4156
 
                                 'Saved passwords may be accessible by other users.')
4157
 
 
4158
 
 
4159
 
class TestAuthenticationConfigFile(tests.TestCase):
4160
 
    """Test the authentication.conf file matching"""
4161
 
 
4162
 
    def _got_user_passwd(self, expected_user, expected_password,
4163
 
                         config, *args, **kwargs):
4164
 
        credentials = config.get_credentials(*args, **kwargs)
4165
 
        if credentials is None:
4166
 
            user = None
4167
 
            password = None
4168
 
        else:
4169
 
            user = credentials['user']
4170
 
            password = credentials['password']
4171
 
        self.assertEqual(expected_user, user)
4172
 
        self.assertEqual(expected_password, password)
4173
 
 
4174
 
    def test_empty_config(self):
4175
 
        conf = config.AuthenticationConfig(_file=BytesIO())
4176
 
        self.assertEqual({}, conf._get_config())
4177
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
4178
 
 
4179
 
    def test_non_utf8_config(self):
4180
 
        conf = config.AuthenticationConfig(_file=BytesIO(b'foo = bar\xff'))
4181
 
        self.assertRaises(config.ConfigContentError, conf._get_config)
4182
 
 
4183
 
    def test_missing_auth_section_header(self):
4184
 
        conf = config.AuthenticationConfig(_file=BytesIO(b'foo = bar'))
4185
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
4186
 
 
4187
 
    def test_auth_section_header_not_closed(self):
4188
 
        conf = config.AuthenticationConfig(_file=BytesIO(b'[DEF'))
4189
 
        self.assertRaises(config.ParseConfigError, conf._get_config)
4190
 
 
4191
 
    def test_auth_value_not_boolean(self):
4192
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4193
 
[broken]
4194
 
scheme=ftp
4195
 
user=joe
4196
 
verify_certificates=askme # Error: Not a boolean
4197
 
"""))
4198
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
4199
 
 
4200
 
    def test_auth_value_not_int(self):
4201
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4202
 
[broken]
4203
 
scheme=ftp
4204
 
user=joe
4205
 
port=port # Error: Not an int
4206
 
"""))
4207
 
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
4208
 
 
4209
 
    def test_unknown_password_encoding(self):
4210
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4211
 
[broken]
4212
 
scheme=ftp
4213
 
user=joe
4214
 
password_encoding=unknown
4215
 
"""))
4216
 
        self.assertRaises(ValueError, conf.get_password,
4217
 
                          'ftp', 'foo.net', 'joe')
4218
 
 
4219
 
    def test_credentials_for_scheme_host(self):
4220
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4221
 
# Identity on foo.net
4222
 
[ftp definition]
4223
 
scheme=ftp
4224
 
host=foo.net
4225
 
user=joe
4226
 
password=secret-pass
4227
 
"""))
4228
 
        # Basic matching
4229
 
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
4230
 
        # different scheme
4231
 
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
4232
 
        # different host
4233
 
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
4234
 
 
4235
 
    def test_credentials_for_host_port(self):
4236
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4237
 
# Identity on foo.net
4238
 
[ftp definition]
4239
 
scheme=ftp
4240
 
port=10021
4241
 
host=foo.net
4242
 
user=joe
4243
 
password=secret-pass
4244
 
"""))
4245
 
        # No port
4246
 
        self._got_user_passwd('joe', 'secret-pass',
4247
 
                              conf, 'ftp', 'foo.net', port=10021)
4248
 
        # different port
4249
 
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
4250
 
 
4251
 
    def test_for_matching_host(self):
4252
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4253
 
# Identity on foo.net
4254
 
[sourceforge]
4255
 
scheme=bzr
4256
 
host=bzr.sf.net
4257
 
user=joe
4258
 
password=joepass
4259
 
[sourceforge domain]
4260
 
scheme=bzr
4261
 
host=.bzr.sf.net
4262
 
user=georges
4263
 
password=bendover
4264
 
"""))
4265
 
        # matching domain
4266
 
        self._got_user_passwd('georges', 'bendover',
4267
 
                              conf, 'bzr', 'foo.bzr.sf.net')
4268
 
        # phishing attempt
4269
 
        self._got_user_passwd(None, None,
4270
 
                              conf, 'bzr', 'bbzr.sf.net')
4271
 
 
4272
 
    def test_for_matching_host_None(self):
4273
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""\
4274
 
# Identity on foo.net
4275
 
[catchup bzr]
4276
 
scheme=bzr
4277
 
user=joe
4278
 
password=joepass
4279
 
[DEFAULT]
4280
 
user=georges
4281
 
password=bendover
4282
 
"""))
4283
 
        # match no host
4284
 
        self._got_user_passwd('joe', 'joepass',
4285
 
                              conf, 'bzr', 'quux.net')
4286
 
        # no host but different scheme
4287
 
        self._got_user_passwd('georges', 'bendover',
4288
 
                              conf, 'ftp', 'quux.net')
4289
 
 
4290
 
    def test_credentials_for_path(self):
4291
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4292
 
[http dir1]
4293
 
scheme=http
4294
 
host=bar.org
4295
 
path=/dir1
4296
 
user=jim
4297
 
password=jimpass
4298
 
[http dir2]
4299
 
scheme=http
4300
 
host=bar.org
4301
 
path=/dir2
4302
 
user=georges
4303
 
password=bendover
4304
 
"""))
4305
 
        # no path no dice
4306
 
        self._got_user_passwd(None, None,
4307
 
                              conf, 'http', host='bar.org', path='/dir3')
4308
 
        # matching path
4309
 
        self._got_user_passwd('georges', 'bendover',
4310
 
                              conf, 'http', host='bar.org', path='/dir2')
4311
 
        # matching subdir
4312
 
        self._got_user_passwd('jim', 'jimpass',
4313
 
                              conf, 'http', host='bar.org', path='/dir1/subdir')
4314
 
 
4315
 
    def test_credentials_for_user(self):
4316
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4317
 
[with user]
4318
 
scheme=http
4319
 
host=bar.org
4320
 
user=jim
4321
 
password=jimpass
4322
 
"""))
4323
 
        # Get user
4324
 
        self._got_user_passwd('jim', 'jimpass',
4325
 
                              conf, 'http', 'bar.org')
4326
 
        # Get same user
4327
 
        self._got_user_passwd('jim', 'jimpass',
4328
 
                              conf, 'http', 'bar.org', user='jim')
4329
 
        # Don't get a different user if one is specified
4330
 
        self._got_user_passwd(None, None,
4331
 
                              conf, 'http', 'bar.org', user='georges')
4332
 
 
4333
 
    def test_credentials_for_user_without_password(self):
4334
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4335
 
[without password]
4336
 
scheme=http
4337
 
host=bar.org
4338
 
user=jim
4339
 
"""))
4340
 
        # Get user but no password
4341
 
        self._got_user_passwd('jim', None,
4342
 
                              conf, 'http', 'bar.org')
4343
 
 
4344
 
    def test_verify_certificates(self):
4345
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4346
 
[self-signed]
4347
 
scheme=https
4348
 
host=bar.org
4349
 
user=jim
4350
 
password=jimpass
4351
 
verify_certificates=False
4352
 
[normal]
4353
 
scheme=https
4354
 
host=foo.net
4355
 
user=georges
4356
 
password=bendover
4357
 
"""))
4358
 
        credentials = conf.get_credentials('https', 'bar.org')
4359
 
        self.assertEqual(False, credentials.get('verify_certificates'))
4360
 
        credentials = conf.get_credentials('https', 'foo.net')
4361
 
        self.assertEqual(True, credentials.get('verify_certificates'))
4362
 
 
4363
 
 
4364
 
class TestAuthenticationStorage(tests.TestCaseInTempDir):
4365
 
 
4366
 
    def test_set_credentials(self):
4367
 
        conf = config.AuthenticationConfig()
4368
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
4369
 
                             99, path='/foo', verify_certificates=False, realm='realm')
4370
 
        credentials = conf.get_credentials(host='host', scheme='scheme',
4371
 
                                           port=99, path='/foo',
4372
 
                                           realm='realm')
4373
 
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4374
 
                       'verify_certificates': False, 'scheme': 'scheme',
4375
 
                       'host': 'host', 'port': 99, 'path': '/foo',
4376
 
                       'realm': 'realm'}
4377
 
        self.assertEqual(CREDENTIALS, credentials)
4378
 
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4379
 
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
4380
 
        self.assertEqual(CREDENTIALS, credentials_from_disk)
4381
 
 
4382
 
    def test_reset_credentials_different_name(self):
4383
 
        conf = config.AuthenticationConfig()
4384
 
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
4385
 
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
4386
 
        self.assertIs(None, conf._get_config().get('name'))
4387
 
        credentials = conf.get_credentials(host='host', scheme='scheme')
4388
 
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4389
 
                       'password', 'verify_certificates': True,
4390
 
                       'scheme': 'scheme', 'host': 'host', 'port': None,
4391
 
                       'path': None, 'realm': None}
4392
 
        self.assertEqual(CREDENTIALS, credentials)
4393
 
 
4394
 
 
4395
 
class TestAuthenticationConfig(tests.TestCaseInTempDir):
4396
 
    """Test AuthenticationConfig behaviour"""
4397
 
 
4398
 
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
4399
 
                                       host=None, port=None, realm=None,
4400
 
                                       path=None):
4401
 
        if host is None:
4402
 
            host = 'bar.org'
4403
 
        user, password = 'jim', 'precious'
4404
 
        expected_prompt = expected_prompt_format % {
4405
 
            'scheme': scheme, 'host': host, 'port': port,
4406
 
            'user': user, 'realm': realm}
4407
 
 
4408
 
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n')
4409
 
        # We use an empty conf so that the user is always prompted
4410
 
        conf = config.AuthenticationConfig()
4411
 
        self.assertEqual(password,
4412
 
                         conf.get_password(scheme, host, user, port=port,
4413
 
                                           realm=realm, path=path))
4414
 
        self.assertEqual(expected_prompt, ui.ui_factory.stderr.getvalue())
4415
 
        self.assertEqual('', ui.ui_factory.stdout.getvalue())
4416
 
 
4417
 
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
4418
 
                                       host=None, port=None, realm=None,
4419
 
                                       path=None):
4420
 
        if host is None:
4421
 
            host = 'bar.org'
4422
 
        username = 'jim'
4423
 
        expected_prompt = expected_prompt_format % {
4424
 
            'scheme': scheme, 'host': host, 'port': port,
4425
 
            'realm': realm}
4426
 
        ui.ui_factory = tests.TestUIFactory(stdin=username + '\n')
4427
 
        # We use an empty conf so that the user is always prompted
4428
 
        conf = config.AuthenticationConfig()
4429
 
        self.assertEqual(username, conf.get_user(scheme, host, port=port,
4430
 
                                                 realm=realm, path=path, ask=True))
4431
 
        self.assertEqual(expected_prompt, ui.ui_factory.stderr.getvalue())
4432
 
        self.assertEqual('', ui.ui_factory.stdout.getvalue())
4433
 
 
4434
 
    def test_username_defaults_prompts(self):
4435
 
        # HTTP prompts can't be tested here, see test_http.py
4436
 
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
4437
 
        self._check_default_username_prompt(
4438
 
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
4439
 
        self._check_default_username_prompt(
4440
 
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
4441
 
 
4442
 
    def test_username_default_no_prompt(self):
4443
 
        conf = config.AuthenticationConfig()
4444
 
        self.assertEqual(None,
4445
 
                         conf.get_user('ftp', 'example.com'))
4446
 
        self.assertEqual("explicitdefault",
4447
 
                         conf.get_user('ftp', 'example.com', default="explicitdefault"))
4448
 
 
4449
 
    def test_password_default_prompts(self):
4450
 
        # HTTP prompts can't be tested here, see test_http.py
4451
 
        self._check_default_password_prompt(
4452
 
            u'FTP %(user)s@%(host)s password: ', 'ftp')
4453
 
        self._check_default_password_prompt(
4454
 
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
4455
 
        self._check_default_password_prompt(
4456
 
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
4457
 
        # SMTP port handling is a bit special (it's handled if embedded in the
4458
 
        # host too)
4459
 
        # FIXME: should we: forbid that, extend it to other schemes, leave
4460
 
        # things as they are that's fine thank you ?
4461
 
        self._check_default_password_prompt(
4462
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
4463
 
        self._check_default_password_prompt(
4464
 
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
4465
 
        self._check_default_password_prompt(
4466
 
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
4467
 
 
4468
 
    def test_ssh_password_emits_warning(self):
4469
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4470
 
[ssh with password]
4471
 
scheme=ssh
4472
 
host=bar.org
4473
 
user=jim
4474
 
password=jimpass
4475
 
"""))
4476
 
        entered_password = 'typed-by-hand'
4477
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n')
4478
 
 
4479
 
        # Since the password defined in the authentication config is ignored,
4480
 
        # the user is prompted
4481
 
        self.assertEqual(entered_password,
4482
 
                         conf.get_password('ssh', 'bar.org', user='jim'))
4483
 
        self.assertContainsRe(
4484
 
            self.get_log(),
4485
 
            'password ignored in section \\[ssh with password\\]')
4486
 
 
4487
 
    def test_ssh_without_password_doesnt_emit_warning(self):
4488
 
        conf = config.AuthenticationConfig(_file=BytesIO(b"""
4489
 
[ssh with password]
4490
 
scheme=ssh
4491
 
host=bar.org
4492
 
user=jim
4493
 
"""))
4494
 
        entered_password = 'typed-by-hand'
4495
 
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n')
4496
 
 
4497
 
        # Since the password defined in the authentication config is ignored,
4498
 
        # the user is prompted
4499
 
        self.assertEqual(entered_password,
4500
 
                         conf.get_password('ssh', 'bar.org', user='jim'))
4501
 
        # No warning shoud be emitted since there is no password. We are only
4502
 
        # providing "user".
4503
 
        self.assertNotContainsRe(
4504
 
            self.get_log(),
4505
 
            'password ignored in section \\[ssh with password\\]')
4506
 
 
4507
 
    def test_uses_fallback_stores(self):
4508
 
        self.overrideAttr(config, 'credential_store_registry',
4509
 
                          config.CredentialStoreRegistry())
4510
 
        store = StubCredentialStore()
4511
 
        store.add_credentials("http", "example.com", "joe", "secret")
4512
 
        config.credential_store_registry.register("stub", store, fallback=True)
4513
 
        conf = config.AuthenticationConfig(_file=BytesIO())
4514
 
        creds = conf.get_credentials("http", "example.com")
4515
 
        self.assertEqual("joe", creds["user"])
4516
 
        self.assertEqual("secret", creds["password"])
4517
 
 
4518
 
 
4519
 
class StubCredentialStore(config.CredentialStore):
4520
 
 
4521
 
    def __init__(self):
4522
 
        self._username = {}
4523
 
        self._password = {}
4524
 
 
4525
 
    def add_credentials(self, scheme, host, user, password=None):
4526
 
        self._username[(scheme, host)] = user
4527
 
        self._password[(scheme, host)] = password
4528
 
 
4529
 
    def get_credentials(self, scheme, host, port=None, user=None,
4530
 
                        path=None, realm=None):
4531
 
        key = (scheme, host)
4532
 
        if key not in self._username:
4533
 
            return None
4534
 
        return {"scheme": scheme, "host": host, "port": port,
4535
 
                "user": self._username[key], "password": self._password[key]}
4536
 
 
4537
 
 
4538
 
class CountingCredentialStore(config.CredentialStore):
4539
 
 
4540
 
    def __init__(self):
4541
 
        self._calls = 0
4542
 
 
4543
 
    def get_credentials(self, scheme, host, port=None, user=None,
4544
 
                        path=None, realm=None):
4545
 
        self._calls += 1
4546
 
        return None
4547
 
 
4548
 
 
4549
 
class TestCredentialStoreRegistry(tests.TestCase):
4550
 
 
4551
 
    def _get_cs_registry(self):
4552
 
        return config.credential_store_registry
4553
 
 
4554
 
    def test_default_credential_store(self):
4555
 
        r = self._get_cs_registry()
4556
 
        default = r.get_credential_store(None)
4557
 
        self.assertIsInstance(default, config.PlainTextCredentialStore)
4558
 
 
4559
 
    def test_unknown_credential_store(self):
4560
 
        r = self._get_cs_registry()
4561
 
        # It's hard to imagine someone creating a credential store named
4562
 
        # 'unknown' so we use that as an never registered key.
4563
 
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
4564
 
 
4565
 
    def test_fallback_none_registered(self):
4566
 
        r = config.CredentialStoreRegistry()
4567
 
        self.assertEqual(None,
4568
 
                         r.get_fallback_credentials("http", "example.com"))
4569
 
 
4570
 
    def test_register(self):
4571
 
        r = config.CredentialStoreRegistry()
4572
 
        r.register("stub", StubCredentialStore(), fallback=False)
4573
 
        r.register("another", StubCredentialStore(), fallback=True)
4574
 
        self.assertEqual(["another", "stub"], r.keys())
4575
 
 
4576
 
    def test_register_lazy(self):
4577
 
        r = config.CredentialStoreRegistry()
4578
 
        r.register_lazy("stub", "breezy.tests.test_config",
4579
 
                        "StubCredentialStore", fallback=False)
4580
 
        self.assertEqual(["stub"], r.keys())
4581
 
        self.assertIsInstance(r.get_credential_store("stub"),
4582
 
                              StubCredentialStore)
4583
 
 
4584
 
    def test_is_fallback(self):
4585
 
        r = config.CredentialStoreRegistry()
4586
 
        r.register("stub1", None, fallback=False)
4587
 
        r.register("stub2", None, fallback=True)
4588
 
        self.assertEqual(False, r.is_fallback("stub1"))
4589
 
        self.assertEqual(True, r.is_fallback("stub2"))
4590
 
 
4591
 
    def test_no_fallback(self):
4592
 
        r = config.CredentialStoreRegistry()
4593
 
        store = CountingCredentialStore()
4594
 
        r.register("count", store, fallback=False)
4595
 
        self.assertEqual(None,
4596
 
                         r.get_fallback_credentials("http", "example.com"))
4597
 
        self.assertEqual(0, store._calls)
4598
 
 
4599
 
    def test_fallback_credentials(self):
4600
 
        r = config.CredentialStoreRegistry()
4601
 
        store = StubCredentialStore()
4602
 
        store.add_credentials("http", "example.com",
4603
 
                              "somebody", "geheim")
4604
 
        r.register("stub", store, fallback=True)
4605
 
        creds = r.get_fallback_credentials("http", "example.com")
4606
 
        self.assertEqual("somebody", creds["user"])
4607
 
        self.assertEqual("geheim", creds["password"])
4608
 
 
4609
 
    def test_fallback_first_wins(self):
4610
 
        r = config.CredentialStoreRegistry()
4611
 
        stub1 = StubCredentialStore()
4612
 
        stub1.add_credentials("http", "example.com",
4613
 
                              "somebody", "stub1")
4614
 
        r.register("stub1", stub1, fallback=True)
4615
 
        stub2 = StubCredentialStore()
4616
 
        stub2.add_credentials("http", "example.com",
4617
 
                              "somebody", "stub2")
4618
 
        r.register("stub2", stub1, fallback=True)
4619
 
        creds = r.get_fallback_credentials("http", "example.com")
4620
 
        self.assertEqual("somebody", creds["user"])
4621
 
        self.assertEqual("stub1", creds["password"])
4622
 
 
4623
 
 
4624
 
class TestPlainTextCredentialStore(tests.TestCase):
4625
 
 
4626
 
    def test_decode_password(self):
4627
 
        r = config.credential_store_registry
4628
 
        plain_text = r.get_credential_store()
4629
 
        decoded = plain_text.decode_password(dict(password='secret'))
4630
 
        self.assertEqual('secret', decoded)
4631
 
 
4632
 
 
4633
 
class TestBase64CredentialStore(tests.TestCase):
4634
 
 
4635
 
    def test_decode_password(self):
4636
 
        r = config.credential_store_registry
4637
 
        plain_text = r.get_credential_store('base64')
4638
 
        decoded = plain_text.decode_password(dict(password='c2VjcmV0'))
4639
 
        self.assertEqual(b'secret', decoded)
4640
 
 
4641
 
 
4642
 
# FIXME: Once we have a way to declare authentication to all test servers, we
4643
 
# can implement generic tests.
4644
 
# test_user_password_in_url
4645
 
# test_user_in_url_password_from_config
4646
 
# test_user_in_url_password_prompted
4647
 
# test_user_in_config
4648
 
# test_user_getpass.getuser
4649
 
# test_user_prompted ?
4650
 
class TestAuthenticationRing(tests.TestCaseWithTransport):
4651
 
    pass
4652
 
 
4653
 
 
4654
 
class EmailOptionTests(tests.TestCase):
4655
 
 
4656
 
    def test_default_email_uses_BRZ_EMAIL(self):
4657
 
        conf = config.MemoryStack(b'email=jelmer@debian.org')
4658
 
        # BRZ_EMAIL takes precedence over BZR_EMAIL and EMAIL
4659
 
        self.overrideEnv('BRZ_EMAIL', 'jelmer@samba.org')
4660
 
        self.overrideEnv('BZR_EMAIL', 'jelmer@jelmer.uk')
4661
 
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
4662
 
        self.assertEqual('jelmer@samba.org', conf.get('email'))
4663
 
 
4664
 
    def test_default_email_uses_BZR_EMAIL(self):
4665
 
        conf = config.MemoryStack(b'email=jelmer@debian.org')
4666
 
        # BZR_EMAIL takes precedence over EMAIL
4667
 
        self.overrideEnv('BZR_EMAIL', 'jelmer@samba.org')
4668
 
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
4669
 
        self.assertEqual('jelmer@samba.org', conf.get('email'))
4670
 
 
4671
 
    def test_default_email_uses_EMAIL(self):
4672
 
        conf = config.MemoryStack(b'')
4673
 
        self.overrideEnv('BRZ_EMAIL', None)
4674
 
        self.overrideEnv('EMAIL', 'jelmer@apache.org')
4675
 
        self.assertEqual('jelmer@apache.org', conf.get('email'))
4676
 
 
4677
 
    def test_BRZ_EMAIL_overrides(self):
4678
 
        conf = config.MemoryStack(b'email=jelmer@debian.org')
4679
 
        self.overrideEnv('BRZ_EMAIL', 'jelmer@apache.org')
4680
 
        self.assertEqual('jelmer@apache.org', conf.get('email'))
4681
 
        self.overrideEnv('BRZ_EMAIL', None)
4682
 
        self.overrideEnv('EMAIL', 'jelmer@samba.org')
4683
 
        self.assertEqual('jelmer@debian.org', conf.get('email'))
4684
 
 
4685
 
 
4686
 
class MailClientOptionTests(tests.TestCase):
4687
 
 
4688
 
    def test_default(self):
4689
 
        conf = config.MemoryStack(b'')
4690
 
        client = conf.get('mail_client')
4691
 
        self.assertIs(client, mail_client.DefaultMail)
4692
 
 
4693
 
    def test_evolution(self):
4694
 
        conf = config.MemoryStack(b'mail_client=evolution')
4695
 
        client = conf.get('mail_client')
4696
 
        self.assertIs(client, mail_client.Evolution)
4697
 
 
4698
 
    def test_kmail(self):
4699
 
        conf = config.MemoryStack(b'mail_client=kmail')
4700
 
        client = conf.get('mail_client')
4701
 
        self.assertIs(client, mail_client.KMail)
4702
 
 
4703
 
    def test_mutt(self):
4704
 
        conf = config.MemoryStack(b'mail_client=mutt')
4705
 
        client = conf.get('mail_client')
4706
 
        self.assertIs(client, mail_client.Mutt)
4707
 
 
4708
 
    def test_thunderbird(self):
4709
 
        conf = config.MemoryStack(b'mail_client=thunderbird')
4710
 
        client = conf.get('mail_client')
4711
 
        self.assertIs(client, mail_client.Thunderbird)
4712
 
 
4713
 
    def test_explicit_default(self):
4714
 
        conf = config.MemoryStack(b'mail_client=default')
4715
 
        client = conf.get('mail_client')
4716
 
        self.assertIs(client, mail_client.DefaultMail)
4717
 
 
4718
 
    def test_editor(self):
4719
 
        conf = config.MemoryStack(b'mail_client=editor')
4720
 
        client = conf.get('mail_client')
4721
 
        self.assertIs(client, mail_client.Editor)
4722
 
 
4723
 
    def test_mapi(self):
4724
 
        conf = config.MemoryStack(b'mail_client=mapi')
4725
 
        client = conf.get('mail_client')
4726
 
        self.assertIs(client, mail_client.MAPIClient)
4727
 
 
4728
 
    def test_xdg_email(self):
4729
 
        conf = config.MemoryStack(b'mail_client=xdg-email')
4730
 
        client = conf.get('mail_client')
4731
 
        self.assertIs(client, mail_client.XDGEmail)
4732
 
 
4733
 
    def test_unknown(self):
4734
 
        conf = config.MemoryStack(b'mail_client=firebird')
4735
 
        self.assertRaises(config.ConfigOptionValueError, conf.get,
4736
 
                          'mail_client')