/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: v.ladeuil+lp at free
  • Date: 2006-10-12 14:29:32 UTC
  • mto: (2145.1.1 keepalive)
  • mto: This revision was merged to the branch mainline in revision 2146.
  • Revision ID: v.ladeuil+lp@free.fr-20061012142932-7221fe16d2b48fa3
Shuffle http related test code. Hopefully it ends up at the right place :)

* bzrlib/tests/HttpServer.py: 
New file. bzrlib.tests.ChrootedTestCase use HttpServer. So the
class can't be defined in bzrlib.tests.HTTPUtils because it
creates a circular dependency (bzrlib.tests.HTTPUtils needs to
import bzrlib.tests).

* bzrlib/transport/http/_urllib.py: 
Transfer test server definition to bzrlib.tests.HttpServer. Clean
up imports.

* bzrlib/transport/http/_pycurl.py: 
Transfer test server definition to bzrlib.tests.HttpServer. Clean
up imports.

* bzrlib/transport/http/__init__.py: 
Transfer all test related code to either bzrlib.tests.HttpServer
and bzrlib.tests.HTTPUtils.
Fix all use of TransportNotPossible and InvalidURL by prefixing it
by 'errors.' (this seems to be the preferred way in the rest of
bzr).
Get rid of unused imports.

* bzrlib/tests/test_transport.py:
(ReadonlyDecoratorTransportTest.test_local_parameters,
FakeNFSDecoratorTests.test_http_parameters): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

* bzrlib/tests/test_sftp_transport.py:
(set_test_transport_to_sftp): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

* bzrlib/tests/test_selftest.py:
(TestTestCaseWithTransport.test_get_readonly_url_http): Use
HttpServer from bzrlib.tests.HttpServer instead of
bzrlib.transport.http.

* bzrlib/tests/test_repository.py: 
Does *not* use HttpServer.

* bzrlib/tests/test_http.py: 
Build on top of bzrlib.tests.HttpServer and bzrlib.tests.HTTPUtils
instead of bzrlib.transport.http.

