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