/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_config.py

  • Committer: Martin Pool
  • Date: 2008-05-02 05:43:54 UTC
  • mfrom: (3287.15.2 1.3)
  • mto: This revision was merged to the branch mainline in revision 3403.
  • Revision ID: mbp@sourcefrog.net-20080502054354-t1ah9qqd1a156v73
merge 1.3.1 back into trunk
(news update only, the fix for #208418 was already merged)

Show diffs side-by-side

added added

removed removed

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