* bzrlib/tests/test_bzrdir.py:
(ChrootedTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/branch_implementations/test_http.py:
(HTTPBranchTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/branch_implementations/test_branch.py:
(ChrootedTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/__init__.py:
(ChrootedTestCase.setUp): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 by 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 bzrlib.util.configobj.configobj import ConfigObj, ConfigObjError
 
21
from cStringIO import StringIO
 
22
import os
 
23
import sys
 
24
 
 
25
#import bzrlib specific imports here
 
26
from bzrlib import (
 
27
    config,
 
28
    errors,
 
29
    osutils,
 
30
    urlutils,
 
31
    )
 
32
from bzrlib.branch import Branch
 
33
from bzrlib.bzrdir import BzrDir
 
34
from bzrlib.tests import TestCase, TestCaseInTempDir, TestCaseWithTransport
 
35
 
 
36
 
 
37
sample_long_alias="log -r-15..-1 --line"
 
38
sample_config_text = ("[DEFAULT]\n"
 
39
                      u"email=Erik B\u00e5gfors <erik@bagfors.nu>\n"
 
40
                      "editor=vim\n"
 
41
                      "gpg_signing_command=gnome-gpg\n"
 
42
                      "log_format=short\n"
 
43
                      "user_global_option=something\n"
 
44
                      "[ALIASES]\n"
 
45
                      "h=help\n"
 
46
                      "ll=" + sample_long_alias + "\n")
 
47
 
 
48
 
 
49
sample_always_signatures = ("[DEFAULT]\n"
 
50
                            "check_signatures=ignore\n"
 
51
                            "create_signatures=always")
 
52
 
 
53
 
 
54
sample_ignore_signatures = ("[DEFAULT]\n"
 
55
                            "check_signatures=require\n"
 
56
                            "create_signatures=never")
 
57
 
 
58
 
 
59
sample_maybe_signatures = ("[DEFAULT]\n"
 
60
                            "check_signatures=ignore\n"
 
61
                            "create_signatures=when-required")
 
62
 
 
63
 
 
64
sample_branches_text = ("[http://www.example.com]\n"
 
65
                        "# Top level policy\n"
 
66
                        "email=Robert Collins <robertc@example.org>\n"
 
67
                        "[http://www.example.com/ignoreparent]\n"
 
68
                        "# different project: ignore parent dir config\n"
 
69
                        "ignore_parents=true\n"
 
70
                        "[http://www.example.com/norecurse]\n"
 
71
                        "# configuration items that only apply to this dir\n"
 
72
                        "recurse=false\n"
 
73
                        "[/b/]\n"
 
74
                        "check_signatures=require\n"
 
75
                        "# test trailing / matching with no children\n"
 
76
                        "[/a/]\n"
 
77
                        "check_signatures=check-available\n"
 
78
                        "gpg_signing_command=false\n"
 
79
                        "user_local_option=local\n"
 
80
                        "# test trailing / matching\n"
 
81
                        "[/a/*]\n"
 
82
                        "#subdirs will match but not the parent\n"
 
83
                        "[/a/c]\n"
 
84
                        "check_signatures=ignore\n"
 
85
                        "post_commit=bzrlib.tests.test_config.post_commit\n"
 
86
                        "#testing explicit beats globs\n")
 
87
 
 
88
 
 
89
 
 
90
class InstrumentedConfigObj(object):
 
91
    """A config obj look-enough-alike to record calls made to it."""
 
92
 
 
93
    def __contains__(self, thing):
 
94
        self._calls.append(('__contains__', thing))
 
95
        return False
 
96
 
 
97
    def __getitem__(self, key):
 
98
        self._calls.append(('__getitem__', key))
 
99
        return self
 
100
 
 
101
    def __init__(self, input, encoding=None):
 
102
        self._calls = [('__init__', input, encoding)]
 
103
 
 
104
    def __setitem__(self, key, value):
 
105
        self._calls.append(('__setitem__', key, value))
 
106
 
 
107
    def write(self, arg):
 
108
        self._calls.append(('write',))
 
109
 
 
110
 
 
111
class FakeBranch(object):
 
112
 
 
113
    def __init__(self, base=None, user_id=None):
 
114
        if base is None:
 
115
            self.base = "http://example.com/branches/demo"
 
116
        else:
 
117
            self.base = base
 
118
        self.control_files = FakeControlFiles(user_id=user_id)
 
119
 
 
120
    def lock_write(self):
 
121
        pass
 
122
 
 
123
    def unlock(self):
 
124
        pass
 
125
 
 
126
 
 
127
class FakeControlFiles(object):
 
128
 
 
129
    def __init__(self, user_id=None):
 
130
        self.email = user_id
 
131
        self.files = {}
 
132
 
 
133
    def get_utf8(self, filename):
 
134
        if filename != 'email':
 
135
            raise NotImplementedError
 
136
        if self.email is not None:
 
137
            return StringIO(self.email)
 
138
        raise errors.NoSuchFile(filename)
 
139
 
 
140
    def get(self, filename):
 
141
        try:
 
142
            return StringIO(self.files[filename])
 
143
        except KeyError:
 
144
            raise errors.NoSuchFile(filename)
 
145
 
 
146
    def put(self, filename, fileobj):
 
147
        self.files[filename] = fileobj.read()
 
148
 
 
149
 
 
150
class InstrumentedConfig(config.Config):
 
151
    """An instrumented config that supplies stubs for template methods."""
 
152
    
 
153
    def __init__(self):
 
154
        super(InstrumentedConfig, self).__init__()
 
155
        self._calls = []
 
156
        self._signatures = config.CHECK_NEVER
 
157
 
 
158
    def _get_user_id(self):
 
159
        self._calls.append('_get_user_id')
 
160
        return "Robert Collins <robert.collins@example.org>"
 
161
 
 
162
    def _get_signature_checking(self):
 
163
        self._calls.append('_get_signature_checking')
 
164
        return self._signatures
 
165
 
 
166
 
 
167
bool_config = """[DEFAULT]
 
168
active = true
 
169
inactive = false
 
170
[UPPERCASE]
 
171
active = True
 
172
nonactive = False
 
173
"""
 
174
class TestConfigObj(TestCase):
 
175
    def test_get_bool(self):
 
176
        from bzrlib.config import ConfigObj
 
177
        co = ConfigObj(StringIO(bool_config))
 
178
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
 
179
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
 
180
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
 
181
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
 
182
 
 
183
 
 
184
class TestConfig(TestCase):
 
185
 
 
186
    def test_constructs(self):
 
187
        config.Config()
 
188
 
 
189
    def test_no_default_editor(self):
 
190
        self.assertRaises(NotImplementedError, config.Config().get_editor)
 
191
 
 
192
    def test_user_email(self):
 
193
        my_config = InstrumentedConfig()
 
194
        self.assertEqual('robert.collins@example.org', my_config.user_email())
 
195
        self.assertEqual(['_get_user_id'], my_config._calls)
 
196
 
 
197
    def test_username(self):
 
198
        my_config = InstrumentedConfig()
 
199
        self.assertEqual('Robert Collins <robert.collins@example.org>',
 
200
                         my_config.username())
 
201
        self.assertEqual(['_get_user_id'], my_config._calls)
 
202
 
 
203
    def test_signatures_default(self):
 
204
        my_config = config.Config()
 
205
        self.assertFalse(my_config.signature_needed())
 
206
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
207
                         my_config.signature_checking())
 
208
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
 
209
                         my_config.signing_policy())
 
210
 
 
211
    def test_signatures_template_method(self):
 
212
        my_config = InstrumentedConfig()
 
213
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
214
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
215
 
 
216
    def test_signatures_template_method_none(self):
 
217
        my_config = InstrumentedConfig()
 
218
        my_config._signatures = None
 
219
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
220
                         my_config.signature_checking())
 
