File: utilstest.py

package info (click to toggle)
gavodachs 2.11%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 8,972 kB
  • sloc: python: 100,078; xml: 3,014; javascript: 2,360; ansic: 918; sh: 216; makefile: 31
file content (438 lines) | stat: -rw-r--r-- 12,423 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""
Tests for the various modules in utils.
"""

#c Copyright 2008-2024, the GAVO project <gavo@ari.uni-heidelberg.de>
#c
#c This program is free software, covered by the GNU GPL.  See the
#c COPYING file in the source distribution.


import os
import pathlib

from gavo.helpers import testhelpers

from gavo import base
from gavo import utils
from gavo.utils import algotricks
from gavo.utils import codetricks
from gavo.utils import stanxml
from gavo.utils import typeconversions


class TopoSortTest(testhelpers.VerboseTest):
	def testEmpty(self):
		self.assertEqual(algotricks.topoSort([]), [])

	def testSimpleGraph(self):
		self.assertEqual(algotricks.topoSort([(1,2), (2,3), (3,4)]), [1,2,3,4])

	def testComplexGraph(self):
		self.assertEqual(algotricks.topoSort([(1,2), (2,3), (1,3), (3,4),
			(1,4), (2,4)]), [1,2,3,4])

	def testCyclicGraph(self):
		self.assertRaisesWithMsg(ValueError, "Graph not acyclic, cycle: 2->1",
			algotricks.topoSort, ([(1,2), (2,1)],))


class PrefixTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
	def _runTest(self, args):
		s1, s2, prefixLength = args
		self.assertEqual(utils.commonPrefixLength(s1, s2), prefixLength)
	
	samples = [
		("abc", "abd", 2),
		("abc", "a", 1),
		("abc", "", 0),
		("", "abc", 0),
		("a", "abc", 1),
		("z", "abc", 0),]


class IdManagerTest(testhelpers.VerboseTest):
	"""tests for working id manager.
	"""
	def setUp(self):
		self.im = utils.IdManagerMixin()

	def testNoDupe(self):
		testob = IdManagerTest
		self.assertEqual(self.im.makeIdFor(testob),
			utils.intToFunnyWord(id(testob)))
		self.assertRaises(ValueError,
			self.im.makeIdFor,
			testob)

	def testRetrieve(self):
		testob = "abc"
		theId = self.im.makeIdFor(testob)
		self.assertEqual(self.im.getIdFor(testob), theId)
	
	def testRefRes(self):
		testob = "abc"
		theId = self.im.makeIdFor(testob)
		self.assertEqual(self.im.getForId(theId), testob)
	
	def testUnknownOb(self):
		self.assertRaises(utils.NotFoundError, self.im.getIdFor, 1)

	def testUnknownId(self):
		self.assertRaises(utils.NotFoundError, self.im.getForId, "abc")

	def testSuggestion(self):
		testob = object()
		givenId = self.im.makeIdFor(testob, "ob1")
		self.assertEqual(givenId, "ob1")
		testob2 = object()
		id2 = self.im.makeIdFor(testob2, "ob1/")
		self.assertEqual(id2, "ob1-02")
		self.assertTrue(testob is self.im.getForId("ob1"))
		self.assertTrue(testob2 is self.im.getForId("ob1-02"))


class LoadModuleTest(testhelpers.VerboseTest):
	"""tests for cli's module loader.
	"""
	def testLoading(self):
		ob = utils.loadInternalObject("utils.codetricks", "loadPythonModule")
		self.assertTrue(hasattr(ob, "__call__"))
	
	def testNotLoading(self):
		self.assertRaises(ImportError, utils.loadInternalObject, "noexist", "u")
	
	def testBadName(self):
		self.assertRaises(AttributeError, utils.loadInternalObject,
			"utils.codetricks", "noexist")


class CachedGetterTest(testhelpers.VerboseTest):
	def testNormal(self):
		g = utils.CachedGetter(lambda c: [c], 3)
		self.assertEqual(g(), [3])
		g().append(4)
		self.assertEqual(g(), [3, 4])
	
	def testMortal(self):
		g = utils.CachedGetter(lambda c: [c], 3,
			isAlive=lambda l: len(l)<3)
		g().append(4)
		self.assertEqual(g(), [3,4])
		g().append(5)
		self.assertEqual(g(), [3])


class SimpleTextTest(testhelpers.VerboseTest):
	def testFeatures(self):
		with testhelpers.testFile("test.txt",
				r"""# Test File\
	this is stripped
