-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_config.py
executable file
·4953 lines (4139 loc) · 185 KB
/
test_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2005-2012 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""Tests for finding and reading the bzr config file[s]."""
# import system imports here
from cStringIO import StringIO
from textwrap import dedent
import os
import sys
import threading
from testtools import matchers
#import bzrlib specific imports here
from bzrlib import (
branch,
config,
controldir,
diff,
errors,
osutils,
mail_client,
ui,
urlutils,
registry as _mod_registry,
remote,
tests,
trace,
)
from bzrlib.symbol_versioning import (
deprecated_in,
)
from bzrlib.transport import remote as transport_remote
from bzrlib.tests import (
features,
scenarios,
test_server,
)
from bzrlib.util.configobj import configobj
def lockable_config_scenarios():
return [
('global',
{'config_class': config.GlobalConfig,
'config_args': [],
'config_section': 'DEFAULT'}),
('locations',
{'config_class': config.LocationConfig,
'config_args': ['.'],
'config_section': '.'}),]
load_tests = scenarios.load_tests_apply_scenarios
# Register helpers to build stores
config.test_store_builder_registry.register(
'configobj', lambda test: config.TransportIniFileStore(
test.get_transport(), 'configobj.conf'))
config.test_store_builder_registry.register(
'bazaar', lambda test: config.GlobalStore())
config.test_store_builder_registry.register(
'location', lambda test: config.LocationStore())
def build_backing_branch(test, relpath,
transport_class=None, server_class=None):
"""Test helper to create a backing branch only once.
Some tests needs multiple stores/stacks to check concurrent update
behaviours. As such, they need to build different branch *objects* even if
they share the branch on disk.
:param relpath: The relative path to the branch. (Note that the helper
should always specify the same relpath).
:param transport_class: The Transport class the test needs to use.
:param server_class: The server associated with the ``transport_class``
above.
Either both or neither of ``transport_class`` and ``server_class`` should
be specified.
"""
if transport_class is not None and server_class is not None:
test.transport_class = transport_class
test.transport_server = server_class
elif not (transport_class is None and server_class is None):
raise AssertionError('Specify both ``transport_class`` and '
'``server_class`` or neither of them')
if getattr(test, 'backing_branch', None) is None:
# First call, let's build the branch on disk
test.backing_branch = test.make_branch(relpath)
def build_branch_store(test):
build_backing_branch(test, 'branch')
b = branch.Branch.open('branch')
return config.BranchStore(b)
config.test_store_builder_registry.register('branch', build_branch_store)
def build_control_store(test):
build_backing_branch(test, 'branch')
b = controldir.ControlDir.open('branch')
return config.ControlStore(b)
config.test_store_builder_registry.register('control', build_control_store)
def build_remote_branch_store(test):
# There is only one permutation (but we won't be able to handle more with
# this design anyway)
(transport_class,
server_class) = transport_remote.get_test_permutations()[0]
build_backing_branch(test, 'branch', transport_class, server_class)
b = branch.Branch.open(test.get_url('branch'))
return config.BranchStore(b)
config.test_store_builder_registry.register('remote_branch',
build_remote_branch_store)
config.test_stack_builder_registry.register(
'bazaar', lambda test: config.GlobalStack())
config.test_stack_builder_registry.register(
'location', lambda test: config.LocationStack('.'))
def build_branch_stack(test):
build_backing_branch(test, 'branch')
b = branch.Branch.open('branch')
return config.BranchStack(b)
config.test_stack_builder_registry.register('branch', build_branch_stack)
def build_branch_only_stack(test):
# There is only one permutation (but we won't be able to handle more with
# this design anyway)
(transport_class,
server_class) = transport_remote.get_test_permutations()[0]
build_backing_branch(test, 'branch', transport_class, server_class)
b = branch.Branch.open(test.get_url('branch'))
return config.BranchOnlyStack(b)
config.test_stack_builder_registry.register('branch_only',
build_branch_only_stack)
def build_remote_control_stack(test):
# There is only one permutation (but we won't be able to handle more with
# this design anyway)
(transport_class,
server_class) = transport_remote.get_test_permutations()[0]
# We need only a bzrdir for this, not a full branch, but it's not worth
# creating a dedicated helper to create only the bzrdir
build_backing_branch(test, 'branch', transport_class, server_class)
b = branch.Branch.open(test.get_url('branch'))
return config.RemoteControlStack(b.bzrdir)
config.test_stack_builder_registry.register('remote_control',
build_remote_control_stack)
sample_long_alias="log -r-15..-1 --line"
sample_config_text = u"""
[DEFAULT]
email=Erik B\u00e5gfors <erik@bagfors.nu>
editor=vim
change_editor=vimdiff -of @new_path @old_path
gpg_signing_command=gnome-gpg
gpg_signing_key=DD4D5088
log_format=short
validate_signatures_in_log=true
acceptable_keys=amy
user_global_option=something
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
bzr.mergetool.newtool='"newtool with spaces" {this_temp}'
bzr.default_mergetool=sometool
[ALIASES]
h=help
ll=""" + sample_long_alias + "\n"
sample_always_signatures = """
[DEFAULT]
check_signatures=ignore
create_signatures=always
"""
sample_ignore_signatures = """
[DEFAULT]
check_signatures=require
create_signatures=never
"""
sample_maybe_signatures = """
[DEFAULT]
check_signatures=ignore
create_signatures=when-required
"""
sample_branches_text = """
[http://www.example.com]
# Top level policy
email=Robert Collins <robertc@example.org>
normal_option = normal
appendpath_option = append
appendpath_option:policy = appendpath
norecurse_option = norecurse
norecurse_option:policy = norecurse
[http://www.example.com/ignoreparent]
# different project: ignore parent dir config
ignore_parents=true
[http://www.example.com/norecurse]
# configuration items that only apply to this dir
recurse=false
normal_option = norecurse
[http://www.example.com/dir]
appendpath_option = normal
[/b/]
check_signatures=require
# test trailing / matching with no children
[/a/]
check_signatures=check-available
gpg_signing_command=false
gpg_signing_key=default
user_local_option=local
# test trailing / matching
[/a/*]
#subdirs will match but not the parent
[/a/c]
check_signatures=ignore
post_commit=bzrlib.tests.test_config.post_commit
#testing explicit beats globs
"""
def create_configs(test):
"""Create configuration files for a given test.
This requires creating a tree (and populate the ``test.tree`` attribute)
and its associated branch and will populate the following attributes:
- branch_config: A BranchConfig for the associated branch.
- locations_config : A LocationConfig for the associated branch
- bazaar_config: A GlobalConfig.
The tree and branch are created in a 'tree' subdirectory so the tests can
still use the test directory to stay outside of the branch.
"""
tree = test.make_branch_and_tree('tree')
test.tree = tree
test.branch_config = config.BranchConfig(tree.branch)
test.locations_config = config.LocationConfig(tree.basedir)
test.bazaar_config = config.GlobalConfig()
def create_configs_with_file_option(test):
"""Create configuration files with a ``file`` option set in each.
This builds on ``create_configs`` and add one ``file`` option in each
configuration with a value which allows identifying the configuration file.
"""
create_configs(test)
test.bazaar_config.set_user_option('file', 'bazaar')
test.locations_config.set_user_option('file', 'locations')
test.branch_config.set_user_option('file', 'branch')
class TestOptionsMixin:
def assertOptions(self, expected, conf):
# We don't care about the parser (as it will make tests hard to write
# and error-prone anyway)
self.assertThat([opt[:4] for opt in conf._get_options()],
matchers.Equals(expected))
class InstrumentedConfigObj(object):
"""A config obj look-enough-alike to record calls made to it."""
def __contains__(self, thing):
self._calls.append(('__contains__', thing))
return False
def __getitem__(self, key):
self._calls.append(('__getitem__', key))
return self
def __init__(self, input, encoding=None):
self._calls = [('__init__', input, encoding)]
def __setitem__(self, key, value):
self._calls.append(('__setitem__', key, value))
def __delitem__(self, key):
self._calls.append(('__delitem__', key))
def keys(self):
self._calls.append(('keys',))
return []
def reload(self):
self._calls.append(('reload',))
def write(self, arg):
self._calls.append(('write',))
def as_bool(self, value):
self._calls.append(('as_bool', value))
return False
def get_value(self, section, name):
self._calls.append(('get_value', section, name))
return None
class FakeBranch(object):
def __init__(self, base=None):
if base is None:
self.base = "http://example.com/branches/demo"
else:
self.base = base
self._transport = self.control_files = \
FakeControlFilesAndTransport()
def _get_config(self):
return config.TransportConfig(self._transport, 'branch.conf')
def lock_write(self):
pass
def unlock(self):
pass
class FakeControlFilesAndTransport(object):
def __init__(self):
self.files = {}
self._transport = self
def get(self, filename):
# from Transport
try:
return StringIO(self.files[filename])
except KeyError:
raise errors.NoSuchFile(filename)
def get_bytes(self, filename):
# from Transport
try:
return self.files[filename]
except KeyError:
raise errors.NoSuchFile(filename)
def put(self, filename, fileobj):
self.files[filename] = fileobj.read()
def put_file(self, filename, fileobj):
return self.put(filename, fileobj)
class InstrumentedConfig(config.Config):
"""An instrumented config that supplies stubs for template methods."""
def __init__(self):
super(InstrumentedConfig, self).__init__()
self._calls = []
self._signatures = config.CHECK_NEVER
def _get_user_id(self):
self._calls.append('_get_user_id')
return "Robert Collins <robert.collins@example.org>"
def _get_signature_checking(self):
self._calls.append('_get_signature_checking')
return self._signatures
def _get_change_editor(self):
self._calls.append('_get_change_editor')
return 'vimdiff -fo @new_path @old_path'
bool_config = """[DEFAULT]
active = true
inactive = false
[UPPERCASE]
active = True
nonactive = False
"""
class TestConfigObj(tests.TestCase):
def test_get_bool(self):
co = config.ConfigObj(StringIO(bool_config))
self.assertIs(co.get_bool('DEFAULT', 'active'), True)
self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
def test_hash_sign_in_value(self):
"""
Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
treated as comments when read in again. (#86838)
"""
co = config.ConfigObj()
co['test'] = 'foo#bar'
outfile = StringIO()
co.write(outfile=outfile)
lines = outfile.getvalue().splitlines()
self.assertEqual(lines, ['test = "foo#bar"'])
co2 = config.ConfigObj(lines)
self.assertEqual(co2['test'], 'foo#bar')
def test_triple_quotes(self):
# Bug #710410: if the value string has triple quotes
# then ConfigObj versions up to 4.7.2 will quote them wrong
# and won't able to read them back
triple_quotes_value = '''spam
""" that's my spam """
eggs'''
co = config.ConfigObj()
co['test'] = triple_quotes_value
# While writing this test another bug in ConfigObj has been found:
# method co.write() without arguments produces list of lines
# one option per line, and multiline values are not split
# across multiple lines,
# and that breaks the parsing these lines back by ConfigObj.
# This issue only affects test, but it's better to avoid
# `co.write()` construct at all.
# [bialix 20110222] bug report sent to ConfigObj's author
outfile = StringIO()
co.write(outfile=outfile)
output = outfile.getvalue()
# now we're trying to read it back
co2 = config.ConfigObj(StringIO(output))
self.assertEquals(triple_quotes_value, co2['test'])
erroneous_config = """[section] # line 1
good=good # line 2
[section] # line 3
whocares=notme # line 4
"""
class TestConfigObjErrors(tests.TestCase):
def test_duplicate_section_name_error_line(self):
try:
co = configobj.ConfigObj(StringIO(erroneous_config),
raise_errors=True)
except config.configobj.DuplicateError, e:
self.assertEqual(3, e.line_number)
else:
self.fail('Error in config file not detected')
class TestConfig(tests.TestCase):
def test_constructs(self):
config.Config()
def test_user_email(self):
my_config = InstrumentedConfig()
self.assertEqual('robert.collins@example.org', my_config.user_email())
self.assertEqual(['_get_user_id'], my_config._calls)
def test_username(self):
my_config = InstrumentedConfig()
self.assertEqual('Robert Collins <robert.collins@example.org>',
my_config.username())
self.assertEqual(['_get_user_id'], my_config._calls)
def test_signatures_default(self):
my_config = config.Config()
self.assertFalse(
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.signature_needed))
self.assertEqual(config.CHECK_IF_POSSIBLE,
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.signature_checking))
self.assertEqual(config.SIGN_WHEN_REQUIRED,
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.signing_policy))
def test_signatures_template_method(self):
my_config = InstrumentedConfig()
self.assertEqual(config.CHECK_NEVER,
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.signature_checking))
self.assertEqual(['_get_signature_checking'], my_config._calls)
def test_signatures_template_method_none(self):
my_config = InstrumentedConfig()
my_config._signatures = None
self.assertEqual(config.CHECK_IF_POSSIBLE,
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.signature_checking))
self.assertEqual(['_get_signature_checking'], my_config._calls)
def test_gpg_signing_command_default(self):
my_config = config.Config()
self.assertEqual('gpg',
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.gpg_signing_command))
def test_get_user_option_default(self):
my_config = config.Config()
self.assertEqual(None, my_config.get_user_option('no_option'))
def test_post_commit_default(self):
my_config = config.Config()
self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.post_commit))
def test_log_format_default(self):
my_config = config.Config()
self.assertEqual('long',
self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.log_format))
def test_acceptable_keys_default(self):
my_config = config.Config()
self.assertEqual(None, self.applyDeprecated(deprecated_in((2, 5, 0)),
my_config.acceptable_keys))
def test_validate_signatures_in_log_default(self):
my_config = config.Config()
self.assertEqual(False, my_config.validate_signatures_in_log())
def test_get_change_editor(self):
my_config = InstrumentedConfig()
change_editor = my_config.get_change_editor('old_tree', 'new_tree')
self.assertEqual(['_get_change_editor'], my_config._calls)
self.assertIs(diff.DiffFromTool, change_editor.__class__)
self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
change_editor.command_template)
class TestConfigPath(tests.TestCase):
def setUp(self):
super(TestConfigPath, self).setUp()
self.overrideEnv('HOME', '/home/bogus')
self.overrideEnv('XDG_CACHE_DIR', '')
if sys.platform == 'win32':
self.overrideEnv(
'BZR_HOME', r'C:\Documents and Settings\bogus\Application Data')
self.bzr_home = \
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
else:
self.bzr_home = '/home/bogus/.bazaar'
def test_config_dir(self):
self.assertEqual(config.config_dir(), self.bzr_home)
def test_config_dir_is_unicode(self):
self.assertIsInstance(config.config_dir(), unicode)
def test_config_filename(self):
self.assertEqual(config.config_filename(),
self.bzr_home + '/bazaar.conf')
def test_locations_config_filename(self):
self.assertEqual(config.locations_config_filename(),
self.bzr_home + '/locations.conf')
def test_authentication_config_filename(self):
self.assertEqual(config.authentication_config_filename(),
self.bzr_home + '/authentication.conf')
def test_xdg_cache_dir(self):
self.assertEqual(config.xdg_cache_dir(),
'/home/bogus/.cache')
class TestXDGConfigDir(tests.TestCaseInTempDir):
# must be in temp dir because config tests for the existence of the bazaar
# subdirectory of $XDG_CONFIG_HOME
def setUp(self):
if sys.platform in ('darwin', 'win32'):
raise tests.TestNotApplicable(
'XDG config dir not used on this platform')
super(TestXDGConfigDir, self).setUp()
self.overrideEnv('HOME', self.test_home_dir)
# BZR_HOME overrides everything we want to test so unset it.
self.overrideEnv('BZR_HOME', None)
def test_xdg_config_dir_exists(self):
"""When ~/.config/bazaar exists, use it as the config dir."""
newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
os.makedirs(newdir)
self.assertEqual(config.config_dir(), newdir)
def test_xdg_config_home(self):
"""When XDG_CONFIG_HOME is set, use it."""
xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
os.makedirs(newdir)
self.assertEqual(config.config_dir(), newdir)
class TestIniConfig(tests.TestCaseInTempDir):
def make_config_parser(self, s):
conf = config.IniBasedConfig.from_string(s)
return conf, conf._get_parser()
class TestIniConfigBuilding(TestIniConfig):
def test_contructs(self):
my_config = config.IniBasedConfig()
def test_from_fp(self):
my_config = config.IniBasedConfig.from_string(sample_config_text)
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
def test_cached(self):
my_config = config.IniBasedConfig.from_string(sample_config_text)
parser = my_config._get_parser()
self.assertTrue(my_config._get_parser() is parser)
def _dummy_chown(self, path, uid, gid):
self.path, self.uid, self.gid = path, uid, gid
def test_ini_config_ownership(self):
"""Ensure that chown is happening during _write_config_file"""
self.requireFeature(features.chown_feature)
self.overrideAttr(os, 'chown', self._dummy_chown)
self.path = self.uid = self.gid = None
conf = config.IniBasedConfig(file_name='./foo.conf')
conf._write_config_file()
self.assertEquals(self.path, './foo.conf')
self.assertTrue(isinstance(self.uid, int))
self.assertTrue(isinstance(self.gid, int))
def test_get_filename_parameter_is_deprecated_(self):
conf = self.callDeprecated([
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
' Use file_name instead.'],
config.IniBasedConfig, lambda: 'ini.conf')
self.assertEqual('ini.conf', conf.file_name)
def test_get_parser_file_parameter_is_deprecated_(self):
config_file = StringIO(sample_config_text.encode('utf-8'))
conf = config.IniBasedConfig.from_string(sample_config_text)
conf = self.callDeprecated([
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
' Use IniBasedConfig(_content=xxx) instead.'],
conf._get_parser, file=config_file)
class TestIniConfigSaving(tests.TestCaseInTempDir):
def test_cant_save_without_a_file_name(self):
conf = config.IniBasedConfig()
self.assertRaises(AssertionError, conf._write_config_file)
def test_saved_with_content(self):
content = 'foo = bar\n'
conf = config.IniBasedConfig.from_string(
content, file_name='./test.conf', save=True)
self.assertFileEqual(content, 'test.conf')
class TestIniConfigOptionExpansion(tests.TestCase):
"""Test option expansion from the IniConfig level.
What we really want here is to test the Config level, but the class being
abstract as far as storing values is concerned, this can't be done
properly (yet).
"""
# FIXME: This should be rewritten when all configs share a storage
# implementation -- vila 2011-02-18
def get_config(self, string=None):
if string is None:
string = ''
c = config.IniBasedConfig.from_string(string)
return c
def assertExpansion(self, expected, conf, string, env=None):
self.assertEquals(expected, conf.expand_options(string, env))
def test_no_expansion(self):
c = self.get_config('')
self.assertExpansion('foo', c, 'foo')
def test_env_adding_options(self):
c = self.get_config('')
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
def test_env_overriding_options(self):
c = self.get_config('foo=baz')
self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
def test_simple_ref(self):
c = self.get_config('foo=xxx')
self.assertExpansion('xxx', c, '{foo}')
def test_unknown_ref(self):
c = self.get_config('')
self.assertRaises(errors.ExpandingUnknownOption,
c.expand_options, '{foo}')
def test_indirect_ref(self):
c = self.get_config('''
foo=xxx
bar={foo}
''')
self.assertExpansion('xxx', c, '{bar}')
def test_embedded_ref(self):
c = self.get_config('''
foo=xxx
bar=foo
''')
self.assertExpansion('xxx', c, '{{bar}}')
def test_simple_loop(self):
c = self.get_config('foo={foo}')
self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
def test_indirect_loop(self):
c = self.get_config('''
foo={bar}
bar={baz}
baz={foo}''')
e = self.assertRaises(errors.OptionExpansionLoop,
c.expand_options, '{foo}')
self.assertEquals('foo->bar->baz', e.refs)
self.assertEquals('{foo}', e.string)
def test_list(self):
conf = self.get_config('''
foo=start
bar=middle
baz=end
list={foo},{bar},{baz}
''')
self.assertEquals(['start', 'middle', 'end'],
conf.get_user_option('list', expand=True))
def test_cascading_list(self):
conf = self.get_config('''
foo=start,{bar}
bar=middle,{baz}
baz=end
list={foo}
''')
self.assertEquals(['start', 'middle', 'end'],
conf.get_user_option('list', expand=True))
def test_pathological_hidden_list(self):
conf = self.get_config('''
foo=bin
bar=go
start={foo
middle=},{
end=bar}
hidden={start}{middle}{end}
''')
# Nope, it's either a string or a list, and the list wins as soon as a
# ',' appears, so the string concatenation never occur.
self.assertEquals(['{foo', '}', '{', 'bar}'],
conf.get_user_option('hidden', expand=True))
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
def get_config(self, location, string=None):
if string is None:
string = ''
# Since we don't save the config we won't strictly require to inherit
# from TestCaseInTempDir, but an error occurs so quickly...
c = config.LocationConfig.from_string(string, location)
return c
def test_dont_cross_unrelated_section(self):
c = self.get_config('/another/branch/path','''
[/one/branch/path]
foo = hello
bar = {foo}/2
[/another/branch/path]
bar = {foo}/2
''')
self.assertRaises(errors.ExpandingUnknownOption,
c.get_user_option, 'bar', expand=True)
def test_cross_related_sections(self):
c = self.get_config('/project/branch/path','''
[/project]
foo = qu
[/project/branch/path]
bar = {foo}ux
''')
self.assertEquals('quux', c.get_user_option('bar', expand=True))
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
def test_cannot_reload_without_name(self):
conf = config.IniBasedConfig.from_string(sample_config_text)
self.assertRaises(AssertionError, conf.reload)
def test_reload_see_new_value(self):
c1 = config.IniBasedConfig.from_string('editor=vim\n',
file_name='./test/conf')
c1._write_config_file()
c2 = config.IniBasedConfig.from_string('editor=emacs\n',
file_name='./test/conf')
c2._write_config_file()
self.assertEqual('vim', c1.get_user_option('editor'))
self.assertEqual('emacs', c2.get_user_option('editor'))
# Make sure we get the Right value
c1.reload()
self.assertEqual('emacs', c1.get_user_option('editor'))
class TestLockableConfig(tests.TestCaseInTempDir):
scenarios = lockable_config_scenarios()
# Set by load_tests
config_class = None
config_args = None
config_section = None
def setUp(self):
super(TestLockableConfig, self).setUp()
self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
self.config = self.create_config(self._content)
def get_existing_config(self):
return self.config_class(*self.config_args)
def create_config(self, content):
kwargs = dict(save=True)
c = self.config_class.from_string(content, *self.config_args, **kwargs)
return c
def test_simple_read_access(self):
self.assertEquals('1', self.config.get_user_option('one'))
def test_simple_write_access(self):
self.config.set_user_option('one', 'one')
self.assertEquals('one', self.config.get_user_option('one'))
def test_listen_to_the_last_speaker(self):
c1 = self.config
c2 = self.get_existing_config()
c1.set_user_option('one', 'ONE')
c2.set_user_option('two', 'TWO')
self.assertEquals('ONE', c1.get_user_option('one'))
self.assertEquals('TWO', c2.get_user_option('two'))
# The second update respect the first one
self.assertEquals('ONE', c2.get_user_option('one'))
def test_last_speaker_wins(self):
# If the same config is not shared, the same variable modified twice
# can only see a single result.
c1 = self.config
c2 = self.get_existing_config()
c1.set_user_option('one', 'c1')
c2.set_user_option('one', 'c2')
self.assertEquals('c2', c2._get_user_option('one'))
# The first modification is still available until another refresh
# occur
self.assertEquals('c1', c1._get_user_option('one'))
c1.set_user_option('two', 'done')
self.assertEquals('c2', c1._get_user_option('one'))
def test_writes_are_serialized(self):
c1 = self.config
c2 = self.get_existing_config()
# We spawn a thread that will pause *during* the write
before_writing = threading.Event()
after_writing = threading.Event()
writing_done = threading.Event()
c1_orig = c1._write_config_file
def c1_write_config_file():
before_writing.set()
c1_orig()
# The lock is held. We wait for the main thread to decide when to
# continue
after_writing.wait()
c1._write_config_file = c1_write_config_file
def c1_set_option():
c1.set_user_option('one', 'c1')
writing_done.set()
t1 = threading.Thread(target=c1_set_option)
# Collect the thread after the test
self.addCleanup(t1.join)
# Be ready to unblock the thread if the test goes wrong
self.addCleanup(after_writing.set)
t1.start()
before_writing.wait()
self.assertTrue(c1._lock.is_held)
self.assertRaises(errors.LockContention,
c2.set_user_option, 'one', 'c2')
self.assertEquals('c1', c1.get_user_option('one'))
# Let the lock be released
after_writing.set()
writing_done.wait()
c2.set_user_option('one', 'c2')
self.assertEquals('c2', c2.get_user_option('one'))
def test_read_while_writing(self):
c1 = self.config
# We spawn a thread that will pause *during* the write
ready_to_write = threading.Event()
do_writing = threading.Event()
writing_done = threading.Event()
c1_orig = c1._write_config_file
def c1_write_config_file():
ready_to_write.set()
# The lock is held. We wait for the main thread to decide when to
# continue
do_writing.wait()
c1_orig()
writing_done.set()
c1._write_config_file = c1_write_config_file
def c1_set_option():
c1.set_user_option('one', 'c1')
t1 = threading.Thread(target=c1_set_option)
# Collect the thread after the test
self.addCleanup(t1.join)
# Be ready to unblock the thread if the test goes wrong
self.addCleanup(do_writing.set)
t1.start()
# Ensure the thread is ready to write
ready_to_write.wait()
self.assertTrue(c1._lock.is_held)
self.assertEquals('c1', c1.get_user_option('one'))
# If we read during the write, we get the old value
c2 = self.get_existing_config()
self.assertEquals('1', c2.get_user_option('one'))
# Let the writing occur and ensure it occurred
do_writing.set()
writing_done.wait()
# Now we get the updated value
c3 = self.get_existing_config()
self.assertEquals('c1', c3.get_user_option('one'))
class TestGetUserOptionAs(TestIniConfig):
def test_get_user_option_as_bool(self):
conf, parser = self.make_config_parser("""
a_true_bool = true
a_false_bool = 0
an_invalid_bool = maybe
a_list = hmm, who knows ? # This is interpreted as a list !
""")
get_bool = conf.get_user_option_as_bool
self.assertEqual(True, get_bool('a_true_bool'))
self.assertEqual(False, get_bool('a_false_bool'))
warnings = []
def warning(*args):
warnings.append(args[0] % args[1:])
self.overrideAttr(trace, 'warning', warning)
msg = 'Value "%s" is not a boolean for "%s"'
self.assertIs(None, get_bool('an_invalid_bool'))
self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
warnings = []
self.assertIs(None, get_bool('not_defined_in_this_config'))
self.assertEquals([], warnings)
def test_get_user_option_as_list(self):
conf, parser = self.make_config_parser("""
a_list = a,b,c
length_1 = 1,
one_item = x
""")
get_list = conf.get_user_option_as_list
self.assertEqual(['a', 'b', 'c'], get_list('a_list'))