]> mj.ucw.cz Git - moe.git/blob - t/moe/config_test.py
Tests for status, status.py fixes, minor changes
[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   def test_escape(s):
110     for tst in ['{B}"#\n\\"', '', '\\\n\\\\"\\{\\}', '"#"', s.s1, s.s2]:
111       s.parse('A="%s"; A+="0"'%config_escape(tst))
112       assert s.val('A') == tst+'0'
113
114 class TestConfigEval(TestConfig):
115
116   def test_ops(s):
117     s.parse('c+="-C_APP"', level=20)
118     s.parse('a="A"; b="{a}-B"; c="C1-{b}-C2"; a+="FOO"; a="AA"')
119     assert s.val('c') == 'C1-AA-B-C2-C_APP'
120     s.parse('b+="-A:\{{a}\}";a+="A"', level=10)
121     assert s.val('c') == 'C1-AAA-B-A:{AAA}-C2-C_APP'
122
123   def test_nested(s):
124     s.parse('a="0"; b{a="1"; b{a="2"; b{a="3"; b{a="4"; b{a="5"}}}}}')
125     assert s.val('b.b.b.a') == '3'
126     s.parse('b.b{b.b{b.a="5MOD"}}')
127     assert s.val('b.b.b.b.b.a') == '5MOD'
128
129   def test_escape_chars(s):
130     s.parse(r"""a='{a}\\\\#\n'; b="{a}'\"\{\}"; c='\'; c+="\{{b}\}";""")
131     assert s.val('c') == r"""\{{a}\\\\#\n'"{}}"""
132
133   def test_expressions(s):
134     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"')
135     assert s.val('E') == 'OK'
136   
137   ts = 'a="A:"; if "{c1}"=="1" {a+="C1"; b="B"; if ("{c2a}"=="1" or not "{c2b}"=="1") { a+="C2"; '\
138     'if ("{c3a}"=="1" and "{c3b}"=="1") { a+="C3" }}}'
139
140   def test_cond_chain(s):
141     s.parse(s.ts)
142     s.parse('c1="1"; c2="0"')
143     # b should have determined value, a should not (since c3a is undefined)
144     s.assertRaises(cf.UndefinedError, s.val, 'a')
145     assert s.val('b') == 'B'
146     s.parse('c1="0"')
147     # now b should be undefined
148     s.assertRaises(cf.UndefinedError, s.val, 'b')
149     # Normal evaluation
150     s.parse('c1="1"; c2a="1"; c2b="0"; c3a="0"')
151     assert s.val('a') == 'A:C1C2'
152     s.parse('c3a="1"; c3b="1"; c2b="1"')
153     assert s.val('a') == 'A:C1C2C3'
154     # tests condition invalidating 
155     s.parse('c2a+="0"')
156     assert s.val('a') == 'A:C1'
157
158   def test_cond_eager(s):
159     s.parse(s.ts)
160     # undefined c2b and c3a should not be evaluated 
161     s.parse('c1="1"; c2a="1"; c3a="0"')
162     assert s.val('a') == 'A:C1C2'
163     # but now c3b should be evaluated 
164     s.parse('c1="1"; c2a="1"; c3a="1"')
165     s.assertRaises(cf.UndefinedError, s.val, 'a')
166     s.parse('c1="1"; c2a="1"; c3b="1"')
167     assert s.val('a') == 'A:C1C2C3'
168
169   def test_undef(s):
170     s.assertRaises(cf.UndefinedError, s.val, 'a')
171     s.parse('a="{b}"')
172     s.assertRaises(cf.UndefinedError, s.val, 'a')
173     s.parse('b+="1"')
174     s.assertRaises(cf.UndefinedError, s.val, 'b')
175
176   def test_loopy_def(s):
177     s.parse('a="A"; a+="{a}"')
178     s.assertRaises(cf.CyclicConfigError, s.val, 'a')
179     s.parse('b="{c}"; c="{b}"')
180     s.assertRaises(cf.CyclicConfigError, s.val, 'b')
181
182   def test_varname(s):
183     s.assertRaises(cf.VariableNameError, s.val, 'b/c')
184     s.assertRaises(cf.VariableNameError, s.val, '.b.c')
185     s.assertRaises(cf.VariableNameError, s.val, 'b.c.')
186     s.assertRaises(cf.VariableNameError, s.val, 'b..c')
187
188   def test_remove(s):
189     l = s.parse('a="A1"; b="B1"; if "{cond}"=="1" {a+="A2"; b+="B2"}; a+="A3"; b+="B3"; cond="1"')
190     assert s.val('a') == 'A1A2A3'
191     assert s.val('b') == 'B1B2B3'
192     # remove b+="B2"
193     s.var('b').remove_operation(l[3][1])
194     assert s.val('a') == 'A1A2A3'
195     assert s.val('b') == 'B1B3'
196     # are the dependencies still handled properly? 
197     s.parse('cond+="-invalidated"')
198     assert s.val('a') == 'A1A3'
199     s.parse('cond="1"')
200     assert s.val('a') == 'A1A2A3'
201
202   def test_fix(s):
203     s.parse(""" A='4'; B="{A}"; C="2"; B+="{C}"; D="{B}"; E="{D}" """)
204     s.var('D').fix()
205     # Break by C 
206     l = s.parse('C="3"')
207     s.assertRaises(cf.VariableFixedError, s.val, "E")
208     s.assertRaises(cf.VariableFixedError, s.val, "D")
209     s.var('C').remove_operation(l[0][1])
210     # Break directly by D 
211     l = s.parse('D="41"')
212     s.assertRaises(cf.VariableFixedError, s.val, "D")
213     s.assertRaises(cf.VariableFixedError, s.val, "E")
214     # Unfix
215     s.var('D').unfix()
216     assert s.val('E') == '41'
217     s.var('D').remove_operation(l[0][1])
218     assert s.val('D') == '42'
219     # Fixing via ConfigTree.fix
220     s.t.fix('D')
221     s.t.fix(['E','A'])
222     s.parse('D=""; E=""; A=""; ')
223     s.assertRaises(cf.VariableFixedError, s.val, "D")
224     s.assertRaises(cf.VariableFixedError, s.val, "E")
225     s.assertRaises(cf.VariableFixedError, s.val, "A")
226
227   def test_unicode(s):
228     # Ascii (1b) and unicode (2b)
229     s.parse(u'A="Ú"; C="ě"')
230     # String
231     s.parse('B=\'chyln\'')
232     # By escapes  
233     s.parse(u'D=\'\u0159e\u017eav\xe1\'')
234     s.parse(u'E="ŽluŤ"')
235     # Via utf8 file
236     f = tempfile.TemporaryFile(mode='w+t')
237     f.write(u'S1="\xdachyln\u011b \u0159e\u017eav\xe1 \u017dlu\u0164" ; S2="{A}{B}{C} {D} {E}"'.encode('utf8'))
238     f.seek(0)
239     s.parse(f)
240     # Test
241     s.parse(u'if "{S1}"=="{S2}" { ANS="jó!" } ')
242     assert s.val('ANS') == u"jó!"
243     assert s.val('S1') == s.val('S2') == u'\xdachyln\u011b \u0159e\u017eav\xe1 \u017dlu\u0164'
244
245   def test_priority(s):
246     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["4"]), level=4))
247     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["3a"]), level=3))
248     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["1"]), level=1))
249     s.var('a').add_operation(cf.Operation('SET', None, cf.ConfigExpression(["2"]), level=2))
250     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["3b"]), level=3))
251     s.var('a').add_operation(cf.Operation('SET', None, cf.ConfigExpression(["0"]), level=0))
252     s.var('a').add_operation(cf.Operation('APPEND', None, cf.ConfigExpression(["5"]), level=5))
253     assert s.val('a')=='23a3b45'
254
255   def test_priority_in_level(s):
256     s.parse('a="A"; c=""; b="B"; c+="C"; d="D"', level=0)
257     s.parse('a=b; b=c; c=d; d="ZZZ"', level=10)
258     s.parse('c="XXX"; c=""; d="S"; c+="YYY"', level=20)
259     assert s.val('a') == "YYY"
260
261 # TODO: Fail on 1st April
262 # TODO (OPT): Somehow add log.debug('Maximum encountered depth: %d', cf.debug_maxdepth)
263
264 # Coverage via command "nosetests conftest --with-coverage --cover-html-dir=cover --cover-html"
265