An empty line is ignored

Contin\
uation lines \
# (a comment in between is ok)
  are concatenated
""")    as fName:
			with open(fName) as f:
				res = list(utils.iterSimpleText(f))

		self.assertEqual(res, [
			(2, "this is stripped"),
			(3, "An empty line is ignored"),
			(8, "Continuation lines are concatenated")])

	def testNoTrailingBackslash(self):
		with testhelpers.testFile("test.txt",
				"""No
non-finished\\
continuation\\""") as fName:
			with open(fName) as f:
				self.assertRaisesWithMsg(utils.SourceParseError,
					"At line 3: File ends with a backslash",
					lambda f: list(utils.iterSimpleText(f)),
					(f,))


class ToVOTableTypeTest(testhelpers.VerboseTest,
		metaclass=testhelpers.SamplesBasedAutoTest):
	def _runTest(self, sample):
		sqlType, voTableType = sample
		self.assertEqual(
			typeconversions.sqltypeToVOTable(sqlType),
			voTableType)
	
	samples = [
		("double precision", ('double', None, None)),
		("text", ('char', "*", None)),
		("char", ('char', '1', None)),
		("unicode", ('unicodeChar', "*", None)),
		("double precision[2]", ('double', '2', None)),
# 5
		("timestamp", ("char", "19", "timestamp")),
		("spoint", ("double", "2", "point")),
		("int4range", ("int", "2", "interval")),
		("timestamp[5]", ("char", "19x5", "timestamp")),
		("scircle[5]", ("double", "3x5", "circle")),
# 10
		("char[1]", ("char", "1", None)),
		("char[12][]", ("char", "12x*", None)),
		# we should probably flat this as invalid
		("char(12)[*]", ("char", "12x*", None)),
		("varchar(*)", ("char", "*", None)),
		# we probably shouldn't let the following parse
		("varchar[13][15](*)", ("char", "13x15x*", None)),
# 15
		("varchar(*)", ("char", "*", None)),
	]


class ToVOTableErrorTest(testhelpers.VerboseTest,
		metaclass=testhelpers.SamplesBasedAutoTest):
	def _runTest(self, sample):
		sqlType, message = sample
		self.assertRaisesWithMsg(Exception,
			message,
			typeconversions.sqltypeToVOTable,
			(sqlType,))
	
	samples = [
		("varchar[1", "No VOTable type for varchar[1"),
		("vanqual", "No VOTable type for vanqual"),
		("char[][]",
			"Arrays may only have variable length in the last dimension"),
	]


class NoModuleAliasingTest(testhelpers.VerboseTest):
	def testAliasing(self):
		dn = base.getConfig("inputsDir")
		with testhelpers.testFile("klotz.py", "sentinel = 1",
				inDir=os.path.join(dn, "mod1")) as modsrc1:
			with testhelpers.testFile("klotz.py", "sentinel = 2",
					inDir=os.path.join(dn, "mod2")) as modsrc2:
				mod1, spec1 = codetricks.loadPythonModule(modsrc1[:-3])
				mod2, spec2 = codetricks.loadPythonModule(modsrc2[:-3])
				self.assertEqual(mod1.sentinel, 1)
				self.assertEqual(mod2.sentinel, 2)
				try:
					import klotz  #noflake: supposed to fail
				except ImportError:
					# this must fail in order to keep "local" modules from polluting
					# global imports.
					pass
				else:
					self.fail("loadPythonModule messed up sys.modules or sys.path.")


class StanXMLTest(testhelpers.VerboseTest):
	class Model(object):
		class MEl(stanxml.Element):
			_local = True
		class Root(MEl):
			_childSequence = ["Child", "Nilble"]
		class Child(MEl):
			_childSequence = ["Foo", None]
		class Other(MEl):
			pass
		class Nilble(stanxml.NillableMixin, MEl):
			_a_restatt = None

	def testNoTextContent(self):
		M = self.Model
		self.assertRaises(stanxml.ChildNotAllowed, lambda:M.Root["abc"])
	
	def testTextContent(self):
		M = self.Model
		data = M.Root[M.Child["a\xA0bc"]]
		self.assertEqual(data.render(), b'<Root><Child>a\xc2\xa0bc</Child></Root>')

	def testRetrieveText(self):
		M = self.Model
		data = M.Other["thrown away", M.Other["mixed"], " remaining "]
		self.assertEqual(data.text_, " remaining ")

	def testNillableNil(self):
		M = self.Model
		rendered = M.Root[M.Nilble()].render()
		self.assertTrue(b'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
			in rendered)
		self.assertTrue(b'Nilble xsi:nil="true"' in rendered)
	
	def testNillableNonNil(self):
		M = self.Model
		rendered = M.Root[M.Nilble["Value"]].render()
		self.assertTrue(b"<Nilble>Value</Nilble>" in rendered)
		self.assertFalse(b'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
			in rendered)
	
	def testNillableAttribute(self):
		M = self.Model
		rendered = M.Root[M.Nilble(restatt="x")].render()
		self.assertTrue(b'<Nilble restatt="x" xsi:nil="true"></Nilble>' in rendered)

	def testSerialisingException(self):
		try:
			_ = 1/0
		except Exception as raised:
			e = raised

		M = self.Model
		rendered = M.Root[M.Child[e]].render()
		self.assertTrue(
			b"<Child>EXCEPTION:\nZeroDivisionError: division by zero"
			in rendered)

	def testLocalAttribute(self):
		M = self.Model
		doc = M.Root[M.Child["x"]]
		doc.addAttribute("xmlns:foo", "urn:foo")
		doc.addAttribute("xmlns:bar", "urn:bar")

		self.assertEqual(
			doc.render(),
			b'<Root xmlns:bar="urn:bar" xmlns:foo="urn:foo"><Child>x</Child></Root>')


class StanXMLNamespaceTest(testhelpers.VerboseTest):

	stanxml.registerPrefix("ns1", "http://bar.com", None)
	stanxml.registerPrefix("ns0", "http://foo.com", None)
	stanxml.registerPrefix("foo", "http://bori.ng", "http://schema.is.here")

	class E(object):
		class LocalElement(stanxml.Element):
			_prefix = "ns1"
			_local = _mayBeEmpty = True
		class A(LocalElement):
			_a_x = None
		class B(LocalElement):
			_a_y = None
		class NSElement(stanxml.Element):
			_prefix = "ns0"
		class C(NSElement):
			_a_z = "ab"
		class D(NSElement):
			_a_u = "x"
			_name_a_u = "foo:u"
			_additionalPrefixes = frozenset(["foo"])

	def testTraversal(self):
		tree = self.E.A[self.E.B, self.E.B, self.E.A]
		def record(node, content, attrDict, childIter):
			return (node.name_,
				[c.apply(record) for c in childIter])
		self.assertEqual(tree.apply(record),
			('A', [('B', []), ('B', []), ('A', [])]))
	
	def testSimpleRender(self):
		tree = self.E.A[self.E.B, self.E.B, self.E.A]
		self.assertEqual(testhelpers.cleanXML(tree.render()),
			'<A><B/><B/><A/></A>')

	def testRenderWithText(self):
		E = self.E
		tree = E.A[E.C["arg"], E.C(z="c")[E.B["muss"], E.A]]
		self.assertEqual(tree.render(),
			b'<A xmlns:ns0="http://foo.com" xmlns:ns1="http://bar.com"><ns0:C z="ab">arg</ns0:C>'
				b'<ns0:C z="c"><B>muss</B><A/></ns0:C></A>')

	def testAdditionalPrefixes(self):
		tree = self.E.C[self.E.D["xy"]]
		self.assertEqual(tree.render(includeSchemaLocation=False),
			b'<ns0:C xmlns:foo="http://bori.ng" xmlns:ns0="http://foo.com" z="ab"><ns0:D foo:u="x">xy</ns0:D></ns0:C>')

	def testSchemaLocation(self):
		tree = self.E.D["xy"]
		self.assertEqual(tree.render(),
			b'<ns0:D foo:u="x" xmlns:foo="http://bori.ng" xmlns:ns0="http://'
			b'foo.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
			b'xsi:schemaLocation="http://bori.ng http://schema.is.here">xy</ns0:D>')

	def testEmptyPrefix(self):
		tree = self.E.C["bar"]
		self.assertEqual(tree.render(prefixForEmpty="ns0"),
			b'<C xmlns:ns0="http://foo.com" xmlns="http://foo.com" z="ab">bar</C>')


class IAUDesignationTest(testhelpers.VerboseTest,
		metaclass=testhelpers.SamplesBasedAutoTest):
	def _runTest(self, sample):
		args, expected = sample
		res = utils.makeIAUId(*args)
		self.assertEqual(res, expected)
	
	samples = [
		(("TJ", 0, 0), "TJ000000+000000"),
		(("TJ", 0, 0, 1), "TJ000000.0+000000"),
		(("TJ", 0, 0, 0, 1), "TJ000000+000000.0"),
		(("BB", 34.13333, 23.24722, 1, 0), "BB021631.9+231449"),
		(("BB", 34.13333, -23.24722, 1, 0), "BB021631.9-231449"),
		(("BB", 34.13333, -23.24722, 0, 0), "BB021631-231449"),
		(("BB", 34.13333, -23.24722, 0, 1), "BB021631-231449.9"),
	]


pP = pathlib.Path

class PathOpsTest(testhelpers.VerboseTest):
	def testRelPathBasicStr(self):
		self.assertEqual(
			utils.getRelativePath("/foo/bar/baz", "/foo"),
			"bar/baz")

	def testRelPathBasicPath(self):
		self.assertEqual(
			utils.getRelativePath(
				pP("/foo/bar/baz"), pP("/foo")),
			pP("bar/baz"))

	def testRelPathTrailingSlashStr(self):
		self.assertEqual(
			utils.getRelativePath("/foo/bar/baz", "/foo/"),
			"bar/baz")

	def testRelPathTrailingSlashPath(self):
		self.assertEqual(
			utils.getRelativePath(
				pP("/foo/bar/baz"), pP("/foo/")),
			pP("bar/baz"))

	def testNoRelPathStr(self):
		self.assertRaises(ValueError,
			utils.getRelativePath,
			"/foo/bar/baz", "/bar")

	def testNoRelPathPath(self):
		self.assertRaises(ValueError,
			utils.getRelativePath,
			pP("/foo/bar/baz"), pP("/bar"))

	def testIlliberalChars(self):
		self.assertRaises(ValueError,
			utils.getRelativePath,
			pP("/foo/bar/baz+quux"), pP("/bar"))

	def testLiberalChars(self):
		self.assertRaises(ValueError,
			utils.getRelativePath,
			pP("/foo/bar/baz+quux"), pP("/bar"),
			liberalChars=True)

	def testIdenticalStr(self):
		self.assertEqual(
			utils.getRelativePath(
				"/foo/bar", "/foo/bar"),
			"")

	def testIdenticalPath(self):
		self.assertEqual(
			utils.getRelativePath(
				pP('/home/msdemlei/_gavo_test/inputs'),
				pP('/home/msdemlei/_gavo_test/inputs')),
			pP("."))


if __name__=="__main__":
	testhelpers.main(CachedGetterTest)