Debian Codegraph @

tests/pqltest.py

raw
1 """
2 Tests for "PQL" and new-style DALI expressions.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import datetime
12
13 from gavo.helpers import testhelpers
14
15 from gavo import base
16 from gavo import svcs
17 from gavo.svcs import dalipars
18 from gavo.svcs import pql
19 from gavo.utils import pgsphere, DEG
20
21
22
23 P = pql.PQLPar
24 PR = pql.PQLRange
25 MS = base.makeStruct
26
27
28 class PQLParsesTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
29 def _runTest(self, sample):
30 literal, expected = sample
31 self.assertEqual(pql.PQLPar.fromLiteral(literal, "pqlExpr"), expected)
32
33 samples = [
34 ("foo;something", P([PR("foo")], "something")),
35 ("foo;something%3bother", P([PR("foo")], "something;other")),
36 ("foo/bar", P([PR(start="foo", stop="bar")])),
37 ("", P([PR(value="")])),
38 (",a", P([PR(value=""), PR(value="a")])),
39 ("a,", P([PR(value="a"), PR(value="")])),
40 ("foo/", P([PR(start="foo")])),
41 ("/foo", P([PR(stop="foo")])),
42 ("bar/,/foo", P([PR(start="bar"), PR(stop="foo")])),
43 ("u,bar/,/foo", P([PR(value="u"), PR(start="bar"), PR(stop="foo")])),
44 ("a,b,c", P([PR(value="a"), PR(value="b"), PR(value="c")])),
45 ("%2f,%2c,%3b", P([PR(value="/"), PR(value=","), PR(value=";")])),
46 ]
47
48
49 class PQLLiteralParseErrorsTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
50 def _runTest(self, sample):
51 literal, msg = sample
52 self.assertRaisesWithMsg(base.LiteralParseError,
53 msg,
54 pql.PQLPar.fromLiteral,
55 (literal, "pqlExpr"))
56
57 samples = [
58 ("foo;something;bother",
59 "'foo;something;bother' is not a valid value for pqlExpr"),
60 ("/bar/quux", "'/bar/quux' is not a valid value for range within pqlExpr"),
61 ("foo/bar/quux",
62 "'foo/bar/quux' is not a valid value for range within pqlExpr"),
63 ("foo//quux", "'foo//quux' is not a valid value for range within pqlExpr"),
64 ("//quux", "'//quux' is not a valid value for range within pqlExpr"),
65 ("//quux/", "'//quux/' is not a valid value for pqlExpr"),
66 ("/", "'/' is not a valid value for range within pqlExpr"),
67 ]
68
69
70 class PQLParsedLiteralTest(testhelpers.VerboseTest):
71 def testWithIntRanges(self):
72 res = pql.PQLIntPar.fromLiteral("10,11/12,50/100/5;schnarch", "pqlExpr")
73 self.assertEqual(res, P([PR(value=10), PR(start=11, stop=12),
74 PR(None, 50, 100, 5)], "schnarch"))
75
76 def testBadInt(self):
77 self.assertRaisesWithMsg(
78 base.LiteralParseError,
79 "At 3: '11/1u' is not a valid value for range within pqlExpr",
80 pql.PQLIntPar.fromLiteral,
81 ("10,11/1u,50/100/5;schnarch", "pqlExpr"))
82
83 def testDateRange(self):
84 res = pql.PQLDatePar.fromLiteral(
85 "2010-11-01T10:00:00/2010-11-24T15:00:00/0.5",
86 "pqlExpr")
87 self.assertEqual(res, P([PR(
88 start=datetime.datetime(2010, 11, 0o1, 10, 00, 00),
89 stop=datetime.datetime(2010, 11, 24, 15, 00, 00),
90 step=datetime.timedelta(days=0.5))]))
91
92
93 class PQLSetValuedTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
94 def _runTest(self, sample):
95 literal, expected = sample
96 res = pql.PQLIntPar.fromLiteral(literal, "pqlExpr")
97 if expected is None:
98 self.assertRaises(ValueError, res.getValuesAsSet)
99 else:
100 self.assertEqual(res.getValuesAsSet(), expected)
101
102 samples = [
103 ("1", set([1])),
104 ("1/3", None),
105 ("/4", None),
106 ("3/", None),
107 ("1/2/1", set([1,2])),
108 ("1/2/1;norks", set([1,2])),
109 ("1/2;norks", None),]
110
111
112 class PQLClausesTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
113 def _runTest(self, sample):
114 literal, expected, expectedPars = sample
115 res = pql.PQLIntPar.fromLiteral(literal, "pqlExpr")
116 pars = {}
117 expr = res.getSQL("foo", pars)
118 self.assertEqual(expr, expected)
119 self.assertEqual(pars, expectedPars)
120
121 samples = [
122 ("1", "foo = %(foo0)s", {"foo0": 1}),
123 ("1/3/1", "foo IN %(foo0)s", {"foo0": set([1,2,3])}),
124 ("1/9/3", "foo IN %(foo0)s", {"foo0": set([1,4,7])}),
125 ("0,1/9/3,1/3/1", "foo IN %(foo0)s", {"foo0": set([0,1,2,3,4,7])}),
126 ("/0,1/9/3,1/3/1",
127 "(foo <= %(foo0)s OR foo IN %(foo1)s OR foo IN %(foo2)s)",
128 {"foo0": 0, "foo1": set([1,4,7]), "foo2": set([1,2,3])}),
129 ("1/", "foo >= %(foo0)s", {"foo0": 1}),
130 ("/1", "foo <= %(foo0)s", {"foo0": 1}),
131 ]
132
133
134 class PQLPositionsTest(testhelpers.VerboseTest):
135 def testNoStep(self):
136 self.assertRaisesWithMsg(base.ValidationError,
137 "Field POS: Ranges are not allowed as cone centers",
138 pql.PQLPositionPar.fromLiteral("12,12/14", "POS").getConeSQL,
139 ("POS", {}, 0.1))
140
141 def testRequiresTwo(self):
142 self.assertRaisesWithMsg(base.ValidationError,
143 "Field POS: PQL position values must be lists of length divisible by 2.",
144 pql.PQLPositionPar.fromLiteral("12", "POS").getConeSQL,
145 ("POS", {}, 0.1))
146
147 def testWhackoFrameRejected(self):
148 self.assertRaisesWithMsg(base.ValidationError,
149 "Field POS: Cannot match against coordinates given in WHACKO frame",
150 pql.PQLPositionPar.fromLiteral("12,13;WHACKO", "POS").getConeSQL,
151 ("POS", {}, 0.1))
152
153 def testSingleCone(self):
154 cs = pql.PQLPositionPar.fromLiteral("8,12", "POS")
155 pars = {}
156 expr = cs.getConeSQL("loc", pars, 0.5)
157 self.assertEqual(expr, '(loc <@ scircle(%(pos0)s, %(size0)s))')
158 self.assertEqual(pars, {'size0': 0.5*DEG,
159 'pos0': pgsphere.SPoint.fromDegrees(8.0, 12.0)})
160
161 def testMultiCone(self):
162 cs = pql.PQLPositionPar.fromLiteral("10,12,-10,13", "POS")
163 pars = {}
164 expr = cs.getConeSQL("loc", pars, 0.5)
165 self.assertEqual(expr, '(loc <@ scircle(%(pos0)s, %(size0)s)'
166 ' OR loc <@ scircle(%(pos1)s, %(size0)s))')
167 self.assertEqual(pars, {'size0': 0.5*DEG,
168 'pos0': pgsphere.SPoint.fromDegrees(10.0, 12.0),
169 'pos1': pgsphere.SPoint.fromDegrees(-10.0, 13.0)})
170
171 def testExtraEncoding(self):
172 cs = pql.PQLPositionPar.fromLiteral("180.0%2C60.0", "POS")
173 pars = {}
174 _ = cs.getConeSQL("loc", pars, 0.5)
175 self.assertEqual(pars, {'size0': 0.5*DEG,
176 'pos0': pgsphere.SPoint.fromDegrees(180.0, 60.0)})
177
178 def testQ3CCond(self):
179 cs = pql.PQLPositionPar.fromLiteral("10,12,-10,13", "POS")
180 pars = {}
181 expr = cs.getQ3CSQL("ra", "dec", pars, 0.5)
182 self.assertEqual(expr,
183 "(q3c_radial_query(ra, dec, %(ra0)s, %(dec0)s, %(size0)s)"
184 " OR q3c_radial_query(ra, dec, %(ra1)s, %(dec1)s, %(size0)s))")
185 self.assertEqual(pars["ra0"], 10.0)
186 self.assertEqual(pars["dec1"], 13.0)
187 self.assertEqual(pars["size0"], 0.5)
188
189
190 class PQLFloatTest(testhelpers.VerboseTest):
191 def testNoStep(self):
192 self.assertRaisesWithMsg(base.LiteralParseError,
193 "'1/5/0.5' is not a valid value for range within VAL",
194 pql.PQLFloatPar.fromLiteral,
195 ("1/5/0.5", "VAL"))
196
197 def testSimple(self):
198 cs = pql.PQLFloatPar.fromLiteral("0.5,4/6", "quack")
199 pars = {}
200 expr = cs.getSQL("val", pars)
201 self.assertEqual(expr,
202 "(val = %(val0)s OR val BETWEEN %(val1)s AND %(val2)s )")
203 self.assertEqual(pars, {'val2': 6.0, 'val1': 4.0, 'val0': 0.5})
204
205 def testIntervalSQL(self):
206 cs = pql.PQLFloatPar.fromLiteral("/-0.5,0,2/4,7/", "quack")
207 pars = {}
208 expr = cs.getSQLForInterval("lower", "upper", pars)
209 self.assertEqual(expr, '((%(val0)s>lower)'
210 ' OR %(val1)s BETWEEN lower AND upper'
211 ' OR (%(val2)s>lower AND %(val3)s<upper)'
212 ' OR (%(val4)s<upper))')
213 self.assertEqual(pars, {"val0": -0.5,
214 "val1": 0.,
215 "val2": 4.0,
216 "val3": 2.0,
217 "val4": 7.})
218
219
220 class PQLCaselessTest(testhelpers.VerboseTest):
221 def testSQLGeneration(self):
222 cs = pql.PQLCaselessPar.fromLiteral("AB/CD,FoOBar,{/", "quack")
223 pars = {}
224 expr = cs.getSQL("val", pars)
225 self.assertEqual(expr, "(LOWER(val) BETWEEN %(val0)s AND %(val1)s"
226 " OR LOWER(val) = %(val2)s OR LOWER(val) >= %(val3)s)")
227 self.assertEqual(pars, { 'val0': 'ab', 'val1': 'cd',
228 'val2': 'foobar', 'val3': '{',})
229
230 def testSQLGenerationDiscrete(self):
231 cs = pql.PQLCaselessPar.fromLiteral("AB,CD,al Horno,22%", "quack")
232 pars = {}
233 expr = cs.getSQL("val", pars)
234 self.assertEqual(expr, "LOWER(val) IN %(val0)s")
235 self.assertEqual(pars, {'val0': set(['al horno', '22%', 'ab', 'cd'])})
236
237
238 class PQLIRTest(testhelpers.VerboseTest):
239 def testBasic(self):
240 cs = pql.PQLTextParIR.fromLiteral("abc ef", "foo")
241 sqlPars = {}
242 sql = cs.getSQL("foo", sqlPars)
243 self.assertEqual(sql,
244 "(to_tsvector('english', foo) @@ plainto_tsquery('english', %(foo0)s))")
245 self.assertEqual(sqlPars, {'foo0': 'abc ef'})
246
247 def testEnumeration(self):
248 cs = pql.PQLTextParIR.fromLiteral("abc ef, urgl", "foo")
249 sqlPars = {}
250 sql = cs.getSQL("foo", sqlPars)
251 self.assertEqual(sql,
252 "(to_tsvector('english', foo) @@ plainto_tsquery('english', %(foo0)s)"
253 " OR to_tsvector('english', foo) @@ plainto_tsquery('english', %(foo1)s))")
254 self.assertEqual(sqlPars, {"foo0": " urgl", 'foo1': 'abc ef'})
255
256 def testNoRangeSyntax(self):
257 cs = pql.PQLStringPar.fromLiteral("abc ef/urgl", "foo")
258 sqlPars = {}
259 sql = cs.getSQL("foo", sqlPars)
260 self.assertEqual(sql, 'foo = %(foo0)s')
261 self.assertEqual(sqlPars, {"foo0": "abc ef/urgl"})
262
263
264 class CoversTest(testhelpers.VerboseTest):
265 def testSimpleStringTrue(self):
266 cs = pql.PQLPar.fromLiteral("ABC", "quack")
267 self.assertEqual(cs.covers("ABC"), True)
268
269 def testSimpleStringFalse(self):
270 cs = pql.PQLPar.fromLiteral("ABC", "quack")
271 self.assertEqual(cs.covers("AB"), False)
272
273 def testStringEnumeration(self):
274 cs = pql.PQLPar.fromLiteral("AB,CDE,FG", "quack")
275 self.assertEqual(cs.covers("CDE"), True)
276
277 def testStringIntervalTrue(self):
278 cs = pql.PQLPar.fromLiteral("!/@", "quack")
279 self.assertEqual(cs.covers("@"), True)
280
281 def testMultiStringIntervalFalse(self):
282 cs = pql.PQLPar.fromLiteral("!/@,B/}", "quack")
283 self.assertEqual(cs.covers("A"), False)
284
285 def testMultiStringIntervalTrue(self):
286 cs = pql.PQLPar.fromLiteral("!/@,B/}", "quack")
287 self.assertEqual(cs.covers("Z"), True)
288
289 def testCaselessStringLower(self):
290 cs = pql.PQLCaselessPar.fromLiteral("abu/simbel", "quack")
291 self.assertEqual(cs.covers("BEMBEL"), True)
292
293 def testCaselessStringUpper(self):
294 cs = pql.PQLCaselessPar.fromLiteral("ABU/SIMBEL", "quack")
295 self.assertEqual(cs.covers("bembel"), True)
296
297 def testCaselessStringSingle(self):
298 cs = pql.PQLCaselessPar.fromLiteral("beMbel", "quack")
299 self.assertEqual(cs.covers("BEmBEL"), True)
300
301 def testIntegerWithStepsTrue(self):
302 cs = pql.PQLIntPar.fromLiteral("50/100/10,200/250/20", "quack")
303 self.assertEqual(cs.covers(60), True)
304 self.assertEqual(cs.covers(220), True)
305
306 def testIntegerWithStepsFalse(self):
307 cs = pql.PQLIntPar.fromLiteral("50/100/10,200/250/20", "quack")
308 self.assertEqual(cs.covers(49), False)
309 self.assertEqual(cs.covers(51), False)
310 self.assertEqual(cs.covers(101), False)
311 self.assertEqual(cs.covers(201), False)
312 self.assertEqual(cs.covers(251), False)
313
314 def testHalfopenFloatTrue(self):
315 cs = pql.PQLFloatPar.fromLiteral("/-3,5/6,12.5/", "quack")
316 self.assertEqual(cs.covers(-5), True)
317 self.assertEqual(cs.covers(5.5), True)
318 self.assertEqual(cs.covers(13), True)
319
320 def testHalfopenFloatFalse(self):
321 cs = pql.PQLFloatPar.fromLiteral("/-3,5/6,12.5/", "quack")
322 self.assertEqual(cs.covers(-2.5), False)
323 self.assertEqual(cs.covers(6.5), False)
324
325
326 class DALISQLTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
327 def _runTest(self, sample):
328 ikAttrs, inVal, expectedFragment, outAsserts = sample
329 args = {"name": "test"}
330 args.update(ikAttrs)
331 ik = MS(svcs.InputKey, **args)
332 ik.set(inVal)
333 inPars, outPars = {ik.name: ik.value}, {}
334 fragment = base.getSQLForField(ik, inPars, outPars)
335 self.assertEqual(expectedFragment, fragment)
336 for key, val in outAsserts:
337 self.assertEqual(outPars[key], val)
338
339 samples = [
340 (dict(xtype="interval", type="real[2]"),
341 "10 20",
342 "test BETWEEN %(test0)s AND %(test1)s",
343 [('test1', 20.0)]),
344 (dict(xtype="interval", type="real[2]"),
345 "-Inf 20",
346 "test < %(test0)s",
347 [('test0', 20.0)]),
348 (dict(xtype="interval", type="real[2]"),
349 "10 Inf",
350 "test > %(test0)s",
351 [('test0', 10.0)]),
352 (dict(type="text"),
353 ["ab", "cd", "ef"],
354 "test IN %(test0)s",
355 [('test0', set(["ab", "cd", "ef"]))]),
356 ]
357
358 def testMJDOnDatetime(self):
359 ik = dalipars.adaptInputKey(
360 MS(svcs.InputKey, name="test", type="timestamp"))
361 ik.set("-Inf 57429")
362 inPars, outPars = {ik.name: ik.value}, {}
363 fragment = base.getSQLForField(ik, inPars, outPars)
364 self.assertEqual(fragment, "test < %(test0)s")
365 self.assertEqual(outPars["test0"],
366 datetime.datetime(2016, 2, 11, 0, 0, 0, 1))
367
368
369 if __name__=="__main__":
370 testhelpers.main(CoversTest)