221
        self.assertEqual(['_get_signature_checking'], my_config._calls)
 
222
 
 
223
    def test_gpg_signing_command_default(self):
 
224
        my_config = config.Config()
 
225
        self.assertEqual('gpg', my_config.gpg_signing_command())
 
226
 
 
227
    def test_get_user_option_default(self):
 
228
        my_config = config.Config()
 
229
        self.assertEqual(None, my_config.get_user_option('no_option'))
 
230
 
 
231
    def test_post_commit_default(self):
 
232
        my_config = config.Config()
 
233
        self.assertEqual(None, my_config.post_commit())
 
234
 
 
235
    def test_log_format_default(self):
 
236
        my_config = config.Config()
 
237
        self.assertEqual('long', my_config.log_format())
 
238
 
 
239
 
 
240
class TestConfigPath(TestCase):
 
241
 
 
242
    def setUp(self):
 
243
        super(TestConfigPath, self).setUp()
 
244
        self.old_home = os.environ.get('HOME', None)
 
245
        self.old_appdata = os.environ.get('APPDATA', None)
 
246
        os.environ['HOME'] = '/home/bogus'
 
247
        os.environ['APPDATA'] = \
 
248
            r'C:\Documents and Settings\bogus\Application Data'
 
249
 
 
250
    def tearDown(self):
 
251
        if self.old_home is None:
 
252
            del os.environ['HOME']
 
253
        else:
 
254
            os.environ['HOME'] = self.old_home
 
255
        if self.old_appdata is None:
 
256
            del os.environ['APPDATA']
 
257
        else:
 
258
            os.environ['APPDATA'] = self.old_appdata
 
259
        super(TestConfigPath, self).tearDown()
 
260
    
 
261
    def test_config_dir(self):
 
262
        if sys.platform == 'win32':
 
