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