Debian Codegraph @

tests/scriptingtest.py

raw
1 """
2 Tests dealing with script parsing and execution.
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 from gavo.helpers import testhelpers
12
13 from gavo import base
14 from gavo import rscdesc
15 from gavo import rsc
16 from gavo import rscdef
17 from gavo.rscdef import scripting
18
19 import tresc
20
21 class FakeRunner(scripting.ScriptRunner):
22 """a script runner that just notices something has run.
23
24 Fetch the stuff run destructively by using getRunScripts()
25 """
26 _scriptsRun = []
27
28 @classmethod
29 def getScriptsRun(cls):
30 try:
31 return cls._scriptsRun[:]
32 finally:
33 cls._scriptsRun[:] = []
34
35 @classmethod
36 def reset(cls):
37 cls._scriptsRun = []
38
39 def _prepare(self, script):
40 self.toNote = script.id
41
42 def run(self, table, **kwargs):
43 self._scriptsRun.append(table.tableDef.id+"-"+self.toNote)
44
45 scripting.RUNNER_CLASSES["Fake"] = FakeRunner
46 scripting.Script._lang.validValues.add("Fake")
47
48
49 class ScriptTest(testhelpers.VerboseTest):
50 """tests for script elements
51
52 (but not actual scripting, that's somewhere else)
53 """
54 def testOkScripts(self):
55 s = base.parseFromString(scripting.Script, '<script type="beforeDrop"'
56 ' lang="SQL" name="test">drop table foo</script>')
57 self.assertEqual(s.type, "beforeDrop")
58 self.assertEqual(s.name, "test")
59 self.assertEqual(s.content_, "drop table foo")
60
61 def testBadScripts(self):
62 self.assertRaises(base.StructureError, base.parseFromString,
63 *(scripting.Script, '<script type="bad">xy</script>'))
64 self.assertRaises(base.StructureError, base.parseFromString,
65 *(scripting.Script, '<script name="bad">xy</script>'))
66
67 def testBadScriptType(self):
68 self.assertRaisesWithMsg(base.StructureError,
69 'At IO:\'<table id="foo" onDisk="True"><script type="newSource...\', (1, 56):'
70 ' Invalid script type newSource for table elements',
71 base.parseFromString,
72 (rscdef.TableDef,
73 '<table id="foo" onDisk="True"><script type="newSource"/></table>'))
74
75 def testOnDiskOnly(self):
76 self.assertRaisesWithMsg(base.StructureError,
77 'At IO:\'<table id="foo"><script lang="Fake" type="preCreation...\', (1, 56):'
78 ' Scripts are only supported for onDisk tables',
79 base.parseFromString,
80 (rscdef.TableDef,
81 '<table id="foo"><script lang="Fake" type="preCreation"/></table>'))
82
83
84 class SQLSplittingTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
85 grammar = scripting.getSQLScriptGrammar()
86
87 def _runTest(self, sample):
88 script, expectedNumberOfParts = sample
89 parts = self.grammar.parseString(script)
90 self.assertEqual(len(parts), expectedNumberOfParts,
91 "Unexpected number of parts: %s"%len(parts))
92
93 samples = [
94 ("select * from foo", 1),
95 ("select * from foo;", 1),
96 ("select * from foo where \"cra;zy\"=';'", 1),
97 ("select * from foo;update where bla=7", 2),
98 ("SELECT a=$$a;bc$$", 1),
99 ("SELECT a=$$abc$$;c", 2),
100 ("/* this should be ignored: ; */; this should be there", 1),
101 ("$funcdef$ stmt; stmt; $$deep;er$$ $funcdef$; two", 2),
102 ("$funcdef$ stmt\n\n; stmt; $$deep;er$$ $funcdef$; two", 2),
103 ("'multiline\nstring;'", 1),
104 ("statement1;\n -- Sp'\nstatement 2 'quoted';", 2),
105 ]
106
107
108 class ScriptingRunTest(testhelpers.VerboseTest):
109 resources = [("conn", tresc.dbConnection)]
110
111 def testFromTable(self):
112 FakeRunner.reset()
113 self.conn.execute("drop table if exists test.foo")
114 res = base.parseFromString(rscdesc.RD,
115 """<resource schema="test"><table id="foo" onDisk="True">
116 <script type="preCreation" lang="Fake" id="precre"/>
117 <script type="preIndex" lang="Fake" id="prein"/>
118 <script type="postCreation" lang="Fake" id="pocre"/>
119 <script type="beforeDrop" lang="Fake" id="befdro"/>
120 </table>
121 <data id="imp">
122 <make table="foo"/>
123 </data>
124 </resource>""")
125 try:
126 d = rsc.makeData(res.getById("imp"), connection=self.conn)
127 self.assertEqual(FakeRunner.getScriptsRun(),
128 ["foo-precre", "foo-prein", "foo-pocre"])
129 finally:
130 d.dropTables(rsc.parseValidating)
131 self.assertEqual(FakeRunner.getScriptsRun(), ["foo-befdro"])
132
133 def testFromTableAndMake(self):
134 res = base.parseFromString(rscdesc.RD,
135 """<resource schema="test"><table id="foo" onDisk="True">
136 <script type="preCreation" lang="Fake" id="precre"/>
137 <script type="preIndex" lang="Fake" id="prein"/>
138 <script type="postCreation" lang="Fake" id="pocre"/>
139 <script type="beforeDrop" lang="Fake" id="befdro"/>
140 </table>
141 <data id="imp">
142 <make table="foo">
143 <script type="preCreation" lang="Fake" id="mprecre"/>
144 <script type="preIndex" lang="Fake" id="mprein"/>
145 <script type="postCreation" lang="Fake" id="mpocre"/>
146 <script type="beforeDrop" lang="Fake" id="mbefdro"/>
147 <script type="preImport" lang="Fake" id="preimp"/>
148 <script type="newSource" lang="Fake" id="newso"/>
149 </make>
150 </data>
151 </resource>""")
152 try:
153 d = rsc.makeData(res.getById("imp"), connection=self.conn
154 )
155 self.assertEqual(FakeRunner.getScriptsRun(),
156 [ 'foo-precre', 'foo-mprecre', 'foo-prein',
157 'foo-mprein', 'foo-pocre', 'foo-mpocre'])
158 finally:
159 d.dropTables(rsc.parseValidating)
160 self.assertEqual(FakeRunner.getScriptsRun(),
161 ["foo-befdro", "foo-mbefdro"])
162
163 def testUpdatingScripts(self):
164 res = base.parseFromString(rscdesc.RD,
165 """<resource schema="test"><table id="foo" onDisk="True">
166 <script type="preCreation" lang="Fake" id="precre"/>
167 <script type="postCreation" lang="Fake" id="pocre"/>
168 </table>
169 <data id="imp" updating="True">
170 <make table="foo">
171 <script type="beforeDrop" lang="Fake" id="mbefdro"/>
172 <script type="preImport" lang="Fake" id="preimp"/>
173 </make>
174 </data>
175 </resource>""")
176 try:
177 d = rsc.makeData(res.getById("imp"), connection=self.conn)
178 # first run: things run all normal.
179 self.assertEqual(FakeRunner.getScriptsRun(),
180 ['foo-precre', 'foo-preimp', 'foo-pocre'])
181
182 # second run: no table scripts run because we're updating
183 d = rsc.makeData(res.getById("imp"), connection=self.conn)
184 self.assertEqual(FakeRunner.getScriptsRun(), [])
185
186 finally:
187 # drop scripts always run
188 d.dropTables(rsc.parseValidating)
189 self.assertEqual(FakeRunner.getScriptsRun(),
190 ["foo-mbefdro"])
191
192 def testFailingPythonScript(self):
193 rd = base.parseFromString(rscdesc.RD,
194 """<resource schema="test"><table id="foo" onDisk="True">
195 <script type="preCreation" lang="python">
196 raise ValueError("Broken Script")
197 </script>
198 </table>
199 </resource>""")
200
201 try:
202 t = rsc.TableForDef(rd.getById("foo"), connection=self.conn)
203 self.assertRaisesWithMsg(
204 base.StructureError,
205 'At IO:\'<resource schema="test"><table id="foo" onDisk="True"...\', line 2:'
206 ' Execution of python script anonymous failed: Broken Script',
207 t.create,
208 ())
209 finally:
210 self.conn.rollback()
211
212 def testFailingSQLScript(self):
213 rd = base.parseFromString(rscdesc.RD,
214 """<resource schema="test"><table id="foo" onDisk="True">
215 <script type="preCreation" lang="SQL">SELECT UPDATE CREATE</script>
216 </table>
217 </resource>""")
218 try:
219 t = rsc.TableForDef(rd.getById("foo"), connection=self.conn)
220 self.assertRaisesWithMsg(
221 base.StructureError,
222 'At IO:\'<resource schema="test"><table id="foo" onDisk="True"...\', line 2:'
223 ' Execution of SQL script anonymous failed: syntax error at or near "CREATE"\nLINE 1: SELECT UPDATE CREATE\n ^\n',
224 t.create,
225 ())
226 finally:
227 self.conn.rollback()
228
229
230 if __name__=="__main__":
231 testhelpers.main(SQLSplittingTest)