263
            self.assertEqual(config.config_dir(), 
 
264
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0')
 
265
        else:
 
266
            self.assertEqual(config.config_dir(), '/home/bogus/.bazaar')
 
267
 
 
268
    def test_config_filename(self):
 
269
        if sys.platform == 'win32':
 
270
            self.assertEqual(config.config_filename(), 
 
271
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/bazaar.conf')
 
272
        else:
 
273
            self.assertEqual(config.config_filename(),
 
274
                             '/home/bogus/.bazaar/bazaar.conf')
 
275
 
 
276
    def test_branches_config_filename(self):
 
277
        if sys.platform == 'win32':
 
278
            self.assertEqual(config.branches_config_filename(), 
 
279
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/branches.conf')
 
280
        else:
 
281
            self.assertEqual(config.branches_config_filename(),
 
282
                             '/home/bogus/.bazaar/branches.conf')
 
283
 
 
284
    def test_locations_config_filename(self):
 
285
        if sys.platform == 'win32':
 
286
            self.assertEqual(config.locations_config_filename(), 
 
287
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0/locations.conf')
 
288
        else:
 
289
            self.assertEqual(config.locations_config_filename(),
 
290
                             '/home/bogus/.bazaar/locations.conf')
 
291
 
 
292
class TestIniConfig(TestCase):
 
293
 
 
294
    def test_contructs(self):
 
295
        my_config = config.IniBasedConfig("nothing")
 
296
 
 
297
    def test_from_fp(self):
 
298
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
299
        my_config = config.IniBasedConfig(None)
 
300
        self.failUnless(
 
301
            isinstance(my_config._get_parser(file=config_file),
 
302
                        ConfigObj))
 
303
 
 
304
    def test_cached(self):
 
305
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
306
        my_config = config.IniBasedConfig(None)
 
307
        parser = my_config._get_parser(file=config_file)
 
308
        self.failUnless(my_config._get_parser() is parser)
 
309
 
 
310
 
 
311
class TestGetConfig(TestCase):
 
312
 
 
313
    def test_constructs(self):
 
314
        my_config = config.GlobalConfig()
 
315
 
 
316
    def test_calls_read_filenames(self):
 
317
        # replace the class that is constructured, to check its parameters
 
318
        oldparserclass = config.ConfigObj
 
319
        config.ConfigObj = InstrumentedConfigObj
 
320
        my_config = config.GlobalConfig()
 
321
        try:
 
322
            parser = my_config._get_parser()
 
323
        finally:
 
324
            config.ConfigObj = oldparserclass
 
325
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
326
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
 
327
                                          'utf-8')])
 
328
 
 
329
 
 
330
class TestBranchConfig(TestCaseWithTransport):
 
331
 
 
332
    def test_constructs(self):
 
333
        branch = FakeBranch()
 
334
        my_config = config.BranchConfig(branch)
 
335
        self.assertRaises(TypeError, config.BranchConfig)
 
336
 
 
337
    def test_get_location_config(self):
 
338
        branch = FakeBranch()
 
339
        my_config = config.BranchConfig(branch)
 
340
        location_config = my_config._get_location_config()
 
341
        self.assertEqual(branch.base, location_config.location)
 
342
        self.failUnless(location_config is my_config._get_location_config())
 
343
 
 
344
    def test_get_config(self):
 
345
        """The Branch.get_config method works properly"""
 
346
        b = BzrDir.create_standalone_workingtree('.').branch
 
347
        my_config = b.get_config()
 
348
        self.assertIs(my_config.get_user_option('wacky'), None)
 
349
        my_config.set_user_option('wacky', 'unlikely')
 
350
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
 
351
 
 
352
        # Ensure we get the same thing if we start again
 
353
        b2 = Branch.open('.')
 
354
        my_config2 = b2.get_config()
 
355
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
 
356
 
 
357
    def test_has_explicit_nickname(self):
 
358
        b = self.make_branch('.')
 
359
        self.assertFalse(b.get_config().has_explicit_nickname())
 
360
        b.nick = 'foo'
 
361
        self.assertTrue(b.get_config().has_explicit_nickname())
 
362
 
 
363
    def test_config_url(self):
 
364
        """The Branch.get_config will use section that uses a local url"""
 
365
        branch = self.make_branch('branch')
 
366
        self.assertEqual('branch', branch.nick)
 
367
 
 
368
        locations = config.locations_config_filename()
 
369
        config.ensure_config_dir_exists()
 
370
        local_url = urlutils.local_path_to_url('branch')
 
371
        open(locations, 'wb').write('[%s]\nnickname = foobar' 
 
372
                                    % (local_url,))
 
373
        self.assertEqual('foobar', branch.nick)
 
374
 
 
375
    def test_config_local_path(self):
 
376
        """The Branch.get_config will use a local system path"""
 
377
        branch = self.make_branch('branch')
 
378
        self.assertEqual('branch', branch.nick)
 
379
 
 
380
        locations = config.locations_config_filename()
 
381
        config.ensure_config_dir_exists()
 
382
        open(locations, 'wb').write('[%s/branch]\nnickname = barry' 
 
383
                                    % (osutils.getcwd().encode('utf8'),))
 
384
        self.assertEqual('barry', branch.nick)
 
385
 
 
386
    def test_config_creates_local(self):
 
387
        """Creating a new entry in config uses a local path."""
 
388
        branch = self.make_branch('branch')
 
389
        branch.set_push_location('http://foobar')
 
390
        locations = config.locations_config_filename()
 
391
        local_path = osutils.getcwd().encode('utf8')
 
392
        # Surprisingly ConfigObj doesn't create a trailing newline
 
393
        self.check_file_contents(locations,
 
394
            '[%s/branch]\npush_location = http://foobar' % (local_path,))
 
395
 
 
396
 
 
397
class TestGlobalConfigItems(TestCase):
 
398
 
 
399
    def test_user_id(self):
 
400
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
401
        my_config = config.GlobalConfig()
 
402
        my_config._parser = my_config._get_parser(file=config_file)
 
403
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
404
                         my_config._get_user_id())
 
405
 
 
406
    def test_absent_user_id(self):
 
407
        config_file = StringIO("")
 
408
        my_config = config.GlobalConfig()
 
409
        my_config._parser = my_config._get_parser(file=config_file)
 
410
        self.assertEqual(None, my_config._get_user_id())
 
411
 
 
412
    def test_configured_editor(self):
 
413
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
414
        my_config = config.GlobalConfig()
 
415
        my_config._parser = my_config._get_parser(file=config_file)
 
416
        self.assertEqual("vim", my_config.get_editor())
 
417
 
 
418
    def test_signatures_always(self):
 
419
        config_file = StringIO(sample_always_signatures)
 
420
        my_config = config.GlobalConfig()
 
421
        my_config._parser = my_config._get_parser(file=config_file)
 
422
        self.assertEqual(config.CHECK_NEVER,
 
423
                         my_config.signature_checking())
 
424
        self.assertEqual(config.SIGN_ALWAYS,
 
425
                         my_config.signing_policy())
 
426
        self.assertEqual(True, my_config.signature_needed())
 
427
 
 
428
    def test_signatures_if_possible(self):
 
429
        config_file = StringIO(sample_maybe_signatures)
 
430
        my_config = config.GlobalConfig()
 
431
        my_config._parser = my_config._get_parser(file=config_file)
 
