/brz/remove-bazaar

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