]> mj.ucw.cz Git - moe.git/blob - t/moe/config_test.py
Add context manager to ConfigTree.parse
[moe.git] / t / moe / config_test.py
1 # -*- coding: utf-8 -*-
2
3 import moe.config as cf
4 from moe.config_parser import *
5 import logging as log
6 import unittest
7 import tempfile
8
9 class TestConfig(unittest.TestCase):
10
11   def setUp(s):
12     s.t = cf.ConfigTree()    
13
14   def parse(s, string, level=0, fname='test'):
15     return s.t.parse(string, source=fname, level=level)
16
17   def var(s, varname, create=True):
18     return s.t.lookup(varname, create=create)
19
20   def val(s, varname):
21     return s.var(varname, create=False).value()
22
23   def eqparse(s, string, *args, **kwargs):
24     "Parse expression `s`, return parts that should be equal to anoter run of `eqparse(s)`."
25     return [(i[0], i[1].operation) for i in s.parse(string, *args, **kwargs)]
26
27
28 class TestParser(TestConfig):
29   s1 = r"""a="1";z{b='2';w{S.Tr_an-g.e='"'}};c.d='\n';e="{a}{b}";e+='{c.d}';a+="\"\n\{\}";f+='Z{a.b}';e+=c.d;e+=c;e+=a"""
30   s2 = '\t\n \n ' + s1.replace('=', '= \n ').replace(';', '\t \n\t \n ').replace('+=',' \n += ') + '\n\n '
31
32   def test_noWS(s):
33     assert len(s.parse(s.s1)) == 11
34
35   def test_noWS_COMMENT(s):
36     assert s.eqparse(s.s1+'#COMMENT') == s.eqparse(s.s1+'#') == s.eqparse(s.s1+'#\n') == s.eqparse(s.s1+'\n#')
37
38   def test_manyWS(s):
39     assert s.eqparse(s.s2) == s.eqparse(s.s1)
40
41   def test_manyWS_COMMENT(s):
42     assert s.eqparse(s.s2.replace('\n',' #COMMENT \n')) == s.eqparse(s.s2.replace('\n','#\n')) == s.eqparse(s.s1)
43
44   def test_empty(s):
45     assert s.eqparse('') == s.eqparse('\n') == s.eqparse('') == s.eqparse('a{}') == \
46       s.eqparse('a.b.c{if ""==\'\' {d.e{\n\n#Nothing\n}} }') == []
47
48   def test_syntax_errors(s):
49     s.assertRaises(ConfigSyntaxError, s.parse, "a=#")
50     s.assertRaises(ConfigSyntaxError, s.parse, "a='\"")
51     s.assertRaises(ConfigSyntaxError, s.parse, 'a="{a@b}"')
52     s.assertRaises(ConfigSyntaxError, s.parse, 'a="A{A"')
53     s.assertRaises(ConfigSyntaxError, s.parse, 'a=b"42"')
54     s.assertRaises(ConfigSyntaxError, s.parse, 'a=b.c.d.')
55
56   def test_error_location(s):
57     try: s.parse('\t \n  \n  { \n \n ')
58     except ConfigSyntaxError, e:
59       assert e.line == 3 and e.column in range(2,4)
60
61   def test_quoting(s):
62     s.parse(' a="\\"\\{a$b\\}\'\n\n\'{z}" ')
63     assert s.var('z', create=False)
64     # No escaping in '-string 
65     s.assertRaises(ConfigSyntaxError, s.parse, " a='\"\\'\n\n' ")
66     # Variable should not be created
67     s.parse(" a='{z2}' ")
68     s.assertRaises(cf.ConfigError, s.var, 'z2', create=False)
69
70   def test_conditions(s):
71     s.assertRaises(ConfigSyntaxError, s.parse, "if '{a}'=='{b}' and ''!='' {}")
72     s.parse('if ((#C\n (\n (not not not""!="")\n#C\n)\t ) ) {}')
73     s.parse('if (""=="" and not (not not ""!="" or ""=="")){}')
74     s.parse('if ((a=="{b}" and a.b.c!=c.b.a)or x!=y){}')
75     s.parse('if(""==""){a{if(""==""){if(""==""){b{if(""==""){if(""==""){}}}}}}}')
76     s.assertRaises(ConfigSyntaxError, s.parse, "if notnot'{a}'=='{b}' {}")
77     s.assertRaises(ConfigSyntaxError, s.parse, "if ('{a}'=='{b}' not and ''!='') {}")
78     s.assertRaises(ConfigSyntaxError, s.parse, "if ('{a}'=='{b}' ornot ''!='') {}")
79     s.assertRaises(ConfigSyntaxError, s.parse, "if 'a'<>'b' {}")
80
81   def test_parse_remove(s):
82     def raise_UserWarning():
83       with s.parse("b='F'", level=99):
84         assert s.val('b') == 'F'
85         raise UserWarning 
86     d0 = s.parse('a="000"')
87     d1 = s.parse("a='A'; b='B'; c='C'", level=10)
88     d2 = s.parse('c="{a}{a}"; b="XX" ', level=20)
89     d3 = s.parse('b+=c ', level=30)
90     assert s.val('b') == "XXAA"
91     s.t.remove(d2)
92     assert s.val('b') == "BC"
93     s.assertRaises(ValueError, s.t.remove, [('d', d1[0][1])])
94     s.assertRaises(ValueError, s.t.remove, [('b', d1[0][1])])
95     # Try exception in "with parse():" 
96     s.assertRaises(UserWarning, raise_UserWarning)
97     assert s.val('b') == "BC"
98     # partially remove d1
99     s.t.remove([('c', d1[2][1])])
100     # try to remove rest - 'a' and 'b' should get removed
101     s.assertRaises(ValueError, s.t.remove, d1)
102     assert s.val('a') == "000"
103     # cleanup
104     s.t.remove(d3)
105     s.t.remove(d0)
106     for v in 'abcd':
107       assert len(s.var(v).operations) == 0
108
109
110 class TestConfigEval(TestConfig):
111
112   def test_ops(s):
113     s.parse('c+="-C_APP"', level=20)
114     s.parse('a="A"; b="{a}-B"; c="C1-{b}-C2"; a+="FOO"; a="AA"')
115     assert s.val('c') == 'C1-AA-B-C2-C_APP'
116     s.parse('b+="-A:\{{a}\}";a+="A"', level=10)
117     assert s.val('c') == 'C1-AAA-B-A:{AAA}-C2-C_APP'
118
119   def test_nested(s):
120     s.parse('a="0"; b{a="1"; b{a="2"; b{a="3"; b{a="4"; b{a="5"}}}}}')
121     assert s.val('b.b.b.a') == '3'
122     s.parse('b.b{b.b{b.a="5MOD"}}')
123     assert s.val('b.b.b.b.b.a') == '5MOD'
124
125   def test_escape_chars(s):
126     s.parse(r"""a='{a}\\\\#\n'; b="{a}'\"\{\}"; c='\'; c+="\{{b}\}";""")
127     assert s.val('c') == r"""\{{a}\\\\#\n'"{}}"""
128
129   def test_expressions(s):
130     s.parse('A="4"; B.B=\'2\'; B.A=A; B.C="{B.A}{B.B}"; if B.C=="42" {D=C}; if C==D{E=D}; C="OK"')
131     assert s.val('E') == 'OK'
132   
133   ts = 'a="A:"; if "{c1}"=="1" {a+="C1"; b="B"; if ("{c2a}"=="1" or not "{c2b}"=="1") { a+="C2"; '\
134     'if ("{c3a}"=="1" and "{c3b}"=="1") { a+="C3" }}}'
135
136   def test_cond_chain(s):
137     s.parse(s.ts)
138     s.parse('c1="1"; c2="0"')
139     # b should have determined value, a should not (since c3a is undefined)
140     s.assertRaises(cf.UndefinedError, s.val, 'a')
141     assert s.val('b') == 'B'
142     s.parse('c1="0"')
143     # now b should be undefined
144     s.assertRaises(cf.UndefinedError, s.val, 'b')
145     # Normal evaluation
146     s.parse('c1="1"; c2a="1"; c2b="0"; c3a="0"')
147     assert s.val('a') == 'A:C1C2'
148     s.parse('c3a="1"; c3b="1"; c2b="1"')
149     assert s.val('a') == 'A:C1C2C3'
150     # tests condition invalidating 
151     s.parse('c2a+="0"')
152     assert s.val('a') == 'A:C1'
153
154   def test_cond_eager(s):
155     s.parse(s.ts)
156     # undefined c2b and c3a should not be evaluated 
157     s.parse('c1="1"; c2a="1"; c3a="0"')
158     assert s.val('a') == 'A:C1C2'
159     # but now c3b should be evaluated 
160     s.parse('c1="1"; c2a="1"; c3a="1"')
161     s.assertRaises(cf.UndefinedError, s.val, 'a')
162     s.parse('c1="1"; c2a="1"; c3b="1"')
163     assert s.val('a') == 'A:C1C2C3'
164
165   def test_undef(s):
166     s.assertRaises(cf.UndefinedError, s.val, 'a')
167     s.parse('a="{b}"')
168     s.assertRaises(cf.UndefinedError, s.val, 'a')
169     s.parse('b+="1"')
170     s.assertRaises(cf.UndefinedError, s.val, 'b')
171
172   def test_loopy_def(s):
173     s.parse('a="A"; a+="{a}"')
174     s.assertRaises(cf.CyclicConfigError, s.val, 'a')
175     s.parse('b="{c}"; c="{b}"')
176     s.assertRaises(cf.CyclicConfigError, s.val, 'b')
177
178   def test_varname(s):
179     s.assertRaises(cf.VariableNameError, s.val, 'b/c')
180     s.assertRaises(cf.VariableNameError, s.val, '.b.c')
181     s.assertRaises(cf.VariableNameError, s.val, 'b.c.')
182     s.assertRaises(cf.VariableNameError, s.val, 'b..c')
183
184   def test_remove(s):
185     l = s.parse('a="A1"; b="B1"; if "{cond}"=="1" {a+="A2"; b+="B2"}; a+="A3"; b+="B3"; cond="1"')
186     assert s.val('a') == 'A1A2A3'
187     assert s.val('b') == 'B1B2B3'
188     # remove b+="B2"
189     s.var('b').remove_operation(l[3][1])
190     assert s.val('a') == 'A1A2A3'
191     assert s.val('b') == 'B1B3'
192     # are the dependencies still handled properly? 
193     s.parse('cond+="-invalidated"')
194     assert s.val('a') == 'A1A3'
195     s.parse('cond="1"')
196     assert s.val('a') == 'A1A2A3'
197
198   def test_fix(s):
199     s.parse(""" A='4'; B="{A}"; C="2"; B+="{C}"; D="{B}"; E="{D}" """)
200     s.var('D').fix()
201     # Break by C 
202     l = s.parse('C="3"')
203     s.assertRaises(cf.VariableFixedError, s.val, "E")
204     s.assertRaises(cf.VariableFixedError, s.val, "D")
205     s.var('C').remove_operation(l[0][1])
206     # Break directly by D 
207     l = s.parse('D="41"')
208     s.assertRaises(cf.VariableFixedError, s.val, "D")
209     s.assertRaises(cf.VariableFixedError, s.val, "E")
210     # Unfix
211     s.var('D').unfix()
212     assert s.val('E') == '41'
213     s.var('D').remove_operation(l[0][1])
214     assert s.val('D') == '42'
215     # Fixing via ConfigTree.fix
216     s.t.fix('D')
217     s.t.fix(['E','A'])
218     s.parse('D=""; E=""; A=""; ')
219     s.assertRaises(cf.VariableFixedError, s.val, "D")
220     s.assertRaises(cf.VariableFixedError, s.val, "E")
221     s.assertRaises(cf.VariableFixedError, s.val, "A")
222
223   def test_unicode(s):
224     # Ascii (1b) and unicode (2b)
225     s.parse(u'A="Ú"; C="ě"')
226     # String
227     s.parse('B=\'chyln\'')
228     # By escapes  
229     s.parse(u'D=\'\u0159e\u017eav\xe1\'')
230     s.parse(u'E="ŽluŤ"')
231     # Via utf8 file
232     f = tempfile.TemporaryFile(mode='w+t')
233     f.write(u'S1="\xdachyln\u011b \u0159e\u017eav\xe1 \u017dlu\u0164" ; S2="{A}{B}{C} {D} {E}"'.encode('utf8'))
234     f.seek(0)
235     s.parse(f)
236     # Test
237     s.parse(u'if "{S1}"=="{S2}" { ANS="jó!" } ')
238     assert s.val('ANS') == u"jó!"
239     assert s.val('S1') == s.val('S2') == u'\xdachyln\u011b \u0159e\u017eav\xe1 \u017dlu\u0164'
240
241   def test_priority(s):
242     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["4"]), level=4))
243     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["3a"]), level=3))
244     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["1"]), level=1))
245     s.var('a').add_operation(cf.Operation('SET', None, cf.ConfigExpression(["2"]), level=2))
246     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["3b"]), level=3))
247     s.var('a').add_operation(cf.Operation('SET', None, cf.ConfigExpression(["0"]), level=0))
248     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["5"]), level=5))
249     assert s.val('a')=='23a3b45'
250
251   def test_priority_in_level(s):
252     s.parse('a="A"; c=""; b="B"; c+="C"; d="D"', level=0)
253     s.parse('a=b; b=c; c=d; d="ZZZ"', level=10)
254     s.parse('c="XXX"; c=""; d="S"; c+="YYY"', level=20)
255     assert s.val('a') == "YYY"
256
257 # TODO: Fail on 1st April
258 # TODO (OPT): Somehow add log.debug('Maximum encountered depth: %d', cf.debug_maxdepth)
259
260 # Coverage via command "nosetests conftest --with-coverage --cover-html-dir=cover --cover-html"
261