432
        self.assertEqual(config.CHECK_NEVER,
 
433
                         my_config.signature_checking())
 
434
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
 
435
                         my_config.signing_policy())
 
436
        self.assertEqual(False, my_config.signature_needed())
 
437
 
 
438
    def test_signatures_ignore(self):
 
439
        config_file = StringIO(sample_ignore_signatures)
 
440
        my_config = config.GlobalConfig()
 
441
        my_config._parser = my_config._get_parser(file=config_file)
 
442
        self.assertEqual(config.CHECK_ALWAYS,
 
443
                         my_config.signature_checking())
 
444
        self.assertEqual(config.SIGN_NEVER,
 
445
                         my_config.signing_policy())
 
446
        self.assertEqual(False, my_config.signature_needed())
 
447
 
 
448
    def _get_sample_config(self):
 
449
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
450
        my_config = config.GlobalConfig()
 
451
        my_config._parser = my_config._get_parser(file=config_file)
 
452
        return my_config
 
453
 
 
454
    def test_gpg_signing_command(self):
 
455
        my_config = self._get_sample_config()
 
456
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
 
457
        self.assertEqual(False, my_config.signature_needed())
 
458
 
 
459
    def _get_empty_config(self):
 
460
        config_file = StringIO("")
 
461
        my_config = config.GlobalConfig()
 
462
        my_config._parser = my_config._get_parser(file=config_file)
 
463
        return my_config
 
464
 
 
465
    def test_gpg_signing_command_unset(self):
 
466
        my_config = self._get_empty_config()
 
467
        self.assertEqual("gpg", my_config.gpg_signing_command())
 
468
 
 
469
    def test_get_user_option_default(self):
 
470
        my_config = self._get_empty_config()
 
471
        self.assertEqual(None, my_config.get_user_option('no_option'))
 
472
 
 
473
    def test_get_user_option_global(self):
 
474
        my_config = self._get_sample_config()
 
475
        self.assertEqual("something",
 
476
                         my_config.get_user_option('user_global_option'))
 
477
        
 
478
    def test_post_commit_default(self):
 
479
        my_config = self._get_sample_config()
 
480
        self.assertEqual(None, my_config.post_commit())
 
481
 
 
482
    def test_configured_logformat(self):
 
483
        my_config = self._get_sample_config()
 
484
        self.assertEqual("short", my_config.log_format())
 
485
 
 
486
    def test_get_alias(self):
 
487
        my_config = self._get_sample_config()
 
488
        self.assertEqual('help', my_config.get_alias('h'))
 
489
 
 
490
    def test_get_no_alias(self):
 
491
        my_config = self._get_sample_config()
 
492
        self.assertEqual(None, my_config.get_alias('foo'))
 
493
 
 
494
    def test_get_long_alias(self):
 
495
        my_config = self._get_sample_config()
 
496
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
 
497
 
 
498
 
 
499
class TestLocationConfig(TestCaseInTempDir):
 
500
 
 
501
    def test_constructs(self):
 
502
        my_config = config.LocationConfig('http://example.com')
 
503
        self.assertRaises(TypeError, config.LocationConfig)
 
504
 
 
505
    def test_branch_calls_read_filenames(self):
 
506
        # This is testing the correct file names are provided.
 
507
        # TODO: consolidate with the test for GlobalConfigs filename checks.
 
508
        #
 
509
        # replace the class that is constructured, to check its parameters
 
510
        oldparserclass = config.ConfigObj
 
511
        config.ConfigObj = InstrumentedConfigObj
 
512
        try:
 
513
            my_config = config.LocationConfig('http://www.example.com')
 
514
            parser = my_config._get_parser()
 
515
        finally:
 
516
            config.ConfigObj = oldparserclass
 
517
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
 
518
        self.assertEqual(parser._calls,
 
519
                         [('__init__', config.locations_config_filename(),
 
520
                           'utf-8')])
 
521
        config.ensure_config_dir_exists()
 
522
        #os.mkdir(config.config_dir())
 
523
        f = file(config.branches_config_filename(), 'wb')
 
524
        f.write('')
 
525
        f.close()
 
526
        oldparserclass = config.ConfigObj
 
527
        config.ConfigObj = InstrumentedConfigObj
 
528
        try:
 
529
            my_config = config.LocationConfig('http://www.example.com')
 
530
            parser = my_config._get_parser()
 
531
        finally:
 
532
            config.ConfigObj = oldparserclass
 
533
 
 
534
    def test_get_global_config(self):
 
535
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
 
536
        global_config = my_config._get_global_config()
 
537
        self.failUnless(isinstance(global_config, config.GlobalConfig))
 
538
        self.failUnless(global_config is my_config._get_global_config())
 
539
 
 
540
    def test__get_matching_sections_no_match(self):
 
