Debian Codegraph @

tests/structuretest.py

raw
1 """
2 Tests for base.Structure-s.
3
4 This is for sort-of generic functionality of structs.
5
6 Tests for specific types of attributes should go to attrdeftest.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 from io import StringIO
16 import re
17 import unittest
18
19 from gavo.helpers import testhelpers
20
21 from gavo import base
22 from gavo.base import structure
23 from gavo.base import xmlstruct
24
25 from structscaffold import (Color, Foo, Foos, Bla,
26 Palette, Image, Root)
27
28
29 class SimpleStructureTest(unittest.TestCase):
30 """tests for very basic structures.
31 """
32 def _getStruct(self):
33 class Bla(structure.ParseableStructure):
34 _att1 = base.UnicodeAttribute("att1", default="default")
35 return Bla
36
37 def testSimpleAttSetting(self):
38 class Bla(structure.ParseableStructure):
39 _att1 = base.UnicodeAttribute("att1")
40 s1 = Bla(None)
41 self.assertEqual(s1.att1, None)
42 s1._att1.feed(None, s1, "value")
43 self.assertEqual(s1.att1, "value")
44
45 def testDefaultAtt(self):
46 Bla = self._getStruct()
47 s1 = Bla(None)
48 self.assertEqual(s1.att1, "default")
49
50 def testNoInterference(self):
51 Bla = self._getStruct()
52 s1, s2 = Bla(None), Bla(None)
53 s2._att1.feed(None, s2, "Foo")
54 self.assertEqual(s1.att1, "default")
55 self.assertEqual(s2.att1, "Foo")
56
57 def testDefault(self):
58 Bla = self._getStruct()
59 s1 = Bla(None, att1="no default")
60 self.assertEqual(s1.att1, "no default")
61
62
63 class AtomListStructureTest(unittest.TestCase):
64 """tests for structures with lists.
65 """
66 def testBasic(self):
67 s1 = Bla(None)
68 self.assertEqual(s1.items, [])
69 s1._att1.feed(None, s1, "2")
70 self.assertEqual(s1.items, [2])
71 s1._att1.feedObject(s1, 1)
72 self.assertEqual(s1.items, [2, 1])
73
74 def testNoInterference(self):
75 s1, s2 = Bla(None), Bla(None)
76 s1._att1.feedObject(s1, 3)
77 s2._att1.feedObject(s2, 1)
78 self.assertEqual(s1.items, [3])
79 self.assertEqual(s2.items, [1])
80
81 def testRaises(self):
82 s1 = Bla(None)
83 try:
84 s1._att1.feed(None, s1, "x4")
85 except base.LiteralParseError as msg:
86 self.assertEqual(msg.attName, "item")
87 self.assertEqual(msg.literal, "x4")
88 else:
89 self.fail("Bad integer literal doesn't raise correct exc. in list")
90
91
92 def _feedInto(baseStruct, eventList):
93 ep = xmlstruct.EventProcessor(baseStruct, base.ParseContext())
94 for ev in eventList:
95 ep.feed(*ev)
96 return ep.result
97
98
99 class AtomicFeedTest(testhelpers.VerboseTest):
100 """tests for feeding into atomic structures.
101 """
102 def _getPlainStructure(self):
103 class Bla(structure.ParseableStructure):
104 name_ = "bla"
105 _foo = base.UnicodeAttribute("foo", default="default")
106 _bar = base.IntAttribute("bar", 0)
107 return Bla
108
109 def testSomeAtoms(self):
110 Bla = self._getPlainStructure()
111 s1 = _feedInto(Bla, [
112 ("start", "bla"),
113 ("start", "foo"),
114 ("value", "content_", "no default"),
115 ("end", "foo"),
116 ("value", "bar", 3),])
117 self.assertEqual(s1.foo, "no default")
118 self.assertEqual(s1.bar, 3)
119
120 def testRaising(self):
121 Bla = self._getPlainStructure()
122 self.assertRaisesWithMsg(base.StructureError,
123 "bla elements have no xxx attributes or children.", _feedInto,
124 (Bla, [("start", "bla"), ("start", "xxx")]))
125
126
127 class XMLParseTest(testhelpers.VerboseTest):
128 """tests for building structures out of XML documents.
129 """
130 def testSimpleParse(self):
131 f = xmlstruct.parseFromStream(Foo, StringIO("""<foo name="red">
132 <color g="0" b="0"/></foo>"""))
133 self.assertEqual(f.color.r, 255)
134 self.assertEqual(f.color.g, 0)
135 self.assertEqual(f.color.b, 0)
136 self.assertEqual(f.name, "red")
137
138 def testIdSet(self):
139 f = xmlstruct.parseFromStream(Foos, StringIO("""<foos>
140 <foo name="red" id="x"><color g="0" b="0"/></foo>
141 <foo name="blue"><color g="0" r="0" id="y"/></foo></foos>"""))
142 self.assertEqual(f.plups[0].id, "x")
143 self.assertEqual(f.plups[1].color.id, "y")
144
145 def testWrongRootElement(self):
146 self.assertRaisesWithMsg(base.StructureError,
147 'At IO:\'<foo name="red"> <color g="0" b="0"/></foo>\', (1, 0):'
148 " Expected root element color, found foo",
149 xmlstruct.parseFromStream, (Color, StringIO("""<foo name="red">
150 <color g="0" b="0"/></foo>""")))
151
152 def testMsgBadAtt(self):
153 self.assertRaisesWithMsg(base.StructureError,
154 'At IO:\'<color noAtt="30"/>\', (1, 0):'
155 " color elements have no noAtt attributes or children.",
156 xmlstruct.parseFromString, (Color, '<color noAtt="30"/>'))
157
158 def testMsgBadChild(self):
159 self.assertRaisesWithMsg(base.StructureError,
160 "At IO:'<color><noAtt>30</noAtt></color>', (1, 7):"
161 " color elements have no noAtt attributes or children.",
162 xmlstruct.parseFromString, (Color, '<color><noAtt>30</noAtt></color>'))
163
164 def testAtomListParse(self):
165 f = xmlstruct.parseFromStream(Bla, StringIO('<bla item="0"><item>1</item>'
166 '<item>2</item></bla>'))
167 self.assertEqual(f.items, [0, 1, 2])
168
169 def testStructContent(self):
170 f = xmlstruct.parseFromString(Foo, '<foo name="xy">Some content</foo>')
171 self.assertEqual(f.content_, "Some content")
172 self.assertRaisesWithMsg(base.StructureError,
173 "At IO:'<color>Some content</color>', (1, 19):"
174 " color elements must not have character data content.",
175 xmlstruct.parseFromString, (Color, '<color>Some content</color>'))
176
177 def testNoAttrsOnAttrs(self):
178 self.assertRaisesWithMsg(
179 base.StructureError,
180 "At IO:'<foo><name attr=\"out\">xy</name></foo>', (1, 5):"
181 " name is atomic and thus has no attribute attr.",
182 xmlstruct.parseFromString,
183 (Foo, '<foo><name attr="out">xy</name></foo>'))
184
185 def testNoChildrenOnAttrs(self):
186 self.assertRaisesWithMsg(
187 base.StructureError,
188 "At IO:'<foo><name><child>out</child>xy</name></foo>', (1, 11):"
189 " name elements cannot have child children",
190 xmlstruct.parseFromString,
191 (Foo, '<foo><name><child>out</child>xy</name></foo>'))
192
193
194 class CopyTest(testhelpers.VerboseTest):
195 """tests for copying structures.
196 """
197 def testCopyStruct(self):
198 f = xmlstruct.parseFromStream(Foo, StringIO("""<foo name="red">
199 <color g="0" b="0"/></foo>"""))
200 f2 = f.copy(None)
201 f.color.g = 27
202 self.assertEqual(f2.color.g, 0)
203
204 def testCopyAtomList(self):
205 f = xmlstruct.parseFromStream(Bla, StringIO('<bla item="0"><item>1</item>'
206 '<item>2</item></bla>'))
207 f2 = f.copy(None)
208 f2.items.append(3)
209 self.assertEqual(f.items, [0, 1, 2])
210 self.assertEqual(f2.items, [0, 1, 2, 3])
211
212 def testCopyStructList(self):
213 f = xmlstruct.parseFromStream(Palette, StringIO('<pal><color/>'
214 '<color g="0"/></pal>'))
215 f2 = f.copy(None)
216 f2.colors.append(Color(f2, r=0))
217 self.assertEqual(len(f.colors), 2)
218 self.assertEqual(len(f2.colors), 3)
219
220 def testOriginal(self):
221 f = xmlstruct.parseFromStream(Palette, StringIO('<pal><color id="x">'
222 '<r>7</r></color><color g="0" original="x"/></pal>'))
223 self.assertEqual(f.colors[0].g, 255)
224 self.assertEqual(f.colors[1].g, 0)
225 f.colors[1].r = 8
226 self.assertEqual(f.colors[1].r, 8)
227 self.assertEqual(f.colors[0].r, 7)
228
229 def testTypecheck(self):
230 self.assertRaisesWithMsg(base.StructureError,
231 'At IO:\'<pal><foo name="x" id="xy"/><color original="xy"/></pal>\', (1, 28):'
232 " Reference to 'xy' yielded object of type Foo, but expected a(n) Color"
233 " instance.",
234 xmlstruct.parseFromString, (Palette, '<pal><foo name="x" id="xy"/>'
235 '<color original="xy"/></pal>'))
236
237 def testElementRefusal(self):
238 self.assertRaisesWithMsg(base.StructureError,
239 'At IO:\'<pal><color id="xy"/><color r="2"><original>xy</origi...\', (1, 46):'
240 " Original must be applied before modifying the destination structure.",
241 xmlstruct.parseFromString, (Palette, '<pal><color id="xy"/>'
242 '<color r="2"><original>xy</original></color></pal>'))
243
244 def testBadId(self):
245 self.assertRaisesWithMsg(base.NotFoundError,
246 "Element with id 'xy' could not be located in parse context",
247 xmlstruct.parseFromString, (Palette, '<pal><color original="xy"/>'
248 '</pal>'))
249
250
251 class FeedFromTest(testhelpers.VerboseTest):
252 """tests for working of feedFrom hackery.
253 """
254 def testBasic(self):
255 f = xmlstruct.parseFromString(Palette,
256 '<pal id="pal1"><foo name="x"><color r="0"/>content</foo></pal>')
257 f2 = xmlstruct.parseFromString(Palette,
258 '<pal id="pal2"/>')
259 f2.feedFrom(f)
260 self.assertEqual(f2.foos[0].content_, "content",
261 "Copyable attribute was not copied")
262 self.assertEqual(f2.id, "pal2", "Non-copyable attribute was copied")
263
264
265 class BeforeTest(testhelpers.VerboseTest):
266 """tests for sorting of children.
267 """
268 def testWorkingSort(self):
269 class Foo(base.Structure):
270 _att1 = base.UnicodeAttribute("b", before="a")
271 _att2 = base.UnicodeAttribute("a")
272 self.assertEqual([a.name_ for a in Foo.attrSeq], ["b", "a", "id"])
273
274 def testBailOnCycle(self):
275 def defineBadStruct():
276 class Foo(base.Structure):
277 _att1 = base.UnicodeAttribute("b", before="a")
278 _att2 = base.UnicodeAttribute("a", before="c")
279 _att3 = base.UnicodeAttribute("c", before="b")
280 self.assertRaises(ValueError, defineBadStruct)
281
282
283 class FeedingTest(testhelpers.VerboseTest):
284 def testMixedParse(self):
285 f = _feedInto(Foo, [
286 ("start", "foo"),
287 ("start", "color"),
288 ("value", "r", "10"),
289 ("start", "g"),
290 ("value", "content_", "20"),
291 ("end", "g"),
292 ("end", "color"),
293 ("start", "name"),
294 ("value", "content_", "blue"),
295 ("end", "name"),])
296 self.assertEqual(f.color.r, 10)
297 self.assertEqual(f.color.g, 20)
298 self.assertEqual(f.color.b, 255)
299 self.assertEqual(f.name, "blue")
300
301
302 class IterEventsTest(testhelpers.VerboseTest):
303 def testPlainAttribute(self):
304 s = base.parseFromString(Color, '<color r="5" g="7"/>')
305 self.assertEqual(list(s.iterEvents()),
306 [('value', 'g', '7'), ('value', 'r', '5')])
307
308 def testNamedRef(self):
309 # see testImmediateRef for the counterpart where there's not
310 # actually a reference to be filled
311 stuff = base.parseFromString(Root, '<root>'
312 '<pal id="pal1"><color r="20"/></pal>'
313 '<image pal="pal1"/></root>')
314 self.assertTrue(('value', 'pal', 'pal1') in list(stuff.iterEvents()))
315
316 # See commented-out parsecontext.ReferenceAttribute.iterEvents
317 # def testImmediateRef(self):
318 # stuff = base.parseFromString(Root, '<root>'
319 # '<image><pal id="pal1"><color r="20"/></pal></image></root>')
320 # # make sure the pal element is present (rather than a bogus reference)
321 # self.failUnless(('start', 'pal', None) in
322 # list(stuff.iterEvents()))
323
324 def testNamedRefCopied(self):
325 stuff = base.parseFromString(Root, '<root>'
326 '<pal id="pal1"><color r="20"/></pal>'
327 '<image id="im1" pal="pal1"/><image original="im1"/></root>')
328 self.assertEqual(
329 list(stuff.iterEvents()).count(('value', 'pal', 'pal1')),
330 2)
331
332 def testAtomList(self):
333 stuff = base.parseFromString(Image,
334 '<image><calib>abc</calib><calib>def</calib></image>')
335 evs = list(stuff.iterEvents())
336 self.assertEqual(len(evs), 6)
337 self.assertEqual(evs[1], ('value', 'content_', 'abc'))
338 self.assertEqual(evs[2], ('end', 'calib', None))
339
340
341 class AttachedPositionsTest(testhelpers.VerboseTest):
342 sampleXML = ('<root>\n'
343 '<pal id="pal1">\n<color r="20"/></pal>\n'
344 '<pal id="pal2">\n<color r="10"/></pal>\n'
345 '</root>')
346
347 def testPositionAdded(self):
348 root = base.parseFromString(Root, self.sampleXML)
349 self.assertEqual(root.getSourcePosition(),
350 'IO:\'<root> <pal id="pal1"> <color r="20"/></pal> <pal id=...\', line 1')
351 self.assertEqual(root.pals[0].getSourcePosition(),
352 'IO:\'<root> <pal id="pal1"> <color r="20"/></pal> <pal id=...\', line 2')
353 self.assertEqual(root.pals[1].getSourcePosition(),
354 'IO:\'<root> <pal id="pal1"> <color r="20"/></pal> <pal id=...\', line 4')
355
356 def testFilePositions(self):
357 def clean(s):
358 return re.sub(".*/", "", s)
359
360 with testhelpers.testFile("bla.xml", self.sampleXML) as p:
361 with open(p) as f:
362 root = base.parseFromStream(Root, f)
363 self.assertEqual(
364 clean(root.getSourcePosition()),
365 'bla.xml, line 1')
366 self.assertEqual(
367 clean(root.pals[0].getSourcePosition()),
368 'bla.xml, line 2')
369 self.assertEqual(
370 clean(root.pals[1].getSourcePosition()),
371 'bla.xml, line 4')
372
373
374 if __name__=="__main__":
375 testhelpers.main(IterEventsTest)