Debian Codegraph @

tests/attrdeftest.py

raw
1 """
2 Tests for sepecific AttributeDef derivations.
3
4 These are far too few so far because most of this is really old code.
5 Let's fill them back as we go.
6 """
7
8 #c Copyright 2008-2025, the GAVO project <[email protected]>
9 #c
10 #c This program is free software, covered by the GNU GPL. See the
11 #c COPYING file in the source distribution.
12
13
14 from gavo.helpers import testhelpers
15
16 from gavo import base
17 from gavo import utils
18 from gavo.user import docgen
19 from gavo.base.structure import Structure
20
21 from structscaffold import (Color, Child, Child2, Image, Root)
22
23
24 MS = base.makeStruct
25
26
27 class MiscAttributeTest(testhelpers.VerboseTest):
28 """tests for various predefined attribute types.
29 """
30 def testEnumUnicode(self):
31 class En(Structure):
32 _att1 = base.EnumeratedUnicodeAttribute("att1", default="left",
33 validValues=["left", "right"])
34 e = En(None)
35 self.assertEqual(e.att1, "left")
36 e._att1.feed(None, e, "right")
37 self.assertEqual(e.att1, "right")
38 self.assertRaises(base.LiteralParseError, e._att1.feed, None, e, "center")
39 self.assertEqual(e._att1.typeDesc_, "One of: left, right")
40
41 def testBadFloat(self):
42 self.assertRaisesWithMsg(base.LiteralParseError,
43 "At IO:'<color b='knall'/>', (1, 0):"
44 " 'knall' is not a valid value for b",
45 base.parseFromString,
46 (Color, "<color b='knall'/>"))
47
48 def testBadInt(self):
49 self.assertRaisesWithMsg(base.LiteralParseError,
50 "At IO:'<color r='knall'/>', (1, 0):"
51 " 'knall' is not a valid value for r",
52 base.parseFromString,
53 (Color, "<color r='knall'/>"))
54
55 def testBadBoolean(self):
56 class q(Structure):
57 name_ = "q"
58 _att1 = base.BooleanAttribute("att1", default=None)
59 self.assertRaisesWithMsg(base.LiteralParseError,
60 'At IO:\'<q att1="banana"/>\', (1, 0):'
61 ' \'banana\' is not a valid value for att1',
62 base.parseFromString,
63 (q, '<q att1="banana"/>'))
64
65
66 class ReferenceAttTest(testhelpers.VerboseTest):
67 def testRealReference(self):
68 res = base.parseFromString(Root, '<root>'
69 '<pal id="pal1"><color r="20"/></pal>'
70 '<image pal="pal1"/></root>')
71 self.assertEqual(res.ims[0].pal.colors[0].r, 20)
72 self.assertEqual(res.ims[0].pal.parent, res)
73
74 def testElementReference(self):
75 res = base.parseFromString(Root, '<root>'
76 '<pal id="pal1"><color r="20"/></pal>'
77 '<image><pal>pal1</pal></image></root>')
78 self.assertEqual(res.ims[0].pal.colors[0].r, 20)
79 self.assertEqual(res.ims[0].pal.parent, res)
80
81 def testImmediateReference(self):
82 res = base.parseFromString(Root, '<root>'
83 '<image><pal id="pal1"><color r="20"/></pal>'
84 '</image></root>')
85 self.assertEqual(res.ims[0].pal.colors[0].r, 20)
86 self.assertEqual(res.ims[0].pal.parent, res.ims[0])
87
88 def testAtomicFirstChild(self):
89 res = base.parseFromString(Root,
90 '<root><image><pal><map>a, b</map><flavor>yellow</flavor></pal>'
91 '</image></root>')
92 self.assertEqual(res.ims[0].pal.map, ['a', 'b'])
93 self.assertEqual(res.ims[0].pal.flavor, "yellow")
94
95
96 class DictAttrTest(testhelpers.VerboseTest):
97 def testBasic(self):
98 i = base.parseFromString(Image, """<image><map key="a">arthur</map>
99 <map from="b">berta</map></image>""")
100 self.assertEqual(i.maps, {"a": "arthur", "b": "berta"})
101
102 def testNoKey(self):
103 self.assertRaisesWithMsg(base.StructureError,
104 "At IO:'<image><map>arthur</map>', (1, 18):"
105 " Content 'arthur' has no from attribute",
106 base.parseFromString,
107 (Image, """<image><map>arthur</map>"""))
108
109 def testNoExtra(self):
110 self.assertRaisesWithMsg(base.StructureError,
111 'At IO:\'<image><map key="a" extra="no">arthur</map>\', (1, 7):'
112 ' No "extra" attributes on mappings',
113 base.parseFromString,
114 (Image, """<image><map key="a" extra="no">arthur</map>"""))
115
116 def testCumulate(self):
117 i = base.parseFromString(Image, """<image><map key="a">arthur</map>
118 <map from="a" cumulate="True"> berta</map></image>""")
119 self.assertEqual(i.maps, {"a": "arthur berta"})
120
121 def testInverted(self):
122 i = base.parseFromString(Image, """<image><rev key="a">arthur</rev>
123 <rev to="b" cumulate="True">berta</rev></image>""")
124 self.assertEqual(i.rev, {"arthur": "a", "berta": "b"})
125
126 def testMapEmpty(self):
127 self.assertRaisesWithMsg(base.StructureError,
128 'At IO:\'<image><map key="a"/></image>\', (1, 21):'
129 ' Empty map values are not allowed',
130 base.parseFromString,
131 (Image, """<image><map key="a"/></image>"""))
132
133 def testNonString(self):
134 class WithInts(Structure):
135 name_ = "withints"
136 _nums = base.DictAttribute("ints",
137 itemAttD=base.IntAttribute("int"),
138 keyName="german")
139
140 res = base.parseFromString(WithInts,
141 '<withints><int german="eins">1</int><int german="zwei">2'
142 '</int></withints>')
143 self.assertEqual(res.ints, {"eins": 1, "zwei": 2})
144
145 def testEvents(self):
146 i = base.parseFromString(Image, """<image><map key="a">arthur</map>
147 <map from="b">berta</map></image>""")
148 self.assertEqual(list(i._maps.iterEvents(i)),
149 [('start', 'map', None), ('value', 'key', 'a'), ('value', 'content_', 'arthur'), ('end', 'map', None),
150 ('start', 'map', None), ('value', 'key', 'b'), ('value', 'content_', 'berta'), ('end', 'map', None)])
151
152
153 class PropertyAttributeTest(testhelpers.VerboseTest):
154 class WithProp(Structure):
155 name_ = "with"
156 _prop = base.PropertyAttribute(copyable=True)
157 def __repr__(self): return "<WithProp>"
158
159 def testBasic(self):
160 res = base.parseFromString(self.WithProp,
161 '<with><property name="propA">Value</property>'
162 '<property name="propB">other</property></with>')
163 self.assertEqual(res.getProperty("propA"), "Value")
164 self.assertEqual(res.getProperty("propB"), "other")
165 self.assertEqual(res.getProperty("propC", "x"), "x")
166 self.assertRaisesWithMsg(base.NotFoundError,
167 "property 'propC' could not be located in <WithProp>",
168 res.getProperty,
169 ("propC",))
170
171 def testNoEmpties(self):
172 self.assertRaisesWithMsg(base.StructureError,
173 'At IO:\'<with><property name="propA"/></with>\', (1, 30): Empty map values are not allowed',
174 base.parseFromString,
175 (self.WithProp,
176 '<with><property name="propA"/></with>'))
177
178 def testOverwrite(self):
179 res = base.parseFromString(self.WithProp,
180 '<with><property name="propA">Value</property>'
181 '<property name="propA">overwritten</property></with>')
182 self.assertEqual(res.getProperty("propA"), "overwritten")
183
184 def testCumulate(self):
185 res = base.parseFromString(self.WithProp,
186 '<with><property name="propA">Value</property>'
187 '<property name="propA" cumulate="True"> amended</property></with>')
188 self.assertEqual(res.getProperty("propA"), "Value amended")
189
190 def testEvents(self):
191 res = base.parseFromString(self.WithProp,
192 '<with><property name="propA">Value</property>'
193 '<property name="propB">other</property></with>')
194 self.assertEqual(
195 list(res.iterEvents()),
196 [('start', 'property', None), ('value', 'key', 'propA'), ('value', 'content_', 'Value'), ('end', 'property', None),
197 ('start', 'property', None), ('value', 'key', 'propB'), ('value', 'content_', 'other'), ('end', 'property', None)])
198
199
200 class SimpleStructAttributeTest(testhelpers.VerboseTest):
201 class StructBearer(Structure):
202 name_ = "bearer"
203 _simple = base.StructAttribute("simple", childFactory=Child)
204
205 def testConstruction(self):
206 res = MS(self.StructBearer, simple=MS(Child, fab="one"))
207 self.assertEqual(res.simple.fab, "one")
208
209 def testParsing(self):
210 res = base.parseFromString(self.StructBearer,
211 '<bearer><simple fab="one"/></bearer>')
212 self.assertEqual(res.simple.fab, "one")
213
214 def testOverwriting(self):
215 res = base.parseFromString(self.StructBearer,
216 '<bearer><simple fab="one"/><simple fab="two"/></bearer>')
217 self.assertEqual(res.simple.fab, "two")
218
219 def testDefaulting(self):
220 class DefaultBearer(Structure):
221 name_ = "bearer"
222 _simple = base.StructAttribute("simple", childFactory=Child,
223 default=MS(Child, fab="fallback"))
224 res = base.parseFromString(DefaultBearer,
225 '<bearer/>')
226 self.assertEqual(res.simple.fab, "fallback")
227 res = base.parseFromString(DefaultBearer,
228 '<bearer><simple fab="one"/></bearer>')
229 self.assertEqual(res.simple.fab, "one")
230
231 def testAliases(self):
232 class DefaultBearer(Structure):
233 name_ = "bearer"
234 _simple = base.StructAttribute("simple", childFactory=Child,
235 aliases=["foo", "bar"])
236
237 for elName in ["simple", "foo", "bar"]:
238 res = base.parseFromString(DefaultBearer,
239 f'<bearer><{elName} fab="one"/></bearer>')
240 self.assertEqual(res.simple.fab, "one")
241
242 def testChanging(self):
243 orig = MS(self.StructBearer, simple=MS(Child, fab="one"))
244 res = orig.change(simple=MS(Child, fab="new"))
245 self.assertEqual(res.simple.fab, "new")
246
247 def testMissing(self):
248 self.assertRaisesWithMsg(
249 base.StructureError,
250 "You must set simple on bearer elements",
251 MS, (self.StructBearer,))
252
253 def testNotMissing(self):
254 class DefaultBearer(Structure):
255 name_ = "bearer"
256 _simple = base.StructAttribute(
257 "simple", childFactory=Child, default=None)
258 self.assertEqual(MS(DefaultBearer).simple, None)
259
260 def testDoc(self):
261 self.assertEqual(
262 self.StructBearer._simple.makeUserDoc(),
263 "**simple** (contains `Element child`_) -- Undocumented")
264
265
266 class MultiStructAttributeTest(testhelpers.VerboseTest):
267 class StructBearer(Structure):
268 name_ = "bearer"
269
270 @staticmethod
271 def getChild(name):
272 return {
273 "child": Child,
274 "other": Child2}[name]
275
276 _simple = base.MultiStructAttribute("poly",
277 childFactory=getChild, childNames=["child", "other"],
278 default=utils.Undefined)
279
280 def testConstruction(self):
281 res = MS(self.StructBearer, poly=MS(Child, fab="one"))
282 self.assertEqual(res.poly.fab, "one")
283 res = MS(self.StructBearer, poly=MS(Child2, romp="other"))
284 self.assertEqual(res.poly.romp, "other")
285
286 def testParsing(self):
287 res = base.parseFromString(self.StructBearer,
288 '<bearer><child fab="one"/></bearer>')
289 self.assertEqual(res.poly.fab, "one")
290 res = base.parseFromString(self.StructBearer,
291 '<bearer><other romp="one"/></bearer>')
292 self.assertEqual(res.poly.romp, "one")
293
294 def testOverwriting(self):
295 res = base.parseFromString(self.StructBearer,
296 '<bearer><child fab="one"/><other romp="two"/></bearer>')
297 self.assertEqual(res.poly.romp, "two")
298 self.assertRaises(AttributeError,
299 lambda: res.poly.fab)
300
301 def testDefaulting(self):
302 class DefaultBearer(self.StructBearer):
303 name_ = "bearer"
304 _simple = base.MultiStructAttribute("poly",
305 childFactory=self.StructBearer.getChild, default=MS(Child2, romp="x"),
306 childNames=["child", "other"])
307 res = base.parseFromString(DefaultBearer, '<bearer/>')
308 self.assertEqual(res.poly.romp, "x")
309 res = base.parseFromString(DefaultBearer,
310 '<bearer><child fab="one"/></bearer>')
311 self.assertEqual(res.poly.fab, "one")
312
313 def testNoAliases(self):
314 try:
315 class Wontwork(self.StructBearer):
316 name_ = "bearer"
317 _poly = base.MultiStructAttribute("poly",
318 childFactory=self.StructBearer.getChild,
319 childNames=["child", "other"],
320 aliases=["foo", "bar"])
321 except TypeError as msg:
322 self.assertEqual(
323 str(msg),
324 "aliases are not supported with MultiStructAttribute")
325 else:
326 raise AssertionError("MultiStructAttribute does not reject aliases?")
327
328 def testChanging(self):
329 orig = MS(self.StructBearer, poly=MS(Child, fab="one"))
330 res = orig.change(poly=MS(Child2, romp="new"))
331 self.assertEqual(res.poly.romp, "new")
332
333 def testMissing(self):
334 self.assertRaisesWithMsg(
335 base.StructureError,
336 "You must set poly on bearer elements",
337 MS, (self.StructBearer,))
338
339 def testNotMissing(self):
340 class DefaultBearer(self.StructBearer):
341 name_ = "bearer"
342 _simple = base.MultiStructAttribute("poly", default=None,
343 childFactory=self.StructBearer.getChild, childNames=["child", "other"])
344
345 self.assertEqual(MS(DefaultBearer).poly, None)
346
347 def testBadChild(self):
348 self.assertRaisesWithMsg(utils.StructureError,
349 "At IO:'<bearer><invalidChild/></bearer>', (1, 8): bearer elements have no invalidChild attributes or children.",
350 base.parseFromString,
351 (self.StructBearer, '<bearer><invalidChild/></bearer>'))
352
353 def testDoc(self):
354 self.assertEqual(
355 self.StructBearer._simple.makeUserDoc(),
356 "**poly** (contains one of child, an `Element child`_;"
357 " other, an `Element child2`_) -- Undocumented")
358
359
360 class StructListAttributeTest(testhelpers.VerboseTest):
361 class StructBearer(Structure):
362 name_ = "bearer"
363
364 _simple = base.StructListAttribute("simple", childFactory=Child,
365 copyable=True)
366
367 def testConstruction(self):
368 res = MS(self.StructBearer, simple=[])
369 self.assertEqual(res.simple, [])
370
371 res = MS(self.StructBearer, simple=[MS(Child)])
372 self.assertEqual(res.simple[0].fab, "empty")
373
374 res = MS(self.StructBearer, simple=[MS(Child), MS(Child, fab="ooh")])
375 self.assertEqual(res.simple[1].fab, "ooh")
376
377 def testConstructionAutoBuildsList(self):
378 res = MS(self.StructBearer, simple=MS(Child))
379 self.assertEqual(res.simple[0].fab, "empty")
380
381 def testParsing(self):
382 res = base.parseFromString(self.StructBearer,
383 '<bearer><simple fab="one"/><simple/></bearer>')
384 self.assertEqual(res.simple[0].fab, "one")
385 self.assertEqual(res.simple[1].fab, "empty")
386
387 def testDefaulting(self):
388 self.assertRaisesWithMsg(TypeError,
389 "StructListAttributes always default to an empty list",
390 base.StructListAttribute,
391 ("simple", Child),
392 default=MS(Child, fab="fallback"))
393
394 def testAliases(self):
395 class DefaultBearer(Structure):
396 name_ = "bearer"
397 _simple = base.StructListAttribute("simple", childFactory=Child,
398 aliases=["foo", "bar"])
399
400 res = base.parseFromString(DefaultBearer,
401 '<bearer><simple fab="1"/><foo fab="2"/><bar fab="3"/></bearer>')
402 self.assertEqual(res.simple[2].fab, "3")
403
404 def testEvents(self):
405 res = base.parseFromString(self.StructBearer,
406 '<bearer><simple fab="one"/><simple fab="two"/></bearer>')
407 self.assertEqual(
408 list(res._simple.iterEvents(res)), [
409 ('start', 'child', None), ('value', 'fab', 'one'), ('end', 'child', None),
410 ('start', 'child', None), ('value', 'fab', 'two'), ('end', 'child', None)])
411
412 def testCopying(self):
413 res = base.parseFromString(self.StructBearer,
414 '<bearer><simple fab="one"/><simple fab="two"/></bearer>')
415 newOb = MS(self.StructBearer)
416 newOb.feedObject("simple", res._simple.getCopy(res, newOb, None))
417 self.assertEqual(res.simple[1].fab, "two")
418 self.assertEqual(newOb.simple[1].fab, "two")
419 self.assertTrue(res.simple[0] is not newOb.simple[0])
420
421 def testCanUseChildName(self):
422 res = base.parseFromString(self.StructBearer,
423 '<bearer><child fab="one"/><child fab="two"/></bearer>')
424 self.assertEqual(res.simple[0].fab, "one")
425 self.assertEqual(res.simple[1].fab, "two")
426
427 def testDoc(self):
428 self.assertEqual(
429 self.StructBearer._simple.makeUserDoc(),
430 "**simple** (contains `Element child`_ and may be repeated zero or more times) -- Undocumented")
431
432
433 class TypingAttributesTest(testhelpers.VerboseTest):
434 def testDefaults(self):
435 class Silly(Structure):
436 _klotz = base.AttributeDef("klotz")
437
438 self.assertEqual(docgen._getAnnotationsForStructure(Silly), [
439 ('managedAttrs', 'Dict[str, Any]'),
440 ('attrSeq', 'List[]'),
441 ('id', 'str'),
442 ('klotz', 'Any')])
443
444 def testParentMethods(self):
445 class MethAttr(base.AttributeDef):
446 typingType_ = "IO"
447 def iterParentMethods(self):
448 def getSomething(self, par1, par2):
449 return par1+par2
450 def getOther(self, foo: str, bar: int) -> str:
451 return foo*bar
452 yield ("getSomething", getSomething)
453 yield ("getOther", getOther)
454
455 class Foo(Structure):
456 _platt = MethAttr("platt")
457
458 self.assertEqual(docgen._getAnnotationsForStructure(Foo), [
459 ('managedAttrs', 'Dict[str, Any]'),
460 ('attrSeq', 'List[]'),
461 ('id', 'str'),
462 ('platt', 'IO'),
463 ('getSomething', 'Callable'),
464 ('getOther', 'Callable[..., "str"]')])
465
466
467 if __name__=="__main__":
468 testhelpers.main(SimpleStructAttributeTest)