541
        self.get_branch_config('/')
 
542
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
543
        
 
544
    def test__get_matching_sections_exact(self):
 
545
        self.get_branch_config('http://www.example.com')
 
546
        self.assertEqual([('http://www.example.com', '')],
 
547
                         self.my_location_config._get_matching_sections())
 
548
   
 
549
    def test__get_matching_sections_suffix_does_not(self):
 
550
        self.get_branch_config('http://www.example.com-com')
 
551
        self.assertEqual([], self.my_location_config._get_matching_sections())
 
552
 
 
553
    def test__get_matching_sections_subdir_recursive(self):
 
554
        self.get_branch_config('http://www.example.com/com')
 
555
        self.assertEqual([('http://www.example.com', 'com')],
 
556
                         self.my_location_config._get_matching_sections())
 
557
 
 
558
    def test__get_matching_sections_ignoreparent(self):
 
559
        self.get_branch_config('http://www.example.com/ignoreparent')
 
560
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
 
561
                         self.my_location_config._get_matching_sections())
 
562
 
 
563
    def test__get_matching_sections_ignoreparent_subdir(self):
 
564
        self.get_branch_config(
 
565
            'http://www.example.com/ignoreparent/childbranch')
 
566
        self.assertEqual([('http://www.example.com/ignoreparent', 'childbranch')],
 
567
                         self.my_location_config._get_matching_sections())
 
568
 
 
569
    def test__get_matching_sections_norecurse(self):
 
570
        self.get_branch_config('http://www.example.com/norecurse')
 
571
        self.assertEqual([('http://www.example.com/norecurse', ''),
 
572
                          ('http://www.example.com', 'norecurse')],
 
573
                         self.my_location_config._get_matching_sections())
 
574
 
 
575
    def test__get_matching_sections_norecurse_subdir(self):
 
576
        self.get_branch_config(
 
577
            'http://www.example.com/norecurse/childbranch')
 
578
        self.assertEqual([('http://www.example.com', 'norecurse/childbranch')],
 
579
                         self.my_location_config._get_matching_sections())
 
580
 
 
581
    def test__get_matching_sections_subdir_trailing_slash(self):
 
582
        self.get_branch_config('/b')
 
583
        self.assertEqual([('/b/', '')],
 
584
                         self.my_location_config._get_matching_sections())
 
585
 
 
586
    def test__get_matching_sections_subdir_child(self):
 
587
        self.get_branch_config('/a/foo')
 
588
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
 
589
                         self.my_location_config._get_matching_sections())
 
590
 
 
591
    def test__get_matching_sections_subdir_child_child(self):
 
592
        self.get_branch_config('/a/foo/bar')
 
593
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
 
594
                         self.my_location_config._get_matching_sections())
 
595
 
 
596
    def test__get_matching_sections_trailing_slash_with_children(self):
 
597
        self.get_branch_config('/a/')
 
598
        self.assertEqual([('/a/', '')],
 
599
                         self.my_location_config._get_matching_sections())
 
600
 
 
601
    def test__get_matching_sections_explicit_over_glob(self):
 
602
        # XXX: 2006-09-08 jamesh
 
603
        # This test only passes because ord('c') > ord('*').  If there
 
604
        # was a config section for '/a/?', it would get precedence
 
605
        # over '/a/c'.
 
606
        self.get_branch_config('/a/c')
 
607
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
 
608
                         self.my_location_config._get_matching_sections())
 
609
 
 
610
    def test_location_without_username(self):
 
611
        self.get_branch_config('http://www.example.com/ignoreparent')
 
612
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
613
                         self.my_config.username())
 
614
 
 
615
    def test_location_not_listed(self):
 
616
        """Test that the global username is used when no location matches"""
 
617
        self.get_branch_config('/home/robertc/sources')
 
618
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
 
619
                         self.my_config.username())
 
620
 
 
621
    def test_overriding_location(self):
 
622
        self.get_branch_config('http://www.example.com/foo')
 
623
        self.assertEqual('Robert Collins <robertc@example.org>',
 
624
                         self.my_config.username())
 
625
 
 
626
    def test_signatures_not_set(self):
 
627
        self.get_branch_config('http://www.example.com',
 
628
                                 global_config=sample_ignore_signatures)
 
629
        self.assertEqual(config.CHECK_ALWAYS,
 
630
                         self.my_config.signature_checking())
 
631
        self.assertEqual(config.SIGN_NEVER,
 
632
                         self.my_config.signing_policy())
 
633
 
 
634
    def test_signatures_never(self):
 
635
        self.get_branch_config('/a/c')
 
636
        self.assertEqual(config.CHECK_NEVER,
 
637
                         self.my_config.signature_checking())
 
638
        
 
639
    def test_signatures_when_available(self):
 
640
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
 
