/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
16
17
"""Tests for finding and reading the bzr config file[s]."""
18
# import system imports here
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
19
from cStringIO import StringIO
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
20
import os
21
import sys
22
23
#import bzrlib specific imports here
1878.1.3 by John Arbash Meinel
some test cleanups
24
from bzrlib import (
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
25
    branch,
26
    bzrdir,
1878.1.3 by John Arbash Meinel
some test cleanups
27
    config,
4603.1.10 by Aaron Bentley
Provide change editor via config.
28
    diff,
1878.1.3 by John Arbash Meinel
some test cleanups
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
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
46
change_editor=vimdiff -of @new_path @old_path
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
47
gpg_signing_command=gnome-gpg
48
log_format=short
49
user_global_option=something
50
[ALIASES]
51
h=help
52
ll=""" + sample_long_alias + "\n"
53
54
55
sample_always_signatures = """
56
[DEFAULT]
57
check_signatures=ignore
58
create_signatures=always
59
"""
60
61
sample_ignore_signatures = """
62
[DEFAULT]
63
check_signatures=require
64
create_signatures=never
65
"""
66
67
sample_maybe_signatures = """
68
[DEFAULT]
69
check_signatures=ignore
70
create_signatures=when-required
71
"""
72
73
sample_branches_text = """
74
[http://www.example.com]
75
# Top level policy
76
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
77
normal_option = normal
78
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
79
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
80
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
81
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
82
[http://www.example.com/ignoreparent]
83
# different project: ignore parent dir config
84
ignore_parents=true
85
[http://www.example.com/norecurse]
86
# configuration items that only apply to this dir
87
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
88
normal_option = norecurse
89
[http://www.example.com/dir]
90
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
91
[/b/]
92
check_signatures=require
93
# test trailing / matching with no children
94
[/a/]
95
check_signatures=check-available
96
gpg_signing_command=false
97
user_local_option=local
98
# test trailing / matching
99
[/a/*]
100
#subdirs will match but not the parent
101
[/a/c]
102
check_signatures=ignore
103
post_commit=bzrlib.tests.test_config.post_commit
104
#testing explicit beats globs
105
"""
1553.6.3 by Erik Bågfors
tests for AliasesConfig
106
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
107
1474 by Robert Collins
Merge from Aaron Bentley.
108
class InstrumentedConfigObj(object):
109
    """A config obj look-enough-alike to record calls made to it."""
110
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
111
    def __contains__(self, thing):
112
        self._calls.append(('__contains__', thing))
113
        return False
114
115
    def __getitem__(self, key):
116
        self._calls.append(('__getitem__', key))
117
        return self
118
1551.2.20 by Aaron Bentley
Treated config files as utf-8
119
    def __init__(self, input, encoding=None):
120
        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.
121
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
122
    def __setitem__(self, key, value):
123
        self._calls.append(('__setitem__', key, value))
124
2120.6.4 by James Henstridge
add support for specifying policy when storing options
125
    def __delitem__(self, key):
126
        self._calls.append(('__delitem__', key))
127
128
    def keys(self):
129
        self._calls.append(('keys',))
130
        return []
131
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
132
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
133
        self._calls.append(('write',))
134
2120.6.4 by James Henstridge
add support for specifying policy when storing options
135
    def as_bool(self, value):
136
        self._calls.append(('as_bool', value))
137
        return False
138
139
    def get_value(self, section, name):
140
        self._calls.append(('get_value', section, name))
141
        return None
142
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
143
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
144
class FakeBranch(object):
145
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
146
    def __init__(self, base=None, user_id=None):
147
        if base is None:
148
            self.base = "http://example.com/branches/demo"
149
        else:
150
            self.base = base
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
151
        self._transport = self.control_files = \
152
            FakeControlFilesAndTransport(user_id=user_id)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
153
4226.1.7 by Robert Collins
Alter test_config.FakeBranch in accordance with the Branch change to have a _get_config.
154
    def _get_config(self):
155
        return config.TransportConfig(self._transport, 'branch.conf')
156
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
157
    def lock_write(self):
158
        pass
159
160
    def unlock(self):
161
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
162
163
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
164
class FakeControlFilesAndTransport(object):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
165
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
166
    def __init__(self, user_id=None):
167
        self.files = {}
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
168
        if user_id:
169
            self.files['email'] = user_id
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
170
        self._transport = self
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
171
1185.65.29 by Robert Collins
Implement final review suggestions.
172
    def get_utf8(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
173
        # from LockableFiles
174
        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
175
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
176
    def get(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
177
        # from Transport
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
178
        try:
179
            return StringIO(self.files[filename])
180
        except KeyError:
181
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
182
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
183
    def get_bytes(self, filename):
184
        # from Transport
185
        try:
186
            return self.files[filename]
187
        except KeyError:
188
            raise errors.NoSuchFile(filename)
189
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
190
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
191
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
192
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
193
    def put_file(self, filename, fileobj):
194
        return self.put(filename, fileobj)
195
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
196
197
class InstrumentedConfig(config.Config):
198
    """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.
199
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
200
    def __init__(self):
201
        super(InstrumentedConfig, self).__init__()
202
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
203
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
204
205
    def _get_user_id(self):
206
        self._calls.append('_get_user_id')
207
        return "Robert Collins <robert.collins@example.org>"
208
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
209
    def _get_signature_checking(self):
210
        self._calls.append('_get_signature_checking')
211
        return self._signatures
212
4603.1.10 by Aaron Bentley
Provide change editor via config.
213
    def _get_change_editor(self):
214
        self._calls.append('_get_change_editor')
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
215
        return 'vimdiff -fo @new_path @old_path'
4603.1.10 by Aaron Bentley
Provide change editor via config.
216
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
217
1556.2.2 by Aaron Bentley
Fixed get_bool
218
bool_config = """[DEFAULT]
219
active = true
220
inactive = false
221
[UPPERCASE]
222
active = True
223
nonactive = False
224
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
225
226
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
227
class TestConfigObj(tests.TestCase):
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
228
1556.2.2 by Aaron Bentley
Fixed get_bool
229
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
230
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
231
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
232
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
233
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
234
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
235
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
236
    def test_hash_sign_in_value(self):
237
        """
238
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
239
        treated as comments when read in again. (#86838)
240
        """
241
        co = config.ConfigObj()
242
        co['test'] = 'foo#bar'
243
        lines = co.write()
244
        self.assertEqual(lines, ['test = "foo#bar"'])
245
        co2 = config.ConfigObj(lines)
246
        self.assertEqual(co2['test'], 'foo#bar')
247
1556.2.2 by Aaron Bentley
Fixed get_bool
248
2900.1.1 by Vincent Ladeuil
249
erroneous_config = """[section] # line 1
250
good=good # line 2
251
[section] # line 3
252
whocares=notme # line 4
253
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
254
255
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
256
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
257
258
    def test_duplicate_section_name_error_line(self):
259
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
260
            co = configobj.ConfigObj(StringIO(erroneous_config),
261
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
262
        except config.configobj.DuplicateError, e:
263
            self.assertEqual(3, e.line_number)
264
        else:
265
            self.fail('Error in config file not detected')
266
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
267
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
268
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
269
270
    def test_constructs(self):
271
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
272
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
273
    def test_no_default_editor(self):
274
        self.assertRaises(NotImplementedError, config.Config().get_editor)
275
276
    def test_user_email(self):
277
        my_config = InstrumentedConfig()
278
        self.assertEqual('robert.collins@example.org', my_config.user_email())
279
        self.assertEqual(['_get_user_id'], my_config._calls)
280
281
    def test_username(self):
282
        my_config = InstrumentedConfig()
283
        self.assertEqual('Robert Collins <robert.collins@example.org>',
284
                         my_config.username())
285
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
286
287
    def test_signatures_default(self):
288
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
289
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
290
        self.assertEqual(config.CHECK_IF_POSSIBLE,
291
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
292
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
293
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
294
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
295
    def test_signatures_template_method(self):
296
        my_config = InstrumentedConfig()
297
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
298
        self.assertEqual(['_get_signature_checking'], my_config._calls)
299
300
    def test_signatures_template_method_none(self):
301
        my_config = InstrumentedConfig()
302
        my_config._signatures = None
303
        self.assertEqual(config.CHECK_IF_POSSIBLE,
304
                         my_config.signature_checking())
305
        self.assertEqual(['_get_signature_checking'], my_config._calls)
306
1442.1.56 by Robert Collins
gpg_signing_command configuration item
307
    def test_gpg_signing_command_default(self):
308
        my_config = config.Config()
309
        self.assertEqual('gpg', my_config.gpg_signing_command())
310
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
311
    def test_get_user_option_default(self):
312
        my_config = config.Config()
313
        self.assertEqual(None, my_config.get_user_option('no_option'))
314
1472 by Robert Collins
post commit hook, first pass implementation
315
    def test_post_commit_default(self):
316
        my_config = config.Config()
317
        self.assertEqual(None, my_config.post_commit())
318
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
319
    def test_log_format_default(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
320
        my_config = config.Config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
321
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
322
4603.1.10 by Aaron Bentley
Provide change editor via config.
323
    def test_get_change_editor(self):
324
        my_config = InstrumentedConfig()
325
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
326
        self.assertEqual(['_get_change_editor'], my_config._calls)
327
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
328
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
4603.1.10 by Aaron Bentley
Provide change editor via config.
329
                         change_editor.command_template)
330
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
331
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
332
class TestConfigPath(tests.TestCase):
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
333
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
    def setUp(self):
335
        super(TestConfigPath, self).setUp()
336
        os.environ['HOME'] = '/home/bogus'
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
337
        os.environ['XDG_CACHE_DIR'] = ''
2309.2.6 by Alexander Belchenko
bzr now use Win32 API to determine Application Data location, and don't rely solely on $APPDATA
338
        if sys.platform == 'win32':
339
            os.environ['BZR_HOME'] = \
340
                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.
341
            self.bzr_home = \
342
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
        else:
344
            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.
345
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
346
    def test_config_dir(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
347
        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.
348
349
    def test_config_filename(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
350
        self.assertEqual(config.config_filename(),
351
                         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.
352
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
353
    def test_branches_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
354
        self.assertEqual(config.branches_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
355
                         self.bzr_home + '/branches.conf')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
356
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
357
    def test_locations_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
358
        self.assertEqual(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
359
                         self.bzr_home + '/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
360
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
361
    def test_authentication_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
362
        self.assertEqual(config.authentication_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
363
                         self.bzr_home + '/authentication.conf')
364
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
365
    def test_xdg_cache_dir(self):
366
        self.assertEqual(config.xdg_cache_dir(),
367
            '/home/bogus/.cache')
368
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
369
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
370
class TestIniConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
371
372
    def test_contructs(self):
373
        my_config = config.IniBasedConfig("nothing")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
374
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
375
    def test_from_fp(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
376
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
377
        my_config = config.IniBasedConfig(None)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
378
        self.failUnless(
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
379
            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.
380
                        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.
381
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
382
    def test_cached(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
383
        config_file = StringIO(sample_config_text.encode('utf-8'))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
384
        my_config = config.IniBasedConfig(None)
385
        parser = my_config._get_parser(file=config_file)
386
        self.failUnless(my_config._get_parser() is parser)
387
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
388
    def test_get_user_option_as_bool(self):
389
        config_file = StringIO("""
390
a_true_bool = true
391
a_false_bool = 0
392
an_invalid_bool = maybe
393
a_list = hmm, who knows ? # This interpreted as a list !
394
""".encode('utf-8'))
395
        my_config = config.IniBasedConfig(None)
396
        parser = my_config._get_parser(file=config_file)
397
        get_option = my_config.get_user_option_as_bool
398
        self.assertEqual(True, get_option('a_true_bool'))
399
        self.assertEqual(False, get_option('a_false_bool'))
400
        self.assertIs(None, get_option('an_invalid_bool'))
401
        self.assertIs(None, get_option('not_defined_in_this_config'))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
402
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
403
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
404
405
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
406
        my_config = config.GlobalConfig()
407
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
408
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
409
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
410
        oldparserclass = config.ConfigObj
411
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
412
        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.
413
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
414
            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.
415
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
416
            config.ConfigObj = oldparserclass
417
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1551.2.20 by Aaron Bentley
Treated config files as utf-8
418
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
419
                                          '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.
420
421
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
422
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
423
424
    def test_constructs(self):
425
        branch = FakeBranch()
426
        my_config = config.BranchConfig(branch)
427
        self.assertRaises(TypeError, config.BranchConfig)
428
429
    def test_get_location_config(self):
430
        branch = FakeBranch()
431
        my_config = config.BranchConfig(branch)
432
        location_config = my_config._get_location_config()
433
        self.assertEqual(branch.base, location_config.location)
434
        self.failUnless(location_config is my_config._get_location_config())
435
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
436
    def test_get_config(self):
437
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
438
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
439
        my_config = b.get_config()
440
        self.assertIs(my_config.get_user_option('wacky'), None)
441
        my_config.set_user_option('wacky', 'unlikely')
442
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
443
444
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
445
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
446
        my_config2 = b2.get_config()
447
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
448
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
449
    def test_has_explicit_nickname(self):
450
        b = self.make_branch('.')
451
        self.assertFalse(b.get_config().has_explicit_nickname())
452
        b.nick = 'foo'
453
        self.assertTrue(b.get_config().has_explicit_nickname())
454
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
455
    def test_config_url(self):
456
        """The Branch.get_config will use section that uses a local url"""
457
        branch = self.make_branch('branch')
458
        self.assertEqual('branch', branch.nick)
459
460
        locations = config.locations_config_filename()
461
        config.ensure_config_dir_exists()
462
        local_url = urlutils.local_path_to_url('branch')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
463
        open(locations, 'wb').write('[%s]\nnickname = foobar'
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
464
                                    % (local_url,))
465
        self.assertEqual('foobar', branch.nick)
466
467
    def test_config_local_path(self):
468
        """The Branch.get_config will use a local system path"""
469
        branch = self.make_branch('branch')
470
        self.assertEqual('branch', branch.nick)
471
472
        locations = config.locations_config_filename()
473
        config.ensure_config_dir_exists()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
474
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
475
                                    % (osutils.getcwd().encode('utf8'),))
476
        self.assertEqual('barry', branch.nick)
477
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
478
    def test_config_creates_local(self):
479
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
480
        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
481
        branch.set_push_location('http://foobar')
482
        locations = config.locations_config_filename()
483
        local_path = osutils.getcwd().encode('utf8')
484
        # Surprisingly ConfigObj doesn't create a trailing newline
485
        self.check_file_contents(locations,
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
486
                                 '[%s/branch]\n'
487
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
488
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
489
                                 % (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
490
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
491
    def test_autonick_urlencoded(self):
492
        b = self.make_branch('!repo')
493
        self.assertEqual('!repo', b.get_config().get_nickname())
494
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
495
    def test_warn_if_masked(self):
496
        _warning = trace.warning
497
        warnings = []
498
        def warning(*args):
499
            warnings.append(args[0] % args[1:])
500
501
        def set_option(store, warn_masked=True):
502
            warnings[:] = []
503
            conf.set_user_option('example_option', repr(store), store=store,
504
                                 warn_masked=warn_masked)
505
        def assertWarning(warning):
506
            if warning is None:
507
                self.assertEqual(0, len(warnings))
508
            else:
509
                self.assertEqual(1, len(warnings))
510
                self.assertEqual(warning, warnings[0])
511
        trace.warning = warning
512
        try:
513
            branch = self.make_branch('.')
514
            conf = branch.get_config()
515
            set_option(config.STORE_GLOBAL)
516
            assertWarning(None)
517
            set_option(config.STORE_BRANCH)
518
            assertWarning(None)
519
            set_option(config.STORE_GLOBAL)
520
            assertWarning('Value "4" is masked by "3" from branch.conf')
521
            set_option(config.STORE_GLOBAL, warn_masked=False)
522
            assertWarning(None)
523
            set_option(config.STORE_LOCATION)
524
            assertWarning(None)
525
            set_option(config.STORE_BRANCH)
526
            assertWarning('Value "3" is masked by "0" from locations.conf')
527
            set_option(config.STORE_BRANCH, warn_masked=False)
528
            assertWarning(None)
529
        finally:
530
            trace.warning = _warning
531
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
532
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
533
class TestGlobalConfigItems(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
534
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
535
    def test_user_id(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
536
        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
537
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
538
        my_config._parser = my_config._get_parser(file=config_file)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
539
        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
540
                         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.
541
542
    def test_absent_user_id(self):
543
        config_file = StringIO("")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
544
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
545
        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
546
        self.assertEqual(None, my_config._get_user_id())
547
548
    def test_configured_editor(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
549
        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
550
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
551
        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
552
        self.assertEqual("vim", my_config.get_editor())
553
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
554
    def test_signatures_always(self):
555
        config_file = StringIO(sample_always_signatures)
556
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
557
        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
558
        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
559
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
560
        self.assertEqual(config.SIGN_ALWAYS,
561
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
562
        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
563
564
    def test_signatures_if_possible(self):
565
        config_file = StringIO(sample_maybe_signatures)
566
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
567
        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
568
        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
569
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
570
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
571
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
572
        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
573
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
574
    def test_signatures_ignore(self):
575
        config_file = StringIO(sample_ignore_signatures)
576
        my_config = config.GlobalConfig()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
577
        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
578
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
579
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
580
        self.assertEqual(config.SIGN_NEVER,
581
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
582
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
583
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
584
    def _get_sample_config(self):
1551.2.20 by Aaron Bentley
Treated config files as utf-8
585
        config_file = StringIO(sample_config_text.encode('utf-8'))
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
586
        my_config = config.GlobalConfig()
587
        my_config._parser = my_config._get_parser(file=config_file)
588
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
589
1442.1.56 by Robert Collins
gpg_signing_command configuration item
590
    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.
591
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
592
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
593
        self.assertEqual(False, my_config.signature_needed())
594
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
595
    def _get_empty_config(self):
596
        config_file = StringIO("")
597
        my_config = config.GlobalConfig()
598
        my_config._parser = my_config._get_parser(file=config_file)
599
        return my_config
600
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
601
    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.
602
        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.
603
        self.assertEqual("gpg", my_config.gpg_signing_command())
604
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
605
    def test_get_user_option_default(self):
606
        my_config = self._get_empty_config()
607
        self.assertEqual(None, my_config.get_user_option('no_option'))
608
609
    def test_get_user_option_global(self):
610
        my_config = self._get_sample_config()
611
        self.assertEqual("something",
612
                         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.
613
1472 by Robert Collins
post commit hook, first pass implementation
614
    def test_post_commit_default(self):
615
        my_config = self._get_sample_config()
616
        self.assertEqual(None, my_config.post_commit())
617
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
618
    def test_configured_logformat(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
619
        my_config = self._get_sample_config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
620
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
621
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
622
    def test_get_alias(self):
623
        my_config = self._get_sample_config()
624
        self.assertEqual('help', my_config.get_alias('h'))
625
2900.3.6 by Tim Penhey
Added tests.
626
    def test_get_aliases(self):
627
        my_config = self._get_sample_config()
628
        aliases = my_config.get_aliases()
629
        self.assertEqual(2, len(aliases))
630
        sorted_keys = sorted(aliases)
631
        self.assertEqual('help', aliases[sorted_keys[0]])
632
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
633
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
634
    def test_get_no_alias(self):
635
        my_config = self._get_sample_config()
636
        self.assertEqual(None, my_config.get_alias('foo'))
637
638
    def test_get_long_alias(self):
639
        my_config = self._get_sample_config()
640
        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.
641
4603.1.10 by Aaron Bentley
Provide change editor via config.
642
    def test_get_change_editor(self):
643
        my_config = self._get_sample_config()
644
        change_editor = my_config.get_change_editor('old', 'new')
645
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
646
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
647
                         ' '.join(change_editor.command_template))
648
649
    def test_get_no_change_editor(self):
650
        my_config = self._get_empty_config()
651
        change_editor = my_config.get_change_editor('old', 'new')
652
        self.assertIs(None, change_editor)
653
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
654
2900.3.6 by Tim Penhey
Added tests.
655
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
656
657
    def test_empty(self):
658
        my_config = config.GlobalConfig()
659
        self.assertEqual(0, len(my_config.get_aliases()))
660
661
    def test_set_alias(self):
662
        my_config = config.GlobalConfig()
663
        alias_value = 'commit --strict'
664
        my_config.set_alias('commit', alias_value)
665
        new_config = config.GlobalConfig()
666
        self.assertEqual(alias_value, new_config.get_alias('commit'))
667
668
    def test_remove_alias(self):
669
        my_config = config.GlobalConfig()
670
        my_config.set_alias('commit', 'commit --strict')
671
        # Now remove the alias again.
672
        my_config.unset_alias('commit')
673
        new_config = config.GlobalConfig()
674
        self.assertIs(None, new_config.get_alias('commit'))
675
676
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
677
class TestLocationConfig(tests.TestCaseInTempDir):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
678
679
    def test_constructs(self):
680
        my_config = config.LocationConfig('http://example.com')
681
        self.assertRaises(TypeError, config.LocationConfig)
682
683
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
684
        # This is testing the correct file names are provided.
685
        # TODO: consolidate with the test for GlobalConfigs filename checks.
686
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
687
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
688
        oldparserclass = config.ConfigObj
689
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
690
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
691
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
692
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
693
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
694
            config.ConfigObj = oldparserclass
695
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
696
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
697
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
698
                           'utf-8')])
1711.4.29 by John Arbash Meinel
Alexander Belchenko, fix test_config to use ensure_config_dir, rather than os.mkdir()
699
        config.ensure_config_dir_exists()
700
        #os.mkdir(config.config_dir())
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
701
        f = file(config.branches_config_filename(), 'wb')
702
        f.write('')
703
        f.close()
704
        oldparserclass = config.ConfigObj
705
        config.ConfigObj = InstrumentedConfigObj
706
        try:
707
            my_config = config.LocationConfig('http://www.example.com')
708
            parser = my_config._get_parser()
709
        finally:
710
            config.ConfigObj = oldparserclass
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
711
712
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
713
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
714
        global_config = my_config._get_global_config()
715
        self.failUnless(isinstance(global_config, config.GlobalConfig))
716
        self.failUnless(global_config is my_config._get_global_config())
717
1993.3.1 by James Henstridge
first go at making location config lookup recursive
718
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
719
        self.get_branch_config('/')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
720
        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.
721
1993.3.1 by James Henstridge
first go at making location config lookup recursive
722
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
723
        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
724
        self.assertEqual([('http://www.example.com', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
725
                         self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
726
1993.3.1 by James Henstridge
first go at making location config lookup recursive
727
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
728
        self.get_branch_config('http://www.example.com-com')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
729
        self.assertEqual([], self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
730
1993.3.1 by James Henstridge
first go at making location config lookup recursive
731
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
732
        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
733
        self.assertEqual([('http://www.example.com', 'com')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
734
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
735
1993.3.5 by James Henstridge
add back recurse=False option to config file
736
    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
737
        self.get_branch_config('http://www.example.com/ignoreparent')
738
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
739
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
740
1993.3.5 by James Henstridge
add back recurse=False option to config file
741
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
742
        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
743
            'http://www.example.com/ignoreparent/childbranch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
744
        self.assertEqual([('http://www.example.com/ignoreparent',
745
                           'childbranch')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
746
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
747
1993.3.1 by James Henstridge
first go at making location config lookup recursive
748
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
749
        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
750
        self.assertEqual([('/b/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
751
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
752
1993.3.1 by James Henstridge
first go at making location config lookup recursive
753
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
754
        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
755
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
756
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
757
1993.3.1 by James Henstridge
first go at making location config lookup recursive
758
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
759
        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
760
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
761
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
762
1993.3.1 by James Henstridge
first go at making location config lookup recursive
763
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
764
        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
765
        self.assertEqual([('/a/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
766
                         self.my_location_config._get_matching_sections())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
767
1993.3.1 by James Henstridge
first go at making location config lookup recursive
768
    def test__get_matching_sections_explicit_over_glob(self):
769
        # XXX: 2006-09-08 jamesh
770
        # This test only passes because ord('c') > ord('*').  If there
771
        # was a config section for '/a/?', it would get precedence
772
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
773
        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
774
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
775
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
776
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
777
    def test__get_option_policy_normal(self):
778
        self.get_branch_config('http://www.example.com')
779
        self.assertEqual(
780
            self.my_location_config._get_config_policy(
781
            'http://www.example.com', 'normal_option'),
782
            config.POLICY_NONE)
783
784
    def test__get_option_policy_norecurse(self):
785
        self.get_branch_config('http://www.example.com')
786
        self.assertEqual(
787
            self.my_location_config._get_option_policy(
788
            'http://www.example.com', 'norecurse_option'),
789
            config.POLICY_NORECURSE)
790
        # Test old recurse=False setting:
791
        self.assertEqual(
792
            self.my_location_config._get_option_policy(
793
            'http://www.example.com/norecurse', 'normal_option'),
794
            config.POLICY_NORECURSE)
795
796
    def test__get_option_policy_normal(self):
797
        self.get_branch_config('http://www.example.com')
798
        self.assertEqual(
799
            self.my_location_config._get_option_policy(
800
            'http://www.example.com', 'appendpath_option'),
801
            config.POLICY_APPENDPATH)
802
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
803
    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
804
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
805
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
806
                         self.my_config.username())
807
808
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
809
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
810
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
811
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
812
                         self.my_config.username())
813
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
814
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
815
        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
816
        self.assertEqual('Robert Collins <robertc@example.org>',
817
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
818
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
819
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
820
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
821
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
822
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
823
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
824
        self.assertEqual(config.SIGN_NEVER,
825
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
826
827
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
828
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
829
        self.assertEqual(config.CHECK_NEVER,
830
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
831
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
832
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
833
        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
834
        self.assertEqual(config.CHECK_IF_POSSIBLE,
835
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
836
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
837
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
838
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
839
        self.assertEqual(config.CHECK_ALWAYS,
840
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
841
1442.1.56 by Robert Collins
gpg_signing_command configuration item
842
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
843
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
844
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
845
846
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
847
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
848
        self.assertEqual("false", self.my_config.gpg_signing_command())
849
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
850
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
851
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
852
        self.assertEqual('something',
853
                         self.my_config.get_user_option('user_global_option'))
854
855
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
856
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
857
        self.assertEqual('local',
858
                         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
859
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
860
    def test_get_user_option_appendpath(self):
861
        # returned as is for the base path:
862
        self.get_branch_config('http://www.example.com')
863
        self.assertEqual('append',
864
                         self.my_config.get_user_option('appendpath_option'))
865
        # Extra path components get appended:
866
        self.get_branch_config('http://www.example.com/a/b/c')
867
        self.assertEqual('append/a/b/c',
868
                         self.my_config.get_user_option('appendpath_option'))
869
        # Overriden for http://www.example.com/dir, where it is a
870
        # normal option:
871
        self.get_branch_config('http://www.example.com/dir/a/b/c')
872
        self.assertEqual('normal',
873
                         self.my_config.get_user_option('appendpath_option'))
874
875
    def test_get_user_option_norecurse(self):
876
        self.get_branch_config('http://www.example.com')
877
        self.assertEqual('norecurse',
878
                         self.my_config.get_user_option('norecurse_option'))
879
        self.get_branch_config('http://www.example.com/dir')
880
        self.assertEqual(None,
881
                         self.my_config.get_user_option('norecurse_option'))
882
        # http://www.example.com/norecurse is a recurse=False section
883
        # that redefines normal_option.  Subdirectories do not pick up
884
        # this redefinition.
885
        self.get_branch_config('http://www.example.com/norecurse')
886
        self.assertEqual('norecurse',
887
                         self.my_config.get_user_option('normal_option'))
888
        self.get_branch_config('http://www.example.com/norecurse/subdir')
889
        self.assertEqual('normal',
890
                         self.my_config.get_user_option('normal_option'))
891
2120.6.4 by James Henstridge
add support for specifying policy when storing options
892
    def test_set_user_option_norecurse(self):
893
        self.get_branch_config('http://www.example.com')
894
        self.my_config.set_user_option('foo', 'bar',
895
                                       store=config.STORE_LOCATION_NORECURSE)
896
        self.assertEqual(
897
            self.my_location_config._get_option_policy(
898
            'http://www.example.com', 'foo'),
899
            config.POLICY_NORECURSE)
900
901
    def test_set_user_option_appendpath(self):
902
        self.get_branch_config('http://www.example.com')
903
        self.my_config.set_user_option('foo', 'bar',
904
                                       store=config.STORE_LOCATION_APPENDPATH)
905
        self.assertEqual(
906
            self.my_location_config._get_option_policy(
907
            'http://www.example.com', 'foo'),
908
            config.POLICY_APPENDPATH)
909
910
    def test_set_user_option_change_policy(self):
911
        self.get_branch_config('http://www.example.com')
912
        self.my_config.set_user_option('norecurse_option', 'normal',
913
                                       store=config.STORE_LOCATION)
914
        self.assertEqual(
915
            self.my_location_config._get_option_policy(
916
            'http://www.example.com', 'norecurse_option'),
917
            config.POLICY_NONE)
918
919
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
920
        # The following section has recurse=False set.  The test is to
921
        # make sure that a normal option can be added to the section,
922
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
923
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
924
        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
925
                             'The section "http://www.example.com/norecurse" '
926
                             'has been converted to use policies.'],
927
                            self.my_config.set_user_option,
928
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
929
        self.assertEqual(
930
            self.my_location_config._get_option_policy(
931
            'http://www.example.com/norecurse', 'foo'),
932
            config.POLICY_NONE)
933
        # The previously existing option is still norecurse:
934
        self.assertEqual(
935
            self.my_location_config._get_option_policy(
936
            'http://www.example.com/norecurse', 'normal_option'),
937
            config.POLICY_NORECURSE)
938
1472 by Robert Collins
post commit hook, first pass implementation
939
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
940
        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
941
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
942
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
943
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
944
    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.
945
        if global_config is None:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
946
            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.
947
        else:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
948
            global_file = StringIO(global_config.encode('utf-8'))
949
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
950
        self.my_config = config.BranchConfig(FakeBranch(location))
951
        # Force location config to use specified file
952
        self.my_location_config = self.my_config._get_location_config()
953
        self.my_location_config._get_parser(branches_file)
954
        # 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.
955
        self.my_config._get_global_config()._get_parser(global_file)
956
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
957
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
958
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
959
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
960
        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
961
962
        real_mkdir = os.mkdir
963
        self.created = False
964
        def checked_mkdir(path, mode=0777):
965
            self.log('making directory: %s', path)
966
            real_mkdir(path, mode)
967
            self.created = True
968
969
        os.mkdir = checked_mkdir
970
        try:
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
971
            self.callDeprecated(['The recurse option is deprecated as of '
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
972
                                 '0.14.  The section "/a/c" has been '
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
973
                                 'converted to use policies.'],
974
                                self.my_config.set_user_option,
975
                                '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
976
        finally:
977
            os.mkdir = real_mkdir
978
979
        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.
980
        self.assertEqual([('__contains__', '/a/c'),
981
                          ('__contains__', '/a/c/'),
982
                          ('__setitem__', '/a/c', {}),
983
                          ('__getitem__', '/a/c'),
984
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
985
                          ('__getitem__', '/a/c'),
986
                          ('as_bool', 'recurse'),
987
                          ('__getitem__', '/a/c'),
988
                          ('__delitem__', 'recurse'),
989
                          ('__getitem__', '/a/c'),
990
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
991
                          ('__getitem__', '/a/c'),
992
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
993
                          ('write',)],
994
                         record._calls[1:])
995
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
996
    def test_set_user_setting_sets_and_saves2(self):
997
        self.get_branch_config('/a/c')
998
        self.assertIs(self.my_config.get_user_option('foo'), None)
999
        self.my_config.set_user_option('foo', 'bar')
1000
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1001
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1002
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1003
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1004
        self.my_config.set_user_option('foo', 'baz',
1005
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1006
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1007
        self.my_config.set_user_option('foo', 'qux')
1008
        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.
1009
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1010
    def test_get_bzr_remote_path(self):
1011
        my_config = config.LocationConfig('/a/c')
1012
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1013
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1014
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1015
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1016
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1017
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1018
1770.2.8 by Aaron Bentley
Add precedence test
1019
precedence_global = 'option = global'
1020
precedence_branch = 'option = branch'
1021
precedence_location = """
1022
[http://]
1023
recurse = true
1024
option = recurse
1025
[http://example.com/specific]
1026
option = exact
1027
"""
1028
1029
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1030
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1031
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1032
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1033
                          location_config=None, branch_data_config=None):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1034
        my_config = config.BranchConfig(FakeBranch(location))
1035
        if global_config is not None:
1036
            global_file = StringIO(global_config.encode('utf-8'))
1037
            my_config._get_global_config()._get_parser(global_file)
1038
        self.my_location_config = my_config._get_location_config()
1039
        if location_config is not None:
1040
            location_file = StringIO(location_config.encode('utf-8'))
1041
            self.my_location_config._get_parser(location_file)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1042
        if branch_data_config is not None:
1043
            my_config.branch.control_files.files['branch.conf'] = \
1044
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1045
        return my_config
1046
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1047
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1048
        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
1049
        my_config = config.BranchConfig(branch)
1050
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1051
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1052
        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.
1053
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1054
                                  "Robert Collins <robertc@example.org>")
1055
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1056
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1057
        self.assertEqual("Robert Collins <robertc@example.org>",
1058
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1059
1060
    def test_not_set_in_branch(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1061
        my_config = self.get_branch_config(sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1062
        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
1063
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1064
        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
1065
        self.assertEqual("John", my_config._get_user_id())
1066
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1067
    def test_BZR_EMAIL_OVERRIDES(self):
1068
        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
1069
        branch = FakeBranch()
1070
        my_config = config.BranchConfig(branch)
1071
        self.assertEqual("Robert Collins <robertc@example.org>",
1072
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1073
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1074
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1075
        my_config = self.get_branch_config(
1076
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1077
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1078
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1079
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1080
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1081
    def test_signatures_forced_branch(self):
1082
        my_config = self.get_branch_config(
1083
            global_config=sample_ignore_signatures,
1084
            branch_data_config=sample_always_signatures)
1085
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1086
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1087
        self.assertTrue(my_config.signature_needed())
1088
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1089
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1090
        my_config = self.get_branch_config(
1091
            # branch data cannot set gpg_signing_command
1092
            branch_data_config="gpg_signing_command=pgp")
1551.2.20 by Aaron Bentley
Treated config files as utf-8
1093
        config_file = StringIO(sample_config_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1094
        my_config._get_global_config()._get_parser(config_file)
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1095
        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.
1096
1097
    def test_get_user_option_global(self):
1098
        branch = FakeBranch()
1099
        my_config = config.BranchConfig(branch)
1551.2.20 by Aaron Bentley
Treated config files as utf-8
1100
        config_file = StringIO(sample_config_text.encode('utf-8'))
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1101
        (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.
1102
        self.assertEqual('something',
1103
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1104
1105
    def test_post_commit_default(self):
1106
        branch = FakeBranch()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1107
        my_config = self.get_branch_config(sample_config_text, '/a/c',
1108
                                           sample_branches_text)
1109
        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
1110
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1111
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1112
        my_config.set_user_option('post_commit', 'rmtree_root')
1113
        # post-commit is ignored when bresent in branch data
1114
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1115
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1116
        my_config.set_user_option('post_commit', 'rmtree_root',
1117
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1118
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1119
1770.2.8 by Aaron Bentley
Add precedence test
1120
    def test_config_precedence(self):
1121
        my_config = self.get_branch_config(global_config=precedence_global)
1122
        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.
1123
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1124
                                      branch_data_config=precedence_branch)
1125
        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.
1126
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1127
                                      branch_data_config=precedence_branch,
1128
                                      location_config=precedence_location)
1129
        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.
1130
        my_config = self.get_branch_config(global_config=precedence_global,
1770.2.8 by Aaron Bentley
Add precedence test
1131
                                      branch_data_config=precedence_branch,
1132
                                      location_config=precedence_location,
1133
                                      location='http://example.com/specific')
1134
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1135
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1136
    def test_get_mail_client(self):
1137
        config = self.get_branch_config()
1138
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1139
        self.assertIsInstance(client, mail_client.DefaultMail)
1140
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1141
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1142
        config.set_user_option('mail_client', 'evolution')
1143
        client = config.get_mail_client()
1144
        self.assertIsInstance(client, mail_client.Evolution)
1145
2681.5.1 by ghigo
Add KMail support to bzr send
1146
        config.set_user_option('mail_client', 'kmail')
1147
        client = config.get_mail_client()
1148
        self.assertIsInstance(client, mail_client.KMail)
1149
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1150
        config.set_user_option('mail_client', 'mutt')
1151
        client = config.get_mail_client()
1152
        self.assertIsInstance(client, mail_client.Mutt)
1153
1154
        config.set_user_option('mail_client', 'thunderbird')
1155
        client = config.get_mail_client()
1156
        self.assertIsInstance(client, mail_client.Thunderbird)
1157
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1158
        # Generic options
1159
        config.set_user_option('mail_client', 'default')
1160
        client = config.get_mail_client()
1161
        self.assertIsInstance(client, mail_client.DefaultMail)
1162
1163
        config.set_user_option('mail_client', 'editor')
1164
        client = config.get_mail_client()
1165
        self.assertIsInstance(client, mail_client.Editor)
1166
1167
        config.set_user_option('mail_client', 'mapi')
1168
        client = config.get_mail_client()
1169
        self.assertIsInstance(client, mail_client.MAPIClient)
1170
2681.1.23 by Aaron Bentley
Add support for xdg-email
1171
        config.set_user_option('mail_client', 'xdg-email')
1172
        client = config.get_mail_client()
1173
        self.assertIsInstance(client, mail_client.XDGEmail)
1174
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1175
        config.set_user_option('mail_client', 'firebird')
1176
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1177
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1178
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1179
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1180
1181
    def test_extract_email_address(self):
1182
        self.assertEqual('jane@test.com',
1183
                         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
1184
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1185
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1186
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1187
    def test_parse_username(self):
1188
        self.assertEqual(('', 'jdoe@example.com'),
1189
                         config.parse_username('jdoe@example.com'))
1190
        self.assertEqual(('', 'jdoe@example.com'),
1191
                         config.parse_username('<jdoe@example.com>'))
1192
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1193
                         config.parse_username('John Doe <jdoe@example.com>'))
1194
        self.assertEqual(('John Doe', ''),
1195
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1196
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1197
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1198
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1199
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1200
1201
    def test_get_value(self):
1202
        """Test that retreiving a value from a section is possible"""
1203
        branch = self.make_branch('.')
1204
        tree_config = config.TreeConfig(branch)
1205
        tree_config.set_option('value', 'key', 'SECTION')
1206
        tree_config.set_option('value2', 'key2')
1207
        tree_config.set_option('value3-top', 'key3')
1208
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1209
        value = tree_config.get_option('key', 'SECTION')
1210
        self.assertEqual(value, 'value')
1211
        value = tree_config.get_option('key2')
1212
        self.assertEqual(value, 'value2')
1213
        self.assertEqual(tree_config.get_option('non-existant'), None)
1214
        value = tree_config.get_option('non-existant', 'SECTION')
1215
        self.assertEqual(value, None)
1216
        value = tree_config.get_option('non-existant', default='default')
1217
        self.assertEqual(value, 'default')
1218
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1219
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1220
        self.assertEqual(value, 'default')
1221
        value = tree_config.get_option('key3')
1222
        self.assertEqual(value, 'value3-top')
1223
        value = tree_config.get_option('key3', 'SECTION')
1224
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1225
1226
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1227
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1228
1229
    def test_get_value(self):
1230
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1231
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1232
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1233
        bzrdir_config.set_option('value', 'key', 'SECTION')
1234
        bzrdir_config.set_option('value2', 'key2')
1235
        bzrdir_config.set_option('value3-top', 'key3')
1236
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1237
        value = bzrdir_config.get_option('key', 'SECTION')
1238
        self.assertEqual(value, 'value')
1239
        value = bzrdir_config.get_option('key2')
1240
        self.assertEqual(value, 'value2')
1241
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1242
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1243
        self.assertEqual(value, None)
1244
        value = bzrdir_config.get_option('non-existant', default='default')
1245
        self.assertEqual(value, 'default')
1246
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1247
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1248
                                         default='default')
1249
        self.assertEqual(value, 'default')
1250
        value = bzrdir_config.get_option('key3')
1251
        self.assertEqual(value, 'value3-top')
1252
        value = bzrdir_config.get_option('key3', 'SECTION')
1253
        self.assertEqual(value, 'value3-section')
1254
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1255
    def test_set_unset_default_stack_on(self):
1256
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1257
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1258
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1259
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1260
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1261
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1262
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1263
        bzrdir_config.set_default_stack_on(None)
1264
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1265
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1266
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1267
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1268
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1269
1270
    def _got_user_passwd(self, expected_user, expected_password,
1271
                         config, *args, **kwargs):
1272
        credentials = config.get_credentials(*args, **kwargs)
1273
        if credentials is None:
1274
            user = None
1275
            password = None
1276
        else:
1277
            user = credentials['user']
1278
            password = credentials['password']
1279
        self.assertEquals(expected_user, user)
1280
        self.assertEquals(expected_password, password)
1281
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1282
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1283
        conf = config.AuthenticationConfig(_file=StringIO())
1284
        self.assertEquals({}, conf._get_config())
1285
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1286
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1287
    def test_missing_auth_section_header(self):
1288
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1289
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1290
1291
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1292
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1293
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1294
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1295
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1296
        conf = config.AuthenticationConfig(_file=StringIO(
1297
                """[broken]
1298
scheme=ftp
1299
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1300
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1301
"""))
1302
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1303
1304
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
1305
        conf = config.AuthenticationConfig(_file=StringIO(
1306
                """[broken]
1307
scheme=ftp
1308
user=joe
1309
port=port # Error: Not an int
1310
"""))
1311
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1312
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1313
    def test_unknown_password_encoding(self):
1314
        conf = config.AuthenticationConfig(_file=StringIO(
1315
                """[broken]
1316
scheme=ftp
1317
user=joe
1318
password_encoding=unknown
1319
"""))
1320
        self.assertRaises(ValueError, conf.get_password,
1321
                          'ftp', 'foo.net', 'joe')
1322
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1323
    def test_credentials_for_scheme_host(self):
1324
        conf = config.AuthenticationConfig(_file=StringIO(
1325
                """# Identity on foo.net
1326
[ftp definition]
1327
scheme=ftp
1328
host=foo.net
1329
user=joe
1330
password=secret-pass
1331
"""))
1332
        # Basic matching
1333
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1334
        # different scheme
1335
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1336
        # different host
1337
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1338
1339
    def test_credentials_for_host_port(self):
1340
        conf = config.AuthenticationConfig(_file=StringIO(
1341
                """# Identity on foo.net
1342
[ftp definition]
1343
scheme=ftp
1344
port=10021
1345
host=foo.net
1346
user=joe
1347
password=secret-pass
1348
"""))
1349
        # No port
1350
        self._got_user_passwd('joe', 'secret-pass',
1351
                              conf, 'ftp', 'foo.net', port=10021)
1352
        # different port
1353
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1354
1355
    def test_for_matching_host(self):
1356
        conf = config.AuthenticationConfig(_file=StringIO(
1357
                """# Identity on foo.net
1358
[sourceforge]
1359
scheme=bzr
1360
host=bzr.sf.net
1361
user=joe
1362
password=joepass
1363
[sourceforge domain]
1364
scheme=bzr
1365
host=.bzr.sf.net
1366
user=georges
1367
password=bendover
1368
"""))
1369
        # matching domain
1370
        self._got_user_passwd('georges', 'bendover',
1371
                              conf, 'bzr', 'foo.bzr.sf.net')
1372
        # phishing attempt
1373
        self._got_user_passwd(None, None,
1374
                              conf, 'bzr', 'bbzr.sf.net')
1375
1376
    def test_for_matching_host_None(self):
1377
        conf = config.AuthenticationConfig(_file=StringIO(
1378
                """# Identity on foo.net
1379
[catchup bzr]
1380
scheme=bzr
1381
user=joe
1382
password=joepass
1383
[DEFAULT]
1384
user=georges
1385
password=bendover
1386
"""))
1387
        # match no host
1388
        self._got_user_passwd('joe', 'joepass',
1389
                              conf, 'bzr', 'quux.net')
1390
        # no host but different scheme
1391
        self._got_user_passwd('georges', 'bendover',
1392
                              conf, 'ftp', 'quux.net')
1393
1394
    def test_credentials_for_path(self):
1395
        conf = config.AuthenticationConfig(_file=StringIO(
1396
                """
1397
[http dir1]
1398
scheme=http
1399
host=bar.org
1400
path=/dir1
1401
user=jim
1402
password=jimpass
1403
[http dir2]
1404
scheme=http
1405
host=bar.org
1406
path=/dir2
1407
user=georges
1408
password=bendover
1409
"""))
1410
        # no path no dice
1411
        self._got_user_passwd(None, None,
1412
                              conf, 'http', host='bar.org', path='/dir3')
1413
        # matching path
1414
        self._got_user_passwd('georges', 'bendover',
1415
                              conf, 'http', host='bar.org', path='/dir2')
1416
        # matching subdir
1417
        self._got_user_passwd('jim', 'jimpass',
1418
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1419
1420
    def test_credentials_for_user(self):
1421
        conf = config.AuthenticationConfig(_file=StringIO(
1422
                """
1423
[with user]
1424
scheme=http
1425
host=bar.org
1426
user=jim
1427
password=jimpass
1428
"""))
1429
        # Get user
1430
        self._got_user_passwd('jim', 'jimpass',
1431
                              conf, 'http', 'bar.org')
1432
        # Get same user
1433
        self._got_user_passwd('jim', 'jimpass',
1434
                              conf, 'http', 'bar.org', user='jim')
1435
        # Don't get a different user if one is specified
1436
        self._got_user_passwd(None, None,
1437
                              conf, 'http', 'bar.org', user='georges')
1438
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
1439
    def test_credentials_for_user_without_password(self):
1440
        conf = config.AuthenticationConfig(_file=StringIO(
1441
                """
1442
[without password]
1443
scheme=http
1444
host=bar.org
1445
user=jim
1446
"""))
1447
        # Get user but no password
1448
        self._got_user_passwd('jim', None,
1449
                              conf, 'http', 'bar.org')
1450
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1451
    def test_verify_certificates(self):
1452
        conf = config.AuthenticationConfig(_file=StringIO(
1453
                """
1454
[self-signed]
1455
scheme=https
1456
host=bar.org
1457
user=jim
1458
password=jimpass
1459
verify_certificates=False
1460
[normal]
1461
scheme=https
1462
host=foo.net
1463
user=georges
1464
password=bendover
1465
"""))
1466
        credentials = conf.get_credentials('https', 'bar.org')
1467
        self.assertEquals(False, credentials.get('verify_certificates'))
1468
        credentials = conf.get_credentials('https', 'foo.net')
1469
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1470
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1471
1472
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1473
3777.1.8 by Aaron Bentley
Commit work-in-progress
1474
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1475
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1476
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1477
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
1478
        credentials = conf.get_credentials(host='host', scheme='scheme',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1479
                                           port=99, path='/foo',
1480
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1481
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1482
                       'verify_certificates': False, 'scheme': 'scheme', 
1483
                       'host': 'host', 'port': 99, 'path': '/foo', 
1484
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1485
        self.assertEqual(CREDENTIALS, credentials)
1486
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1487
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1488
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
1489
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1490
    def test_reset_credentials_different_name(self):
1491
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1492
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1493
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1494
        self.assertIs(None, conf._get_config().get('name'))
1495
        credentials = conf.get_credentials(host='host', scheme='scheme')
1496
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1497
                       'password', 'verify_certificates': True, 
1498
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
1499
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1500
        self.assertEqual(CREDENTIALS, credentials)
1501
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1502
2900.2.14 by Vincent Ladeuil
More tests.
1503
class TestAuthenticationConfig(tests.TestCase):
1504
    """Test AuthenticationConfig behaviour"""
1505
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1506
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1507
                                       host=None, port=None, realm=None,
1508
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
1509
        if host is None:
1510
            host = 'bar.org'
1511
        user, password = 'jim', 'precious'
1512
        expected_prompt = expected_prompt_format % {
1513
            'scheme': scheme, 'host': host, 'port': port,
1514
            'user': user, 'realm': realm}
1515
1516
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1517
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
1518
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1519
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
1520
        # We use an empty conf so that the user is always prompted
1521
        conf = config.AuthenticationConfig()
1522
        self.assertEquals(password,
1523
                          conf.get_password(scheme, host, user, port=port,
1524
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1525
        self.assertEquals(expected_prompt, stderr.getvalue())
1526
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
1527
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1528
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1529
                                       host=None, port=None, realm=None,
1530
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1531
        if host is None:
1532
            host = 'bar.org'
1533
        username = 'jim'
1534
        expected_prompt = expected_prompt_format % {
1535
            'scheme': scheme, 'host': host, 'port': port,
1536
            'realm': realm}
1537
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1538
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1539
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1540
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1541
        # We use an empty conf so that the user is always prompted
1542
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
1543
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
1544
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1545
        self.assertEquals(expected_prompt, stderr.getvalue())
1546
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1547
1548
    def test_username_defaults_prompts(self):
1549
        # HTTP prompts can't be tested here, see test_http.py
1550
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1551
        self._check_default_username_prompt(
1552
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1553
        self._check_default_username_prompt(
1554
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1555
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1556
    def test_username_default_no_prompt(self):
1557
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1558
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1559
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1560
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1561
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
1562
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1563
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1564
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1565
        self._check_default_password_prompt(
1566
            'FTP %(user)s@%(host)s password: ', 'ftp')
1567
        self._check_default_password_prompt(
1568
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1569
        self._check_default_password_prompt(
1570
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
1571
        # SMTP port handling is a bit special (it's handled if embedded in the
1572
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
1573
        # FIXME: should we: forbid that, extend it to other schemes, leave
1574
        # things as they are that's fine thank you ?
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1575
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1576
                                            'smtp')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1577
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1578
                                            'smtp', host='bar.org:10025')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1579
        self._check_default_password_prompt(
2900.2.14 by Vincent Ladeuil
More tests.
1580
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1581
            'smtp', port=10025)
1582
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1583
    def test_ssh_password_emits_warning(self):
1584
        conf = config.AuthenticationConfig(_file=StringIO(
1585
                """
1586
[ssh with password]
1587
scheme=ssh
1588
host=bar.org
1589
user=jim
1590
password=jimpass
1591
"""))
1592
        entered_password = 'typed-by-hand'
1593
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1594
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1595
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1596
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1597
1598
        # Since the password defined in the authentication config is ignored,
1599
        # the user is prompted
1600
        self.assertEquals(entered_password,
1601
                          conf.get_password('ssh', 'bar.org', user='jim'))
1602
        self.assertContainsRe(
1603
            self._get_log(keep_log_file=True),
1604
            'password ignored in section \[ssh with password\]')
1605
3420.1.3 by Vincent Ladeuil
John's review feedback.
1606
    def test_ssh_without_password_doesnt_emit_warning(self):
1607
        conf = config.AuthenticationConfig(_file=StringIO(
1608
                """
1609
[ssh with password]
1610
scheme=ssh
1611
host=bar.org
1612
user=jim
1613
"""))
1614
        entered_password = 'typed-by-hand'
1615
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1616
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
1617
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1618
                                            stdout=stdout,
1619
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
1620
1621
        # Since the password defined in the authentication config is ignored,
1622
        # the user is prompted
1623
        self.assertEquals(entered_password,
1624
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
1625
        # No warning shoud be emitted since there is no password. We are only
1626
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
1627
        self.assertNotContainsRe(
1628
            self._get_log(keep_log_file=True),
1629
            'password ignored in section \[ssh with password\]')
1630
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
1631
    def test_uses_fallback_stores(self):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1632
        self._old_cs_registry = config.credential_store_registry
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
1633
        def restore():
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1634
            config.credential_store_registry = self._old_cs_registry
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
1635
        self.addCleanup(restore)
1636
        config.credential_store_registry = config.CredentialStoreRegistry()
1637
        store = StubCredentialStore()
1638
        store.add_credentials("http", "example.com", "joe", "secret")
1639
        config.credential_store_registry.register("stub", store, fallback=True)
1640
        conf = config.AuthenticationConfig(_file=StringIO())
1641
        creds = conf.get_credentials("http", "example.com")
1642
        self.assertEquals("joe", creds["user"])
1643
        self.assertEquals("secret", creds["password"])
1644
2900.2.14 by Vincent Ladeuil
More tests.
1645
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1646
class StubCredentialStore(config.CredentialStore):
1647
1648
    def __init__(self):
1649
        self._username = {}
1650
        self._password = {}
1651
1652
    def add_credentials(self, scheme, host, user, password=None):
1653
        self._username[(scheme, host)] = user
1654
        self._password[(scheme, host)] = password
1655
1656
    def get_credentials(self, scheme, host, port=None, user=None,
1657
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1658
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1659
        if not key in self._username:
1660
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1661
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1662
                "user": self._username[key], "password": self._password[key]}
1663
1664
1665
class CountingCredentialStore(config.CredentialStore):
1666
1667
    def __init__(self):
1668
        self._calls = 0
1669
1670
    def get_credentials(self, scheme, host, port=None, user=None,
1671
        path=None, realm=None):
1672
        self._calls += 1
1673
        return None
1674
1675
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1676
class TestCredentialStoreRegistry(tests.TestCase):
1677
1678
    def _get_cs_registry(self):
1679
        return config.credential_store_registry
1680
1681
    def test_default_credential_store(self):
1682
        r = self._get_cs_registry()
1683
        default = r.get_credential_store(None)
1684
        self.assertIsInstance(default, config.PlainTextCredentialStore)
1685
1686
    def test_unknown_credential_store(self):
1687
        r = self._get_cs_registry()
1688
        # It's hard to imagine someone creating a credential store named
1689
        # 'unknown' so we use that as an never registered key.
1690
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1691
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1692
    def test_fallback_none_registered(self):
1693
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1694
        self.assertEquals(None,
1695
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1696
1697
    def test_register(self):
1698
        r = config.CredentialStoreRegistry()
1699
        r.register("stub", StubCredentialStore(), fallback=False)
1700
        r.register("another", StubCredentialStore(), fallback=True)
1701
        self.assertEquals(["another", "stub"], r.keys())
1702
1703
    def test_register_lazy(self):
1704
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1705
        r.register_lazy("stub", "bzrlib.tests.test_config",
1706
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1707
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1708
        self.assertIsInstance(r.get_credential_store("stub"),
1709
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1710
1711
    def test_is_fallback(self):
1712
        r = config.CredentialStoreRegistry()
1713
        r.register("stub1", None, fallback=False)
1714
        r.register("stub2", None, fallback=True)
1715
        self.assertEquals(False, r.is_fallback("stub1"))
1716
        self.assertEquals(True, r.is_fallback("stub2"))
1717
1718
    def test_no_fallback(self):
1719
        r = config.CredentialStoreRegistry()
1720
        store = CountingCredentialStore()
1721
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1722
        self.assertEquals(None,
1723
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1724
        self.assertEquals(0, store._calls)
1725
1726
    def test_fallback_credentials(self):
1727
        r = config.CredentialStoreRegistry()
1728
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1729
        store.add_credentials("http", "example.com",
1730
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1731
        r.register("stub", store, fallback=True)
1732
        creds = r.get_fallback_credentials("http", "example.com")
1733
        self.assertEquals("somebody", creds["user"])
1734
        self.assertEquals("geheim", creds["password"])
1735
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1736
    def test_fallback_first_wins(self):
1737
        r = config.CredentialStoreRegistry()
1738
        stub1 = StubCredentialStore()
1739
        stub1.add_credentials("http", "example.com",
1740
                              "somebody", "stub1")
1741
        r.register("stub1", stub1, fallback=True)
1742
        stub2 = StubCredentialStore()
1743
        stub2.add_credentials("http", "example.com",
1744
                              "somebody", "stub2")
1745
        r.register("stub2", stub1, fallback=True)
1746
        creds = r.get_fallback_credentials("http", "example.com")
1747
        self.assertEquals("somebody", creds["user"])
1748
        self.assertEquals("stub1", creds["password"])
1749
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1750
1751
class TestPlainTextCredentialStore(tests.TestCase):
1752
1753
    def test_decode_password(self):
1754
        r = config.credential_store_registry
1755
        plain_text = r.get_credential_store()
1756
        decoded = plain_text.decode_password(dict(password='secret'))
1757
        self.assertEquals('secret', decoded)
1758
1759
2900.2.14 by Vincent Ladeuil
More tests.
1760
# 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.
1761
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1762
# test_user_password_in_url
1763
# test_user_in_url_password_from_config
1764
# test_user_in_url_password_prompted
1765
# test_user_in_config
1766
# test_user_getpass.getuser
1767
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1768
class TestAuthenticationRing(tests.TestCaseWithTransport):
1769
    pass