~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005, 2006 Canonical Ltd
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
18
"""Tests for finding and reading the bzr config file[s]."""
19
# import system imports here
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
20
from cStringIO import StringIO
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
21
import os
22
import sys
23
24
#import bzrlib specific imports here
1878.1.3 by John Arbash Meinel
some test cleanups
25
from bzrlib import (
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
26
    branch,
27
    bzrdir,
1878.1.3 by John Arbash Meinel
some test cleanups
28
    config,
29
    errors,
30
    osutils,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
31
    mail_client,
2900.2.14 by Vincent Ladeuil
More tests.
32
    ui,
1878.1.3 by John Arbash Meinel
some test cleanups
33
    urlutils,
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
34
    tests,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
35
    trace,
1878.1.3 by John Arbash Meinel
some test cleanups
36
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
37
from bzrlib.util.configobj import configobj
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
38
39
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
40
sample_long_alias="log -r-15..-1 --line"
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
41
sample_config_text = u"""
42
[DEFAULT]
43
email=Erik B\u00e5gfors <erik@bagfors.nu>
44
editor=vim
45
gpg_signing_command=gnome-gpg
46
log_format=short
47
user_global_option=something
48
[ALIASES]
49
h=help
50
ll=""" + sample_long_alias + "\n"
51
52
53
sample_always_signatures = """
54
[DEFAULT]
55
check_signatures=ignore
56
create_signatures=always
57
"""
58
59
sample_ignore_signatures = """
60
[DEFAULT]
61
check_signatures=require
62
create_signatures=never
63
"""
64
65
sample_maybe_signatures = """
66
[DEFAULT]
67
check_signatures=ignore
68
create_signatures=when-required
69
"""
70
71
sample_branches_text = """
72
[http://www.example.com]
73
# Top level policy
74
email=Robert Collins <robertc@example.org>
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
75
normal_option = normal
76
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
77
appendpath_option:policy = appendpath
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
78
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
79
norecurse_option:policy = norecurse
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
80
[http://www.example.com/ignoreparent]
81
# different project: ignore parent dir config
82
ignore_parents=true
83
[http://www.example.com/norecurse]
84
# configuration items that only apply to this dir
85
recurse=false
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
86
normal_option = norecurse
87
[http://www.example.com/dir]
88
appendpath_option = normal
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
89
[/b/]
90
check_signatures=require
91
# test trailing / matching with no children
92
[/a/]
93
check_signatures=check-available
94
gpg_signing_command=false
95
user_local_option=local
96
# test trailing / matching
97
[/a/*]
98
#subdirs will match but not the parent
99
[/a/c]
100
check_signatures=ignore
101
post_commit=bzrlib.tests.test_config.post_commit
102
#testing explicit beats globs
103
"""
1553.6.3 by Erik Bågfors
tests for AliasesConfig
104
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
105
1474 by Robert Collins
Merge from Aaron Bentley.
106
class InstrumentedConfigObj(object):
107
    """A config obj look-enough-alike to record calls made to it."""
108
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
109
    def __contains__(self, thing):
110
        self._calls.append(('__contains__', thing))
111
        return False
112
113
    def __getitem__(self, key):
114
        self._calls.append(('__getitem__', key))
115
        return self
116
1551.2.20 by Aaron Bentley
Treated config files as utf-8
117
    def __init__(self, input, encoding=None):
118
        self._calls = [('__init__', input, encoding)]
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
119
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
120
    def __setitem__(self, key, value):
121
        self._calls.append(('__setitem__', key, value))
122
2120.6.4 by James Henstridge
add support for specifying policy when storing options
123
    def __delitem__(self, key):
124
        self._calls.append(('__delitem__', key))
125
126
    def keys(self):
127
        self._calls.append(('keys',))
128
        return []
129
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
130
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
131
        self._calls.append(('write',))
132
2120.6.4 by James Henstridge
add support for specifying policy when storing options
133
    def as_bool(self, value):
134
        self._calls.append(('as_bool', value))
135
        return False
136
137
    def get_value(self, section, name):
138
        self._calls.append(('get_value', section, name))
139
        return None
140
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
141
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
142
class FakeBranch(object):
143
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
144
    def __init__(self, base=None, user_id=None):
145
        if base is None:
146
            self.base = "http://example.com/branches/demo"
147
        else:
148
            self.base = base
149
        self.control_files = FakeControlFiles(user_id=user_id)
150
151
    def lock_write(self):
152
        pass
153
154
    def unlock(self):
155
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
156
157
158
class FakeControlFiles(object):
159
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
160
    def __init__(self, user_id=None):
161
        self.email = user_id
162
        self.files = {}
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
163
1185.65.29 by Robert Collins
Implement final review suggestions.
164
    def get_utf8(self, filename):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
165
        if filename != 'email':
166
            raise NotImplementedError
167
        if self.email is not None:
168
            return StringIO(self.email)
1185.31.45 by John Arbash Meinel
Refactoring Exceptions found some places where the wrong exception was caught.
169
        raise errors.NoSuchFile(filename)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
170
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
171
    def get(self, filename):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
172
        try:
173
            return StringIO(self.files[filename])
174
        except KeyError:
175
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
176
177
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
178
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
179
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
180
181
class InstrumentedConfig(config.Config):
182
    """An instrumented config that supplies stubs for template methods."""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
183
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
184
    def __init__(self):
185
        super(InstrumentedConfig, self).__init__()
186
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
187
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
188
189
    def _get_user_id(self):
190
        self._calls.append('_get_user_id')
191
        return "Robert Collins <robert.collins@example.org>"
192
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
193
    def _get_signature_checking(self):
194
        self._calls.append('_get_signature_checking')
195
        return self._signatures
196
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
197
1556.2.2 by Aaron Bentley
Fixed get_bool
198
bool_config = """[DEFAULT]
199
active = true
200
inactive = false
201
[UPPERCASE]
202
active = True
203
nonactive = False
204
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
205
206
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
207
class TestConfigObj(tests.TestCase):
1556.2.2 by Aaron Bentley
Fixed get_bool
208
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
209
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
210
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
211
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
212
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
213
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
214
215
2900.1.1 by Vincent Ladeuil
216
erroneous_config = """[section] # line 1
217
good=good # line 2
218
[section] # line 3
219
whocares=notme # line 4
220
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
221
222
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
223
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
224
225
    def test_duplicate_section_name_error_line(self):
226
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
227
            co = configobj.ConfigObj(StringIO(erroneous_config),
228
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
229
        except config.configobj.DuplicateError, e:
230
            self.assertEqual(3, e.line_number)
231
        else:
232
            self.fail('Error in config file not detected')
233
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
234
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
235
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
236
237
    def test_constructs(self):
238
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
239
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
240
    def test_no_default_editor(self):
241
        self.assertRaises(NotImplementedError, config.Config().get_editor)
242
243
    def test_user_email(self):
244
        my_config = InstrumentedConfig()
245
        self.assertEqual('robert.collins@example.org', my_config.user_email())
246
        self.assertEqual(['_get_user_id'], my_config._calls)
247
248
    def test_username(self):
249
        my_config = InstrumentedConfig()
250
        self.assertEqual('Robert Collins <robert.collins@example.org>',
251
                         my_config.username())
252
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
253
254
    def test_signatures_default(self):
255
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
256
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
257
        self.assertEqual(config.CHECK_IF_POSSIBLE,
258
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
259
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
260
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
261
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
262
    def test_signatures_template_method(self):
263
        my_config = InstrumentedConfig()
264
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
265
        self.assertEqual(['_get_signature_checking'], my_config._calls)
266
267
    def test_signatures_template_method_none(self):
268
        my_config = InstrumentedConfig()
269
        my_config._signatures = None
270
        self.assertEqual(config.CHECK_IF_POSSIBLE,
271
                         my_config.signature_checking())
272
        self.assertEqual(['_get_signature_checking'], my_config._calls)
273
1442.1.56 by Robert Collins
gpg_signing_command configuration item
274
    def test_gpg_signing_command_default(self):
275
        my_config = config.Config()
276
        self.assertEqual('gpg', my_config.gpg_signing_command())
277
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
278
    def test_get_user_option_default(self):
279
        my_config = config.Config()
280
        self.assertEqual(None, my_config.get_user_option('no_option'))
281
1472 by Robert Collins
post commit hook, first pass implementation
282
    def test_post_commit_default(self):
283
        my_config = config.Config()
284
        self.assertEqual(None, my_config.post_commit())
285
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
286
    def test_log_format_default(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
287
        my_config = config.Config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
288
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
289
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
290
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
291
class TestConfigPath(tests.TestCase):
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
292
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
293
    def setUp(self):
294
        super(TestConfigPath, self).setUp()
295
        os.environ['HOME'] = '/home/bogus'
2309.2.6 by Alexander Belchenko
bzr now use Win32 API to determine Application Data location, and don't rely solely on $APPDATA
296
        if sys.platform == 'win32':
297
            os.environ['BZR_HOME'] = \
298
                r'C:\Documents and Settings\bogus\Application Data'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
299
            self.bzr_home = \
300
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
301
        else:
302
            self.bzr_home = '/home/bogus/.bazaar'
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
303
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
304
    def test_config_dir(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
305
        self.assertEqual(config.config_dir(), self.bzr_home)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
306
307
    def test_config_filename(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
308
        self.assertEqual(config.config_filename(),
309
                         self.bzr_home + '/bazaar.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
310
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
311
    def test_branches_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
312
        self.assertEqual(config.branches_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
313
                         self.bzr_home + '/branches.conf')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
314
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
315
    def test_locations_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
316
        self.assertEqual(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
317
                         self.bzr_home + '/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
318
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
319
    def test_authentication_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
320
        self.assertEqual(config.authentication_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
321
                         self.bzr_home + '/authentication.conf')
322
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
323
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
324
class TestIniConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
325
326
    def test_contructs(self):
327
        my_config = config.IniBasedConfig("nothing")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
328
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
329
    def test_from_fp(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
330
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
331
        my_config = config.IniBasedConfig(None)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
332
        self.failUnless(
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
333
            isinstance(my_config._get_parser(file=config_file),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
334
                        configobj.ConfigObj))
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
335
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
336
    def test_cached(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
337
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
338
        my_config = config.IniBasedConfig(None)
339
        parser = my_config._get_parser(file=config_file)
340
        self.failUnless(my_config._get_parser() is parser)
341
342
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
343
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
344
345
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
346
        my_config = config.GlobalConfig()
347
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
348
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
349
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
350
        oldparserclass = config.ConfigObj
351
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
352
        my_config = config.GlobalConfig()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
353
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
354
            parser = my_config._get_parser()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
355
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
356
            config.ConfigObj = oldparserclass
357
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1551.2.20 by Aaron Bentley
Treated config files as utf-8
358
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
359
                                          'utf-8')])
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
360
361
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
362
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
363
364
    def test_constructs(self):
365
        branch = FakeBranch()
366
        my_config = config.BranchConfig(branch)
367
        self.assertRaises(TypeError, config.BranchConfig)
368
369
    def test_get_location_config(self):
370
        branch = FakeBranch()
371
        my_config = config.BranchConfig(branch)
372
        location_config = my_config._get_location_config()
373
        self.assertEqual(branch.base, location_config.location)
374
        self.failUnless(location_config is my_config._get_location_config())
375
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
376
    def test_get_config(self):
377
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
378
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
379
        my_config = b.get_config()
380
        self.assertIs(my_config.get_user_option('wacky'), None)
381
        my_config.set_user_option('wacky', 'unlikely')
382
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
383
384
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
385
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
386
        my_config2 = b2.get_config()
387
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
388
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
389
    def test_has_explicit_nickname(self):
390
        b = self.make_branch('.')
391
        self.assertFalse(b.get_config().has_explicit_nickname())
392
        b.nick = 'foo'
393
        self.assertTrue(b.get_config().has_explicit_nickname())
394
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
395
    def test_config_url(self):
396
        """The Branch.get_config will use section that uses a local url"""
397
        branch = self.make_branch('branch')
398
        self.assertEqual('branch', branch.nick)
399
400
        locations = config.locations_config_filename()
401
        config.ensure_config_dir_exists()
402
        local_url = urlutils.local_path_to_url('branch')
403
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
404
                                    % (local_url,))
405
        self.assertEqual('foobar', branch.nick)
406
407
    def test_config_local_path(self):
408
        """The Branch.get_config will use a local system path"""
409
        branch = self.make_branch('branch')
410
        self.assertEqual('branch', branch.nick)
411
412
        locations = config.locations_config_filename()
413
        config.ensure_config_dir_exists()
414
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
415
                                    % (osutils.getcwd().encode('utf8'),))
416
        self.assertEqual('barry', branch.nick)
417
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
418
    def test_config_creates_local(self):
419
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
420
        branch = self.make_branch('branch', format='knit')
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
421
        branch.set_push_location('http://foobar')
422
        locations = config.locations_config_filename()
423
        local_path = osutils.getcwd().encode('utf8')
424
        # Surprisingly ConfigObj doesn't create a trailing newline
425
        self.check_file_contents(locations,
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
426
                                 '[%s/branch]\n'
427
                                 'push_location = http://foobar\n'
428
                                 'push_location:policy = norecurse'
429
                                 % (local_path,))
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
430
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
431
    def test_autonick_urlencoded(self):
432
        b = self.make_branch('!repo')
433
        self.assertEqual('!repo', b.get_config().get_nickname())
434
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
435
    def test_warn_if_masked(self):
436
        _warning = trace.warning
437
        warnings = []
438
        def warning(*args):
439
            warnings.append(args[0] % args[1:])
440
441
        def set_option(store, warn_masked=True):
442
            warnings[:] = []
443
            conf.set_user_option('example_option', repr(store), store=store,
444
                                 warn_masked=warn_masked)
445
        def assertWarning(warning):
446
            if warning is None:
447
                self.assertEqual(0, len(warnings))
448
            else:
449
                self.assertEqual(1, len(warnings))
450
                self.assertEqual(warning, warnings[0])
451
        trace.warning = warning
452
        try:
453
            branch = self.make_branch('.')
454
            conf = branch.get_config()
455
            set_option(config.STORE_GLOBAL)
456
            assertWarning(None)
457
            set_option(config.STORE_BRANCH)
458
            assertWarning(None)
459
            set_option(config.STORE_GLOBAL)
460
            assertWarning('Value "4" is masked by "3" from branch.conf')
461
            set_option(config.STORE_GLOBAL, warn_masked=False)
462
            assertWarning(None)
463
            set_option(config.STORE_LOCATION)
464
            assertWarning(None)
465
            set_option(config.STORE_BRANCH)
466
            assertWarning('Value "3" is masked by "0" from locations.conf')
467
            set_option(config.STORE_BRANCH, warn_masked=False)
468
            assertWarning(None)
469
        finally:
470
            trace.warning = _warning
471
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
472
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
473
class TestGlobalConfigItems(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
474
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
475
    def test_user_id(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
476
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
477
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
478
        my_config._parser = my_config._get_parser(file=config_file)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
479
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
480
                         my_config._get_user_id())
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
481
482
    def test_absent_user_id(self):
483
        config_file = StringIO("")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
484
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
485
        my_config._parser = my_config._get_parser(file=config_file)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
486
        self.assertEqual(None, my_config._get_user_id())
487
488
    def test_configured_editor(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
489
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
490
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
491
        my_config._parser = my_config._get_parser(file=config_file)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
492
        self.assertEqual("vim", my_config.get_editor())
493
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
494
    def test_signatures_always(self):
495
        config_file = StringIO(sample_always_signatures)
496
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
497
        my_config._parser = my_config._get_parser(file=config_file)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
498
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
499
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
500
        self.assertEqual(config.SIGN_ALWAYS,
501
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
502
        self.assertEqual(True, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
503
504
    def test_signatures_if_possible(self):
505
        config_file = StringIO(sample_maybe_signatures)
506
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
507
        my_config._parser = my_config._get_parser(file=config_file)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
508
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
509
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
510
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
511
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
512
        self.assertEqual(False, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
513
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
514
    def test_signatures_ignore(self):
515
        config_file = StringIO(sample_ignore_signatures)
516
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
517
        my_config._parser = my_config._get_parser(file=config_file)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
518
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
519
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
520
        self.assertEqual(config.SIGN_NEVER,
521
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
522
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
523
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
524
    def _get_sample_config(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
525
        config_file = StringIO(sample_config_text.encode('utf-8'))
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
526
        my_config = config.GlobalConfig()
527
        my_config._parser = my_config._get_parser(file=config_file)
528
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
529
1442.1.56 by Robert Collins
gpg_signing_command configuration item
530
    def test_gpg_signing_command(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
531
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
532
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
533
        self.assertEqual(False, my_config.signature_needed())
534
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
535
    def _get_empty_config(self):
536
        config_file = StringIO("")
537
        my_config = config.GlobalConfig()
538
        my_config._parser = my_config._get_parser(file=config_file)
539
        return my_config
540
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
541
    def test_gpg_signing_command_unset(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
542
        my_config = self._get_empty_config()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
543
        self.assertEqual("gpg", my_config.gpg_signing_command())
544
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
545
    def test_get_user_option_default(self):
546
        my_config = self._get_empty_config()
547
        self.assertEqual(None, my_config.get_user_option('no_option'))
548
549
    def test_get_user_option_global(self):
550
        my_config = self._get_sample_config()
551
        self.assertEqual("something",
552
                         my_config.get_user_option('user_global_option'))
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
553
1472 by Robert Collins
post commit hook, first pass implementation
554
    def test_post_commit_default(self):
555
        my_config = self._get_sample_config()
556
        self.assertEqual(None, my_config.post_commit())
557
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
558
    def test_configured_logformat(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
559
        my_config = self._get_sample_config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
560
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
561
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
562
    def test_get_alias(self):
563
        my_config = self._get_sample_config()
564
        self.assertEqual('help', my_config.get_alias('h'))
565
566
    def test_get_no_alias(self):
567
        my_config = self._get_sample_config()
568
        self.assertEqual(None, my_config.get_alias('foo'))
569
570
    def test_get_long_alias(self):
571
        my_config = self._get_sample_config()
572
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
573
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
574
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
575
class TestLocationConfig(tests.TestCaseInTempDir):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
576
577
    def test_constructs(self):
578
        my_config = config.LocationConfig('http://example.com')
579
        self.assertRaises(TypeError, config.LocationConfig)
580
581
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
582
        # This is testing the correct file names are provided.
583
        # TODO: consolidate with the test for GlobalConfigs filename checks.
584
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
585
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
586
        oldparserclass = config.ConfigObj
587
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
588
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
589
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
590
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
591
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
592
            config.ConfigObj = oldparserclass
593
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
594
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
595
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
596
                           'utf-8')])
1711.4.29 by John Arbash Meinel
Alexander Belchenko, fix test_config to use ensure_config_dir, rather than os.mkdir()
597
        config.ensure_config_dir_exists()
598
        #os.mkdir(config.config_dir())
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
599
        f = file(config.branches_config_filename(), 'wb')
600
        f.write('')
601
        f.close()
602
        oldparserclass = config.ConfigObj
603
        config.ConfigObj = InstrumentedConfigObj
604
        try:
605
            my_config = config.LocationConfig('http://www.example.com')
606
            parser = my_config._get_parser()
607
        finally:
608
            config.ConfigObj = oldparserclass
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
609
610
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
611
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
612
        global_config = my_config._get_global_config()
613
        self.failUnless(isinstance(global_config, config.GlobalConfig))
614
        self.failUnless(global_config is my_config._get_global_config())
615
1993.3.1 by James Henstridge
first go at making location config lookup recursive
616
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
617
        self.get_branch_config('/')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
618
        self.assertEqual([], self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
619
1993.3.1 by James Henstridge
first go at making location config lookup recursive
620
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
621
        self.get_branch_config('http://www.example.com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
622
        self.assertEqual([('http://www.example.com', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
623
                         self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
624
1993.3.1 by James Henstridge
first go at making location config lookup recursive
625
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
626
        self.get_branch_config('http://www.example.com-com')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
627
        self.assertEqual([], self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
628
1993.3.1 by James Henstridge
first go at making location config lookup recursive
629
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
630
        self.get_branch_config('http://www.example.com/com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
631
        self.assertEqual([('http://www.example.com', 'com')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
632
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
633
1993.3.5 by James Henstridge
add back recurse=False option to config file
634
    def test__get_matching_sections_ignoreparent(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
635
        self.get_branch_config('http://www.example.com/ignoreparent')
636
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
637
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
638
1993.3.5 by James Henstridge
add back recurse=False option to config file
639
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
640
        self.get_branch_config(
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
641
            'http://www.example.com/ignoreparent/childbranch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
642
        self.assertEqual([('http://www.example.com/ignoreparent',
643
                           'childbranch')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
644
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
645
1993.3.1 by James Henstridge
first go at making location config lookup recursive
646
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
647
        self.get_branch_config('/b')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
648
        self.assertEqual([('/b/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
649
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
650
1993.3.1 by James Henstridge
first go at making location config lookup recursive
651
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
652
        self.get_branch_config('/a/foo')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
653
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
654
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
655
1993.3.1 by James Henstridge
first go at making location config lookup recursive
656
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
657
        self.get_branch_config('/a/foo/bar')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
658
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
659
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
660
1993.3.1 by James Henstridge
first go at making location config lookup recursive
661
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
662
        self.get_branch_config('/a/')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
663
        self.assertEqual([('/a/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
664
                         self.my_location_config._get_matching_sections())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
665
1993.3.1 by James Henstridge
first go at making location config lookup recursive
666
    def test__get_matching_sections_explicit_over_glob(self):
667
        # XXX: 2006-09-08 jamesh
668
        # This test only passes because ord('c') > ord('*').  If there
669
        # was a config section for '/a/?', it would get precedence
670
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
671
        self.get_branch_config('/a/c')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
672
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
673
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
674
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
675
    def test__get_option_policy_normal(self):
676
        self.get_branch_config('http://www.example.com')
677
        self.assertEqual(
678
            self.my_location_config._get_config_policy(
679
            'http://www.example.com', 'normal_option'),
680
            config.POLICY_NONE)
681
682
    def test__get_option_policy_norecurse(self):
683
        self.get_branch_config('http://www.example.com')
684
        self.assertEqual(
685
            self.my_location_config._get_option_policy(
686
            'http://www.example.com', 'norecurse_option'),
687
            config.POLICY_NORECURSE)
688
        # Test old recurse=False setting:
689
        self.assertEqual(
690
            self.my_location_config._get_option_policy(
691
            'http://www.example.com/norecurse', 'normal_option'),
692
            config.POLICY_NORECURSE)
693
694
    def test__get_option_policy_normal(self):
695
        self.get_branch_config('http://www.example.com')
696
        self.assertEqual(
697
            self.my_location_config._get_option_policy(
698
            'http://www.example.com', 'appendpath_option'),
699
            config.POLICY_APPENDPATH)
700
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
701
    def test_location_without_username(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
702
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
703
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
704
                         self.my_config.username())
705
706
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
707
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
708
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
709
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
710
                         self.my_config.username())
711
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
712
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
713
        self.get_branch_config('http://www.example.com/foo')
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
714
        self.assertEqual('Robert Collins <robertc@example.org>',
715
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
716
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
717
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
718
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
719
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
720
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
721
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
722
        self.assertEqual(config.SIGN_NEVER,
723
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
724
725
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
726
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
727
        self.assertEqual(config.CHECK_NEVER,
728
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
729
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
730
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
731
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
732
        self.assertEqual(config.CHECK_IF_POSSIBLE,
733
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
734
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
735
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
736
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
737
        self.assertEqual(config.CHECK_ALWAYS,
738
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
739
1442.1.56 by Robert Collins
gpg_signing_command configuration item
740
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
741
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
742
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
743
744
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
745
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
746
        self.assertEqual("false", self.my_config.gpg_signing_command())
747
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
748
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
749
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
750
        self.assertEqual('something',
751
                         self.my_config.get_user_option('user_global_option'))
752
753
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
754
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
755
        self.assertEqual('local',
756
                         self.my_config.get_user_option('user_local_option'))
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
757
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
758
    def test_get_user_option_appendpath(self):
759
        # returned as is for the base path:
760
        self.get_branch_config('http://www.example.com')
761
        self.assertEqual('append',
762
                         self.my_config.get_user_option('appendpath_option'))
763
        # Extra path components get appended:
764
        self.get_branch_config('http://www.example.com/a/b/c')
765
        self.assertEqual('append/a/b/c',
766
                         self.my_config.get_user_option('appendpath_option'))
767
        # Overriden for http://www.example.com/dir, where it is a
768
        # normal option:
769
        self.get_branch_config('http://www.example.com/dir/a/b/c')
770
        self.assertEqual('normal',
771
                         self.my_config.get_user_option('appendpath_option'))
772
773
    def test_get_user_option_norecurse(self):
774
        self.get_branch_config('http://www.example.com')
775
        self.assertEqual('norecurse',
776
                         self.my_config.get_user_option('norecurse_option'))
777
        self.get_branch_config('http://www.example.com/dir')
778
        self.assertEqual(None,
779
                         self.my_config.get_user_option('norecurse_option'))
780
        # http://www.example.com/norecurse is a recurse=False section
781
        # that redefines normal_option.  Subdirectories do not pick up
782
        # this redefinition.
783
        self.get_branch_config('http://www.example.com/norecurse')
784
        self.assertEqual('norecurse',
785
                         self.my_config.get_user_option('normal_option'))
786
        self.get_branch_config('http://www.example.com/norecurse/subdir')
787
        self.assertEqual('normal',
788
                         self.my_config.get_user_option('normal_option'))
789
2120.6.4 by James Henstridge
add support for specifying policy when storing options
790
    def test_set_user_option_norecurse(self):
791
        self.get_branch_config('http://www.example.com')
792
        self.my_config.set_user_option('foo', 'bar',
793
                                       store=config.STORE_LOCATION_NORECURSE)
794
        self.assertEqual(
795
            self.my_location_config._get_option_policy(
796
            'http://www.example.com', 'foo'),
797
            config.POLICY_NORECURSE)
798
799
    def test_set_user_option_appendpath(self):
800
        self.get_branch_config('http://www.example.com')
801
        self.my_config.set_user_option('foo', 'bar',
802
                                       store=config.STORE_LOCATION_APPENDPATH)
803
        self.assertEqual(
804
            self.my_location_config._get_option_policy(
805
            'http://www.example.com', 'foo'),
806
            config.POLICY_APPENDPATH)
807
808
    def test_set_user_option_change_policy(self):
809
        self.get_branch_config('http://www.example.com')
810
        self.my_config.set_user_option('norecurse_option', 'normal',
811
                                       store=config.STORE_LOCATION)
812
        self.assertEqual(
813
            self.my_location_config._get_option_policy(
814
            'http://www.example.com', 'norecurse_option'),
815
            config.POLICY_NONE)
816
817
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
818
        # The following section has recurse=False set.  The test is to
819
        # make sure that a normal option can be added to the section,
820
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
821
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
822
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
823
                             'The section "http://www.example.com/norecurse" '
824
                             'has been converted to use policies.'],
825
                            self.my_config.set_user_option,
826
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
827
        self.assertEqual(
828
            self.my_location_config._get_option_policy(
829
            'http://www.example.com/norecurse', 'foo'),
830
            config.POLICY_NONE)
831
        # The previously existing option is still norecurse:
832
        self.assertEqual(
833
            self.my_location_config._get_option_policy(
834
            'http://www.example.com/norecurse', 'normal_option'),
835
            config.POLICY_NORECURSE)
836
1472 by Robert Collins
post commit hook, first pass implementation
837
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
838
        self.get_branch_config('/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
839
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
840
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
841
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
842
    def get_branch_config(self, location, global_config=None):
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
843
        if global_config is None:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
844
            global_file = StringIO(sample_config_text.encode('utf-8'))
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
845
        else:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
846
            global_file = StringIO(global_config.encode('utf-8'))
847
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
848
        self.my_config = config.BranchConfig(FakeBranch(location))
849
        # Force location config to use specified file
850
        self.my_location_config = self.my_config._get_location_config()
851
        self.my_location_config._get_parser(branches_file)
852
        # Force global config to use specified file
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
853
        self.my_config._get_global_config()._get_parser(global_file)
854
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
855
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
856
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
857
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
858
        self.my_location_config._parser = record
1185.62.6 by John Arbash Meinel
Updated test_set_user_setting_sets_and_saves to remove the print statement, and make sure it is doing the right thing
859
860
        real_mkdir = os.mkdir
861
        self.created = False
862
        def checked_mkdir(path, mode=0777):
863
            self.log('making directory: %s', path)
864
            real_mkdir(path, mode)
865
            self.created = True
866
867
        os.mkdir = checked_mkdir
868
        try:
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
869
            self.callDeprecated(['The recurse option is deprecated as of '
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
870
                                 '0.14.  The section "/a/c" has been '
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
871
                                 'converted to use policies.'],
872
                                self.my_config.set_user_option,
873
                                'foo', 'bar', store=config.STORE_LOCATION)
1185.62.6 by John Arbash Meinel
Updated test_set_user_setting_sets_and_saves to remove the print statement, and make sure it is doing the right thing
874
        finally:
875
            os.mkdir = real_mkdir
876
877
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
878
        self.assertEqual([('__contains__', '/a/c'),
879
                          ('__contains__', '/a/c/'),
880
                          ('__setitem__', '/a/c', {}),
881
                          ('__getitem__', '/a/c'),
882
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
883
                          ('__getitem__', '/a/c'),
884
                          ('as_bool', 'recurse'),
885
                          ('__getitem__', '/a/c'),
886
                          ('__delitem__', 'recurse'),
887
                          ('__getitem__', '/a/c'),
888
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
889
                          ('__getitem__', '/a/c'),
890
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
891
                          ('write',)],
892
                         record._calls[1:])
893
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
894
    def test_set_user_setting_sets_and_saves2(self):
895
        self.get_branch_config('/a/c')
896
        self.assertIs(self.my_config.get_user_option('foo'), None)
897
        self.my_config.set_user_option('foo', 'bar')
898
        self.assertEqual(
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
899
            self.my_config.branch.control_files.files['branch.conf'],
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
900
            'foo = bar')
901
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
902
        self.my_config.set_user_option('foo', 'baz',
903
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
904
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
905
        self.my_config.set_user_option('foo', 'qux')
906
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
907
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
908
    def test_get_bzr_remote_path(self):
909
        my_config = config.LocationConfig('/a/c')
910
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
911
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
912
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
913
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
914
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
915
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
916
1770.2.8 by Aaron Bentley
Add precedence test
917
precedence_global = 'option = global'
918
precedence_branch = 'option = branch'
919
precedence_location = """
920
[http://]
921
recurse = true
922
option = recurse
923
[http://example.com/specific]
924
option = exact
925
"""
926
927
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
928
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
929
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
930
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
931
                          location_config=None, branch_data_config=None):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
932
        my_config = config.BranchConfig(FakeBranch(location))
933
        if global_config is not None:
934
            global_file = StringIO(global_config.encode('utf-8'))
935
            my_config._get_global_config()._get_parser(global_file)
936
        self.my_location_config = my_config._get_location_config()
937
        if location_config is not None:
938
            location_file = StringIO(location_config.encode('utf-8'))
939
            self.my_location_config._get_parser(location_file)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
940
        if branch_data_config is not None:
941
            my_config.branch.control_files.files['branch.conf'] = \
942
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
943
        return my_config
944
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
945
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
946
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
947
        my_config = config.BranchConfig(branch)
948
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
949
                         my_config.username())
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
950
        branch.control_files.email = "John"
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
951
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
952
                                  "Robert Collins <robertc@example.org>")
953
        self.assertEqual("John", my_config.username())
954
        branch.control_files.email = None
955
        self.assertEqual("Robert Collins <robertc@example.org>",
956
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
957
958
    def test_not_set_in_branch(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
959
        my_config = self.get_branch_config(sample_config_text)
960
        my_config.branch.control_files.email = None
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
961
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
962
                         my_config._get_user_id())
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
963
        my_config.branch.control_files.email = "John"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
964
        self.assertEqual("John", my_config._get_user_id())
965
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
966
    def test_BZR_EMAIL_OVERRIDES(self):
967
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
968
        branch = FakeBranch()
969
        my_config = config.BranchConfig(branch)
970
        self.assertEqual("Robert Collins <robertc@example.org>",
971
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
972
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
973
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
974
        my_config = self.get_branch_config(
975
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
976
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
977
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
978
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
979
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
980
    def test_signatures_forced_branch(self):
981
        my_config = self.get_branch_config(
982
            global_config=sample_ignore_signatures,
983
            branch_data_config=sample_always_signatures)
984
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
985
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
986
        self.assertTrue(my_config.signature_needed())
987
1442.1.56 by Robert Collins
gpg_signing_command configuration item
988
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
989
        my_config = self.get_branch_config(
990
            # branch data cannot set gpg_signing_command
991
            branch_data_config="gpg_signing_command=pgp")
1551.2.20 by Aaron Bentley
Treated config files as utf-8
992
        config_file = StringIO(sample_config_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
993
        my_config._get_global_config()._get_parser(config_file)
1442.1.56 by Robert Collins
gpg_signing_command configuration item
994
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
995
996
    def test_get_user_option_global(self):
997
        branch = FakeBranch()
998
        my_config = config.BranchConfig(branch)
1551.2.20 by Aaron Bentley
Treated config files as utf-8
999
        config_file = StringIO(sample_config_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1000
        (my_config._get_global_config()._get_parser(config_file))
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1001
        self.assertEqual('something',
1002
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1003
1004
    def test_post_commit_default(self):
1005
        branch = FakeBranch()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1006
        my_config = self.get_branch_config(sample_config_text, '/a/c',
1007
                                           sample_branches_text)
1008
        self.assertEqual(my_config.branch.base, '/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
1009
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1010
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1011
        my_config.set_user_option('post_commit', 'rmtree_root')
1012
        # post-commit is ignored when bresent in branch data
1013
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1014
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1015
        my_config.set_user_option('post_commit', 'rmtree_root',
1016
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1017
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1018
1770.2.8 by Aaron Bentley
Add precedence test
1019
    def test_config_precedence(self):
1020
        my_config = self.get_branch_config(global_config=precedence_global)
1021
        self.assertEqual(my_config.get_user_option('option'), 'global')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1022
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1023
                                      branch_data_config=precedence_branch)
1024
        self.assertEqual(my_config.get_user_option('option'), 'branch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1025
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1026
                                      branch_data_config=precedence_branch,
1027
                                      location_config=precedence_location)
1028
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1029
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1030
                                      branch_data_config=precedence_branch,
1031
                                      location_config=precedence_location,
1032
                                      location='http://example.com/specific')
1033
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1034
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1035
    def test_get_mail_client(self):
1036
        config = self.get_branch_config()
1037
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1038
        self.assertIsInstance(client, mail_client.DefaultMail)
1039
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1040
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1041
        config.set_user_option('mail_client', 'evolution')
1042
        client = config.get_mail_client()
1043
        self.assertIsInstance(client, mail_client.Evolution)
1044
2681.5.1 by ghigo
Add KMail support to bzr send
1045
        config.set_user_option('mail_client', 'kmail')
1046
        client = config.get_mail_client()
1047
        self.assertIsInstance(client, mail_client.KMail)
1048
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1049
        config.set_user_option('mail_client', 'mutt')
1050
        client = config.get_mail_client()
1051
        self.assertIsInstance(client, mail_client.Mutt)
1052
1053
        config.set_user_option('mail_client', 'thunderbird')
1054
        client = config.get_mail_client()
1055
        self.assertIsInstance(client, mail_client.Thunderbird)
1056
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1057
        # Generic options
1058
        config.set_user_option('mail_client', 'default')
1059
        client = config.get_mail_client()
1060
        self.assertIsInstance(client, mail_client.DefaultMail)
1061
1062
        config.set_user_option('mail_client', 'editor')
1063
        client = config.get_mail_client()
1064
        self.assertIsInstance(client, mail_client.Editor)
1065
1066
        config.set_user_option('mail_client', 'mapi')
1067
        client = config.get_mail_client()
1068
        self.assertIsInstance(client, mail_client.MAPIClient)
1069
2681.1.23 by Aaron Bentley
Add support for xdg-email
1070
        config.set_user_option('mail_client', 'xdg-email')
1071
        client = config.get_mail_client()
1072
        self.assertIsInstance(client, mail_client.XDGEmail)
1073
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1074
        config.set_user_option('mail_client', 'firebird')
1075
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1076
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1077
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1078
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1079
1080
    def test_extract_email_address(self):
1081
        self.assertEqual('jane@test.com',
1082
                         config.extract_email_address('Jane <jane@test.com>'))
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
1083
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1084
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1085
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1086
    def test_parse_username(self):
1087
        self.assertEqual(('', 'jdoe@example.com'),
1088
                         config.parse_username('jdoe@example.com'))
1089
        self.assertEqual(('', 'jdoe@example.com'),
1090
                         config.parse_username('<jdoe@example.com>'))
1091
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1092
                         config.parse_username('John Doe <jdoe@example.com>'))
1093
        self.assertEqual(('John Doe', ''),
1094
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1095
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1096
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1097
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1098
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1099
1100
    def test_get_value(self):
1101
        """Test that retreiving a value from a section is possible"""
1102
        branch = self.make_branch('.')
1103
        tree_config = config.TreeConfig(branch)
1104
        tree_config.set_option('value', 'key', 'SECTION')
1105
        tree_config.set_option('value2', 'key2')
1106
        tree_config.set_option('value3-top', 'key3')
1107
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1108
        value = tree_config.get_option('key', 'SECTION')
1109
        self.assertEqual(value, 'value')
1110
        value = tree_config.get_option('key2')
1111
        self.assertEqual(value, 'value2')
1112
        self.assertEqual(tree_config.get_option('non-existant'), None)
1113
        value = tree_config.get_option('non-existant', 'SECTION')
1114
        self.assertEqual(value, None)
1115
        value = tree_config.get_option('non-existant', default='default')
1116
        self.assertEqual(value, 'default')
1117
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1118
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1119
        self.assertEqual(value, 'default')
1120
        value = tree_config.get_option('key3')
1121
        self.assertEqual(value, 'value3-top')
1122
        value = tree_config.get_option('key3', 'SECTION')
1123
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1124
1125
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1126
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1127
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1128
1129
    def _got_user_passwd(self, expected_user, expected_password,
1130
                         config, *args, **kwargs):
1131
        credentials = config.get_credentials(*args, **kwargs)
1132
        if credentials is None:
1133
            user = None
1134
            password = None
1135
        else:
1136
            user = credentials['user']
1137
            password = credentials['password']
1138
        self.assertEquals(expected_user, user)
1139
        self.assertEquals(expected_password, password)
1140
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1141
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1142
        conf = config.AuthenticationConfig(_file=StringIO())
1143
        self.assertEquals({}, conf._get_config())
1144
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1145
1146
    def test_broken_config(self):
1147
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1148
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1149
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1150
        conf = config.AuthenticationConfig(_file=StringIO(
1151
                """[broken]
1152
scheme=ftp
1153
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1154
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1155
"""))
1156
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.22 by Vincent Ladeuil
Polishing.
1157
        conf = config.AuthenticationConfig(_file=StringIO(
1158
                """[broken]
1159
scheme=ftp
1160
user=joe
1161
port=port # Error: Not an int
1162
"""))
1163
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1164
1165
    def test_credentials_for_scheme_host(self):
1166
        conf = config.AuthenticationConfig(_file=StringIO(
1167
                """# Identity on foo.net
1168
[ftp definition]
1169
scheme=ftp
1170
host=foo.net
1171
user=joe
1172
password=secret-pass
1173
"""))
1174
        # Basic matching
1175
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1176
        # different scheme
1177
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1178
        # different host
1179
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1180
1181
    def test_credentials_for_host_port(self):
1182
        conf = config.AuthenticationConfig(_file=StringIO(
1183
                """# Identity on foo.net
1184
[ftp definition]
1185
scheme=ftp
1186
port=10021
1187
host=foo.net
1188
user=joe
1189
password=secret-pass
1190
"""))
1191
        # No port
1192
        self._got_user_passwd('joe', 'secret-pass',
1193
                              conf, 'ftp', 'foo.net', port=10021)
1194
        # different port
1195
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1196
1197
    def test_for_matching_host(self):
1198
        conf = config.AuthenticationConfig(_file=StringIO(
1199
                """# Identity on foo.net
1200
[sourceforge]
1201
scheme=bzr
1202
host=bzr.sf.net
1203
user=joe
1204
password=joepass
1205
[sourceforge domain]
1206
scheme=bzr
1207
host=.bzr.sf.net
1208
user=georges
1209
password=bendover
1210
"""))
1211
        # matching domain
1212
        self._got_user_passwd('georges', 'bendover',
1213
                              conf, 'bzr', 'foo.bzr.sf.net')
1214
        # phishing attempt
1215
        self._got_user_passwd(None, None,
1216
                              conf, 'bzr', 'bbzr.sf.net')
1217
1218
    def test_for_matching_host_None(self):
1219
        conf = config.AuthenticationConfig(_file=StringIO(
1220
                """# Identity on foo.net
1221
[catchup bzr]
1222
scheme=bzr
1223
user=joe
1224
password=joepass
1225
[DEFAULT]
1226
user=georges
1227
password=bendover
1228
"""))
1229
        # match no host
1230
        self._got_user_passwd('joe', 'joepass',
1231
                              conf, 'bzr', 'quux.net')
1232
        # no host but different scheme
1233
        self._got_user_passwd('georges', 'bendover',
1234
                              conf, 'ftp', 'quux.net')
1235
1236
    def test_credentials_for_path(self):
1237
        conf = config.AuthenticationConfig(_file=StringIO(
1238
                """
1239
[http dir1]
1240
scheme=http
1241
host=bar.org
1242
path=/dir1
1243
user=jim
1244
password=jimpass
1245
[http dir2]
1246
scheme=http
1247
host=bar.org
1248
path=/dir2
1249
user=georges
1250
password=bendover
1251
"""))
1252
        # no path no dice
1253
        self._got_user_passwd(None, None,
1254
                              conf, 'http', host='bar.org', path='/dir3')
1255
        # matching path
1256
        self._got_user_passwd('georges', 'bendover',
1257
                              conf, 'http', host='bar.org', path='/dir2')
1258
        # matching subdir
1259
        self._got_user_passwd('jim', 'jimpass',
1260
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1261
1262
    def test_credentials_for_user(self):
1263
        conf = config.AuthenticationConfig(_file=StringIO(
1264
                """
1265
[with user]
1266
scheme=http
1267
host=bar.org
1268
user=jim
1269
password=jimpass
1270
"""))
1271
        # Get user
1272
        self._got_user_passwd('jim', 'jimpass',
1273
                              conf, 'http', 'bar.org')
1274
        # Get same user
1275
        self._got_user_passwd('jim', 'jimpass',
1276
                              conf, 'http', 'bar.org', user='jim')
1277
        # Don't get a different user if one is specified
1278
        self._got_user_passwd(None, None,
1279
                              conf, 'http', 'bar.org', user='georges')
1280
1281
    def test_verify_certificates(self):
1282
        conf = config.AuthenticationConfig(_file=StringIO(
1283
                """
1284
[self-signed]
1285
scheme=https
1286
host=bar.org
1287
user=jim
1288
password=jimpass
1289
verify_certificates=False
1290
[normal]
1291
scheme=https
1292
host=foo.net
1293
user=georges
1294
password=bendover
1295
"""))
1296
        credentials = conf.get_credentials('https', 'bar.org')
1297
        self.assertEquals(False, credentials.get('verify_certificates'))
1298
        credentials = conf.get_credentials('https', 'foo.net')
1299
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1300
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1301
2900.2.14 by Vincent Ladeuil
More tests.
1302
class TestAuthenticationConfig(tests.TestCase):
1303
    """Test AuthenticationConfig behaviour"""
1304
1305
    def _check_default_prompt(self, expected_prompt_format, scheme,
1306
                              host=None, port=None, realm=None, path=None):
1307
        if host is None:
1308
            host = 'bar.org'
1309
        user, password = 'jim', 'precious'
1310
        expected_prompt = expected_prompt_format % {
1311
            'scheme': scheme, 'host': host, 'port': port,
1312
            'user': user, 'realm': realm}
1313
1314
        stdout = tests.StringIOWrapper()
1315
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
1316
                                            stdout=stdout)
1317
        # We use an empty conf so that the user is always prompted
1318
        conf = config.AuthenticationConfig()
1319
        self.assertEquals(password,
1320
                          conf.get_password(scheme, host, user, port=port,
1321
                                            realm=realm, path=path))
1322
        self.assertEquals(stdout.getvalue(), expected_prompt)
1323
1324
    def test_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1325
        # HTTP prompts can't be tested here, see test_http.py
2900.2.14 by Vincent Ladeuil
More tests.
1326
        self._check_default_prompt('FTP %(user)s@%(host)s password: ', 'ftp')
1327
        self._check_default_prompt('FTP %(user)s@%(host)s:%(port)d password: ',
1328
                                   'ftp', port=10020)
1329
1330
        self._check_default_prompt('SSH %(user)s@%(host)s:%(port)d password: ',
1331
                                   'ssh', port=12345)
1332
        # SMTP port handling is a bit special (it's handled if embedded in the
1333
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
1334
        # FIXME: should we: forbid that, extend it to other schemes, leave
1335
        # things as they are that's fine thank you ?
2900.2.14 by Vincent Ladeuil
More tests.
1336
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1337
                                   'smtp')
1338
        self._check_default_prompt('SMTP %(user)s@%(host)s password: ',
1339
                                   'smtp', host='bar.org:10025')
1340
        self._check_default_prompt(
1341
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1342
            'smtp', port=10025)
1343
1344
1345
# FIXME: Once we have a way to declare authentication to all test servers, we
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1346
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1347
# test_user_password_in_url
1348
# test_user_in_url_password_from_config
1349
# test_user_in_url_password_prompted
1350
# test_user_in_config
1351
# test_user_getpass.getuser
1352
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1353
class TestAuthenticationRing(tests.TestCaseWithTransport):
1354
    pass