641
        self.assertEqual(config.CHECK_IF_POSSIBLE,
 
642
                         self.my_config.signature_checking())
 
643
        
 
644
    def test_signatures_always(self):
 
645
        self.get_branch_config('/b')
 
646
        self.assertEqual(config.CHECK_ALWAYS,
 
647
                         self.my_config.signature_checking())
 
648
        
 
649
    def test_gpg_signing_command(self):
 
650
        self.get_branch_config('/b')
 
651
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
 
652
 
 
653
    def test_gpg_signing_command_missing(self):
 
654
        self.get_branch_config('/a')
 
655
        self.assertEqual("false", self.my_config.gpg_signing_command())
 
656
 
 
657
    def test_get_user_option_global(self):
 
658
        self.get_branch_config('/a')
 
659
        self.assertEqual('something',
 
660
                         self.my_config.get_user_option('user_global_option'))
 
661
 
 
662
    def test_get_user_option_local(self):
 
663
        self.get_branch_config('/a')
 
664
        self.assertEqual('local',
 
665
                         self.my_config.get_user_option('user_local_option'))
 
666
 
 
667
    def test_post_commit_default(self):
 
668
        self.get_branch_config('/a/c')
 
669
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
670
                         self.my_config.post_commit())
 
671
 
 
672
    def get_branch_config(self, location, global_config=None):
 
673
        if global_config is None:
 
674
            global_file = StringIO(sample_config_text.encode('utf-8'))
 
675
        else:
 
676
            global_file = StringIO(global_config.encode('utf-8'))
 
677
        branches_file = StringIO(sample_branches_text.encode('utf-8'))
 
678
        self.my_config = config.BranchConfig(FakeBranch(location))
 
679
        # Force location config to use specified file
 
680
        self.my_location_config = self.my_config._get_location_config()
 
681
        self.my_location_config._get_parser(branches_file)
 
682
        # Force global config to use specified file
 
683
        self.my_config._get_global_config()._get_parser(global_file)
 
684
 
 
685
    def test_set_user_setting_sets_and_saves(self):
 
686
        self.get_branch_config('/a/c')
 
687
        record = InstrumentedConfigObj("foo")
 
688
        self.my_location_config._parser = record
 
689
 
 
690
        real_mkdir = os.mkdir
 
691
        self.created = False
 
692
        def checked_mkdir(path, mode=0777):
 
693
            self.log('making directory: %s', path)
 
694
            real_mkdir(path, mode)
 
695
            self.created = True
 
696
 
 
697
        os.mkdir = checked_mkdir
 
698
        try:
 
699
            self.my_config.set_user_option('foo', 'bar', local=True)
 
700
        finally:
 
701
            os.mkdir = real_mkdir
 
702
 
 
703
        self.failUnless(self.created, 'Failed to create ~/.bazaar')
 
704
        self.assertEqual([('__contains__', '/a/c'),
 
705
                          ('__contains__', '/a/c/'),
 
706
                          ('__setitem__', '/a/c', {}),
 
707
                          ('__getitem__', '/a/c'),
 
708
                          ('__setitem__', 'foo', 'bar'),
 
709
                          ('write',)],
 
710
                         record._calls[1:])
 
711
 
 
712
    def test_set_user_setting_sets_and_saves2(self):
 
713
        self.get_branch_config('/a/c')
 
714
        self.assertIs(self.my_config.get_user_option('foo'), None)
 
715
        self.my_config.set_user_option('foo', 'bar')
 
716
        self.assertEqual(
 
717
            self.my_config.branch.control_files.files['branch.conf'], 
 
718
            'foo = bar')
 
719
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
 
720
        self.my_config.set_user_option('foo', 'baz', local=True)
 
721
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
722
        self.my_config.set_user_option('foo', 'qux')
 
723
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
 
724
        
 
725
 
 
726
precedence_global = 'option = global'
 
727
precedence_branch = 'option = branch'
 
728
precedence_location = """
 
729
[http://]
 
730
recurse = true
 
731
option = recurse
 
732
[http://example.com/specific]
 
733
option = exact
 
734
"""
 
735
 
 
736
 
 
737
class TestBranchConfigItems(TestCaseInTempDir):
 
738
 
 
739
    def get_branch_config(self, global_config=None, location=None, 
 
740
                          location_config=None, branch_data_config=None):
 
741
        my_config = config.BranchConfig(FakeBranch(location))
 
742
        if global_config is not None:
 
743
            global_file = StringIO(global_config.encode('utf-8'))
 
744
            my_config._get_global_config()._get_parser(global_file)
 
745
        self.my_location_config = my_config._get_location_config()
 
746
        if location_config is not None:
 
747
            location_file = StringIO(location_config.encode('utf-8'))
 
748
            self.my_location_config._get_parser(location_file)
 
749
        if branch_data_config is not None:
 
750
            my_config.branch.control_files.files['branch.conf'] = \
 
751
                branch_data_config
 
752
        return my_config
 
753
 
 
754
    def test_user_id(self):
 
755
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
 
756
        my_config = config.BranchConfig(branch)
 
757
        self.assertEqual("Robert Collins <robertc@example.net>",
 
758
                         my_config.username())
 
759
        branch.control_files.email = "John"
 
760
        my_config.set_user_option('email', 
 
761
                                  "Robert Collins <robertc@example.org>")
 
762
        self.assertEqual("John", my_config.username())
 
763
        branch.control_files.email = None
 
764
        self.assertEqual("Robert Collins <robertc@example.org>",
 
765
                         my_config.username())
 
766
 
 
767
    def test_not_set_in_branch(self):
 
768
        my_config = self.get_branch_config(sample_config_text)
 
769
        my_config.branch.control_files.email = None
 
770
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
 
771
                         my_config._get_user_id())
 
772
        my_config.branch.control_files.email = "John"
 
773
        self.assertEqual("John", my_config._get_user_id())
 
774
 
 
775
    def test_BZR_EMAIL_OVERRIDES(self):
 
776
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
 
777
        branch = FakeBranch()
 
778
        my_config = config.BranchConfig(branch)
 
779
        self.assertEqual("Robert Collins <robertc@example.org>",
 
780
                         my_config.username())
 
781
    
 
782
    def test_signatures_forced(self):
 
783
        my_config = self.get_branch_config(
 
784
            global_config=sample_always_signatures)
 
785
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
786
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
787
        self.assertTrue(my_config.signature_needed())
 
788
 
 
789
    def test_signatures_forced_branch(self):
 
790
        my_config = self.get_branch_config(
 
791
            global_config=sample_ignore_signatures,
 
792
            branch_data_config=sample_always_signatures)
 
793
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
 
794
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
 
795
        self.assertTrue(my_config.signature_needed())
 
796
 
 
797
    def test_gpg_signing_command(self):
 
798
        my_config = self.get_branch_config(
 
799
            # branch data cannot set gpg_signing_command
 
800
            branch_data_config="gpg_signing_command=pgp")
 
801
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
802
        my_config._get_global_config()._get_parser(config_file)
 
803
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
 
804
 
 
805
    def test_get_user_option_global(self):
 
806
        branch = FakeBranch()
 
807
        my_config = config.BranchConfig(branch)
 
808
        config_file = StringIO(sample_config_text.encode('utf-8'))
 
809
        (my_config._get_global_config()._get_parser(config_file))
 
810
        self.assertEqual('something',
 
811
                         my_config.get_user_option('user_global_option'))
 
812
 
 
813
    def test_post_commit_default(self):
 
814
        branch = FakeBranch()
 
815
        my_config = self.get_branch_config(sample_config_text, '/a/c',
 
816
                                           sample_branches_text)
 
817
        self.assertEqual(my_config.branch.base, '/a/c')
 
818
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
819
                         my_config.post_commit())
 
820
        my_config.set_user_option('post_commit', 'rmtree_root')
 
821
        # post-commit is ignored when bresent in branch data
 
822
        self.assertEqual('bzrlib.tests.test_config.post_commit',
 
823
                         my_config.post_commit())
 
824
        my_config.set_user_option('post_commit', 'rmtree_root', local=True)
 
825
        self.assertEqual('rmtree_root', my_config.post_commit())
 
826
 
 
827
    def test_config_precedence(self):
 
828
        my_config = self.get_branch_config(global_config=precedence_global)
 
829
        self.assertEqual(my_config.get_user_option('option'), 'global')
 
830
        my_config = self.get_branch_config(global_config=precedence_global, 
 
831
                                      branch_data_config=precedence_branch)
 
832
        self.assertEqual(my_config.get_user_option('option'), 'branch')
 
833
        my_config = self.get_branch_config(global_config=precedence_global, 
 
834
                                      branch_data_config=precedence_branch,
 
835
                                      location_config=precedence_location)
 
836
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
 
837
        my_config = self.get_branch_config(global_config=precedence_global, 
 
838
                                      branch_data_config=precedence_branch,
 
839
                                      location_config=precedence_location,
 
840
                                      location='http://example.com/specific')
 
841
        self.assertEqual(my_config.get_user_option('option'), 'exact')
 
842
 
 
843
 
 
844
class TestMailAddressExtraction(TestCase):
 
845
 
 
846
    def test_extract_email_address(self):
 
847
        self.assertEqual('jane@test.com',
 
848
                         config.extract_email_address('Jane <jane@test.com>'))
 
849
        self.assertRaises(errors.NoEmailInUsername,
 
850
                          config.extract_email_address, 'Jane Tester')