Debian Codegraph @

gavo/rscdef/regtest.py

raw
1 """
2 A framework for regression tests within RDs.
3
4 The basic idea is that there's small pieces of python almost-declaratively
5 defining tests for a given piece of data. These things can then be
6 run while (or rather, after) executing dachs val.
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 import functools
16 import argparse
17 import base64
18 import collections
19 import io
20 import pickle as pickle
21 import http.client
22 import os
23 import queue
24 import random
25 import re
26 import sys
27 import time
28 import threading
29 import traceback
30 import unittest
31 import urllib.parse
32
33 try:
34 from urllib3 import filepost as req_filepost
35 from urllib3 import fields as req_fields
36 except ImportError:
37 # we need requests to format multipart uploads since python's email
38 # package is broken for that purpose (formats everything as text).
39 # I don't want to hard-depend on requests, though.
40 # TODO: skip tests that want it rather than crashing them
41 pass
42
43 from lxml import etree as lxtree
44
45 from gavo import base
46 from gavo import votable
47 from gavo import utils
48 from gavo.utils import EqualingRE #noflake: published name
49 from gavo.rscdef import common
50 from gavo.rscdef import procdef
51
52 ################## Utilities
53
54 @functools.lru_cache(1)
55 def _loadCreds():
56 """returns a dictionary of auth keys to user/password pairs from
57 ~/.gavo/test.creds
58 """
59 res = {}
60 try:
61 with open(os.path.join(os.environ["HOME"], ".gavo", "test.creds"),
62 "rb") as f:
63 for ln in f:
64 authKey, user, pw = ln.strip().split()
65 res[authKey.decode("utf-8")] = (user, pw)
66 except IOError:
67 pass
68 return res
69
70
71 def getAuthFor(authKey):
72 """returns a header dictionary to authenticate for authKey.
73
74 authKey is a key into ~/.gavo/test.creds.
75 """
76 try:
77 user, pw = _loadCreds()[authKey]
78 except KeyError:
79 raise base.NotFoundError(authKey, "Authorization info",
80 "~/.gavo/test.creds")
81 return {'Authorization': b"Basic "+(
82 base64.b64encode(b"%s:%s"%(user, pw))).strip()}
83
84
85 def doHTTPRequest(scheme, method, host, path, query,
86 payload, headers, timeout):
87 """creates the HTTP request and retrieves the result.
88 """
89 try:
90 connClass = {
91 "http": http.client.HTTPConnection,
92 "https": http.client.HTTPSConnection}[scheme]
93 except KeyError:
94 raise base.ReportableError(
95 f"Unsupported scheme for regTest URL: {scheme}")
96
97 conn = connClass(host, timeout=timeout)
98 conn.connect()
99 try:
100 if query:
101 path = path+"?"+query
102 conn.request(method, path, payload, headers)
103 resp = conn.getresponse()
104 respHeaders = resp.getheaders()
105 content = resp.read()
106 finally:
107 conn.close()
108 return resp.status, respHeaders, content
109
110
111 def getHeaderValue(headers, key):
112 """returns the value for key in the httplib headers.
113
114 Matching is case-insensitive as required by HTTP. Missing keys
115 raise KeyErrors.
116 """
117 for hKey, hValue in headers:
118 if hKey.lower()==key.lower():
119 return hValue
120 raise KeyError(key)
121
122
123 class Keywords(argparse.Action):
124 """A class encapsulating test selection keywords.
125
126 There's a match method that takes a string and returns true if either
127 no keywords are defined or all keywords are present in other (after
128 case folding).
129
130 This doubles as an argparse action and as such is "self-parsing" if you
131 will.
132 """
133 def __init__(self, *args, **kwargs):
134 argparse.Action.__init__(self, *args, **kwargs)
135 self.keywords = set()
136
137 def __call__(self, parser, namespace, values, option_string=None):
138 self.keywords = self._normalise(values)
139 setattr(namespace, self.dest, self)
140
141 def _normalise(self, s):
142 return set(re.sub(r"[^\w\s]+", "", s).lower().split())
143
144 def match(self, other):
145 if not self.keywords:
146 return True
147
148 return not self.keywords-self._normalise(other)
149
150
151 ################## RD elements
152
153 class DynamicOpenVocAttribute(base.AttributeDef):
154 """an attribute that collects arbitrary attributes in a sequence
155 of pairs.
156
157 The finished sequence is available as a freeAttrs attribute on the
158 embedding instance. No parsing is done, everything is handled as
159 a string.
160
161 Macros in the string are expanded by the first parent that can expand
162 macros. For regtest URLs, that's the regression suite.
163 """
164 typeDesc_ = "any attribute not otherwise used"
165
166 def __init__(self, name, **kwargs):
167 base.AttributeDef.__init__(self, name, **kwargs)
168
169 def feedObject(self, instance, value):
170 expand = utils.identity
171 anc = instance
172 while anc:
173 if hasattr(anc, "expand"):
174 expand = anc.expand
175 break
176 anc = anc.parent
177 value = expand(value)
178
179 if not hasattr(instance, "freeAttrs"):
180 instance.freeAttrs = []
181 instance.freeAttrs.append((self.name_, value))
182
183 def feed(self, ctx, instance, value):
184 self.feedObject(instance, value)
185
186 def getCopy(self, instance, newParent):
187 raise NotImplementedError("This needs some thought")
188
189 def makeUserDoc(self):
190 return "(ignore)"
191
192 def iterParentMethods(self):
193 def getAttribute(self, name):
194 # we need an instance-private attribute dict here:
195 if self.managedAttrs is self.__class__.managedAttrs:
196 self.managedAttrs = self.managedAttrs.copy()
197
198 try:
199 return base.Structure.getAttribute(self, name)
200 except base.StructureError: # no "real" attribute, it's a macro def
201 self.managedAttrs[name] = DynamicOpenVocAttribute(name)
202 # that's a decoy to make Struct.validate see a value for the attribute
203 setattr(self, name, None)
204 return self.managedAttrs[name]
205 yield "getAttribute", getAttribute
206
207
208 class _FormData(object):
209 """a container for multipart/form-data encoded messages.
210
211 This is used for file uploads and depends on requests for that.
212 """
213 def __init__(self):
214 self.fields = []
215
216 def addFile(self, paramName, fileName, data):
217 """attaches the contents of fileName under the http parameter name
218 paramName.
219 """
220 field = req_fields.RequestField(paramName, data, fileName)
221 field.make_multipart(content_type="application/octet-stream")
222 self.fields.append(field)
223
224 def addParam(self, paramName, paramVal):
225 """adds a form parameter paramName with the (string) value paramVal
226 """
227 field = req_fields.RequestField(paramName, paramVal)
228 field.make_multipart(content_type=None)
229 self.fields.append(field)
230
231 def encode(self):
232 """returns the formatted payload for the upload as bytes, and
233 the content-type to use (including the boundary).
234 """
235 return req_filepost.encode_multipart_formdata(self.fields)
236
237
238 class Upload(base.Structure):
239 """An upload going with a URL.
240 """
241 name_ = "httpUpload"
242
243 _src = common.ResdirRelativeAttribute("source",
244 default=base.NotGiven,
245 description="Path to a file containing the data to be uploaded.",
246 copyable=True)
247
248 _name = base.UnicodeAttribute("name",
249 default=base.Undefined,
250 description="Name of the upload parameter",
251 copyable=True)
252
253 _filename = base.UnicodeAttribute("fileName",
254 default="upload.dat",
255 description="Remote file name for the uploaded file.",
256 copyable=True)
257
258 _content = base.DataContent(description="Inline data to be uploaded"
259 " (conflicts with source)")
260
261 @property
262 def rd(self):
263 return self.parent.rd
264
265 def addToForm(self, form):
266 """sets up a _Form instance to upload the data.
267 """
268 if self.content_:
269 data = self.content_.encode("utf-8")
270 else:
271 with open(self.source, "rb") as f:
272 data = f.read()
273 form.addFile(self.name, self.fileName, data)
274
275 def validate(self):
276 if (self.content_ and self.source
277 or not (self.content_ or self.source)):
278 raise base.StructureError("Exactly one of element content and source"
279 " attribute must be given for an upload.")
280
281
282 def _iterInChunks(stuff, chunkSize):
283 """returns a function returning stuff in bits of chunkSize elements (of
284 stuff).
285 """
286 def iterate():
287 offset = 0
288 while True:
289 chunk = stuff[offset:offset+chunkSize]
290 if not chunk:
291 return
292 else:
293 yield chunk
294 offset += chunkSize
295
296 return iterate
297
298
299 class DataURL(base.Structure):
300 """A source document for a regression test.
301
302 As string URLs, they specify where to get data from, but the additionally
303 let you specify uploads, authentication, headers and http methods,
304 while at the same time saving you manual escaping of parameters.
305
306 The bodies is the path to run the test against. This is
307 interpreted as relative to the RD if there's no leading slash,
308 relative to the server if there's a leading slash, and absolute
309 if there's a scheme.
310
311 The attributes are translated to parameters, except for a few
312 pre-defined names. If you actually need those as URL parameters,
313 should at us and we'll provide some way of escaping these.
314
315 We don't actually parse the URLs coming in here. GET parameters
316 are appended with a & if there's a ? in the existing URL, with a ?
317 if not. Again, shout if this is too dumb for you (but urlparse
318 really isn't all that robust either...)
319 """
320 name_ = "url"
321
322 # httpURL will be set to the URL actually used in retrieveResource
323 # Only use this to report the source of the data for, e.g., failing
324 # tests.
325 httpURL = "(not retrieved)"
326
327 _base = base.DataContent(description="Base for URL generation; embedded"
328 " whitespace will be removed, so you're free to break those wherever"
329 " you like.",
330 copyable=True)
331
332 _httpMethod = base.UnicodeAttribute("httpMethod",
333 description="Request method; usually one of GET or POST",
334 default="GET")
335
336 _httpPost = common.ResdirRelativeAttribute("postPayload",
337 default=base.NotGiven,
338 description="Path to a file containing material that should go"
339 " with a POST request (conflicts with additional parameters).",
340 copyable=True)
341
342 _postMediaType = base.UnicodeAttribute("httpPostMediaType",
343 default="application/octet-stream",
344 description="The media type of postPayload (which is also applicable"
345 " to other methods)",
346 copyable=True)
347
348 _parset = base.EnumeratedUnicodeAttribute("parSet",
349 description="Preselect a default parameter set; form gives what"
350 " our framework adds to form queries.", default=base.NotGiven,
351 validValues=["form", "TAP"],
352 copyable=True)
353
354 _httpHeaders = base.DictAttribute("httpHeader",
355 description="Additional HTTP headers to pass.",
356 copyable=True)
357
358 _httpAuthKey = base.UnicodeAttribute("httpAuthKey",
359 description="A key into ~/.gavo/test.creds to find a user/password"
360 " pair for this request.",
361 default=base.NotGiven,
362 copyable=True)
363
364 _httpUploads = base.StructListAttribute("uploads",
365 childFactory=Upload,
366 description='HTTP uploads to add to request (must have httpMethod="POST")',
367 copyable=True)
368
369 _httpHonorRedirects = base.BooleanAttribute("httpHonorRedirects",
370 default=False,
371 description="Follow 30x redirects instead of just using"
372 " status, headers, and payload of the initial request.",
373 copyable=True)
374
375 _httpChunkSize = base.IntAttribute("httpChunkSize",
376 default=None,
377 description="If there are uploads, upload them in chunks of this"
378 " many bytes using chunked encoding.",
379 copyable=True)
380
381 _rd = common.RDAttribute()
382
383 _open = DynamicOpenVocAttribute("open")
384
385 def getValue(self, serverURL):
386 """returns a pair of full request URL and postable payload for this
387 test.
388 """
389 urlBase = re.sub(r"\s+", "", self.content_)
390 if "://" in urlBase:
391 # we believe there's a scheme in there
392 pass
393 elif urlBase.startswith("/"):
394 urlBase = serverURL+urlBase
395 else:
396 urlBase = serverURL+"/"+self.parent.rd.sourceId+"/"+urlBase
397
398 if self.httpMethod=="POST":
399 return urlBase
400 else:
401 return self._addParams(urlBase, urllib.parse.urlencode(self.getParams()))
402
403 def getParams(self):
404 """returns the URL parameters as a sequence of kw, value pairs.
405 """
406 params = getattr(self, "freeAttrs", [])
407
408 if self.parSet=="form":
409 params.extend([("__nevow_form__", "genForm"), ("submit", "Go"),
410 ("_charset_", "UTF-8")])
411
412 elif self.parSet=='TAP':
413 params.extend([("LANG", "ADQL"), ("REQUEST", "doQuery")])
414
415 return params
416
417 def retrieveResource(self, serverURL, timeout):
418 """returns a triple of status, headers, and content for retrieving
419 this URL.
420 """
421 self.httpURL, payload = self.getValue(serverURL), None
422 headers = {
423 "user-agent": "DaCHS regression tester"}
424 headers.update(self.httpHeader)
425
426 if self.httpMethod not in ["HEAD", "GET"]:
427 if self.postPayload:
428 headers["content-type"] = self.httpPostMediaType
429 with open(self.postPayload, "rb") as f:
430 payload = f.read()
431
432 elif self.uploads:
433 form = _FormData()
434 for key, value in self.getParams():
435 form.addParam(key, value)
436 for upload in self.uploads:
437 upload.addToForm(form)
438
439 payload, ct = form.encode()
440 headers["Content-Type"] = ct
441
442 if self.httpChunkSize:
443 payload = _iterInChunks(payload, self.httpChunkSize)()
444
445 else:
446 payload = urllib.parse.urlencode(self.getParams())
447 headers["Content-Type"] = "application/x-www-form-urlencoded"
448
449 scheme, host, path, _, query, _ = urllib.parse.urlparse(str(self.httpURL))
450
451 if self.httpAuthKey is not base.NotGiven:
452 headers.update(getAuthFor(self.httpAuthKey))
453 status, respHeaders, content = doHTTPRequest(
454 scheme, str(self.httpMethod),
455 host, path, query, payload, headers, timeout)
456
457 while self.httpHonorRedirects and status in [301, 302, 303]:
458 scheme, host, path, _, query, _ = urllib.parse.urlparse(
459 getHeaderValue(respHeaders, "location"))
460 status, respHeaders, content = doHTTPRequest(scheme, "GET",
461 host, path, query, None, {}, timeout)
462
463 return status, respHeaders, content
464
465 def _addParams(self, urlBase, params):
466 """a brief hack to add query parameters to GET-style URLs.
467
468 This is a workaround for not trusting urlparse and is fairly easy to
469 fool.
470
471 Params must already be fully encoded.
472 """
473 if not params:
474 return urlBase
475
476 if "?" in urlBase:
477 return urlBase+"&"+params
478 else:
479 return urlBase+"?"+params
480
481 def validate(self):
482 if self.postPayload is not base.NotGiven:
483 if self.getParams():
484 raise base.StructureError("No parameters (or parSets) are"
485 " possible with postPayload")
486 if self.httpMethod in ["GET", "HEAD"]:
487 raise base.StructureError("We don't let you do GET or HEAD"
488 " together with postPayload")
489
490 if self.uploads:
491 if self.httpMethod!="POST":
492 raise base.StructureError("Only POST is allowed as httpMethod"
493 " together with upload")
494
495 super().validate()
496
497
498 class RegTest(procdef.ProcApp, unittest.TestCase):
499 """A regression test.
500
501 Tests are defined through url and code elements. See `Regression Testing`_
502 for more information.
503
504 Most of the external code you will use here is on the test itself,
505 which you see as ``self`` in regTests and has the standard pyunit
506 methods as well as quite a few utility methods (such as
507 ``self.getFirstVOTableRow``) described in the reference documentation.
508
509 Extra names you see in regTest code:
510
511 * EqualingRE -- a class letting you pass in regular expressions into
512 equality tests
513 """
514 name_ = "regTest"
515 requiredType = "regTest"
516 formalArgs = "self"
517 data = b"<No data retrieved yet>"
518 requestTime = None
519
520 runCount = 1
521
522 additionalNamesForProcs = {
523 "EqualingRE": EqualingRE,}
524
525 _title = base.NWUnicodeAttribute("title",
526 default=base.Undefined,
527 description="A short, human-readable phrase describing what this"
528 " test is exercising.")
529
530 _url = base.StructAttribute("url",
531 childFactory=DataURL,
532 default=base.NotGiven,
533 description="The source from which to fetch the test data.")
534
535 _tags = base.StringSetAttribute("tags",
536 description="A list of (free-form) tags for this test. Tagged tests"
537 " are only run when the runner is constructed with at least one"
538 " of the tags given. This is mainly for restricting tags to production"
539 " or development servers.")
540
541 _rd = common.RDAttribute()
542
543 def __init__(self, *args, **kwargs):
544 unittest.TestCase.__init__(self, "fakeForPyUnit")
545 procdef.ProcApp.__init__(self, *args, **kwargs)
546
547 def fakeForPyUnit(self):
548 raise AssertionError("This is not a pyunit test right now")
549
550 @property
551 def description(self):
552 source = ""
553 if self.rd:
554 id = self.rd.sourceId
555 source = " (%s)"%id
556 return self.title+source
557
558 def retrieveData(self, serverURL, timeout):
559 """returns headers and content when retrieving the resource at url.
560
561 Sets the headers and data attributes of the test instance.
562 """
563 startTime = time.time()
564 if self.url is base.NotGiven:
565 self.status, self.headers, self.data = None, None, None
566 else:
567 self.status, self.headers, self.data = self.url.retrieveResource(
568 serverURL, timeout=timeout)
569 self.requestTime = time.time()-startTime
570
571 def getDataSource(self):
572 """returns a string pointing people to where data came from.
573 """
574 if self.url is base.NotGiven:
575 return "(Unconditional)"
576 else:
577 return self.url.httpURL
578
579 def pointNextToLocation(self, addToPath=""):
580 """arranges for the value of the location header to become the
581 base URL of the next test.
582
583 addToPath, if given, is appended to the location header.
584
585 If no location header was provided, the test fails.
586
587 All this of course only works for tests in sequential regSuites.
588 """
589 if not hasattr(self, "followUp"):
590 raise AssertionError("pointNextToLocation only allowed within"
591 " sequential regSuites")
592
593 for key, value in self.headers:
594 if key.lower()=='location':
595 self.followUp.url.content_ = value+addToPath
596 break
597 else:
598 raise AssertionError("No location header in redirect")
599
600 @utils.document
601 def assertHasStrings(self, *strings):
602 """checks that all its arguments are found within content.
603
604 If string arguments are passed, they are utf-8 encoded before
605 comparison. If that's not what you want, pass bytes yourself.
606 """
607 for phrase in strings:
608 assert utils.bytify(phrase) in self.data, "%s missing"%repr(phrase)
609
610 @utils.document
611 def assertLacksStrings(self, *strings):
612 """checks that all its arguments are *not* found within content.
613 """
614 for phrase in strings:
615 assert utils.bytify(phrase) not in self.data, \
616 "Unexpected: '%s'"%repr(phrase)
617
618 @utils.document
619 def assertHTTPStatus(self, expectedStatus):
620 """checks whether the request came back with expectedStatus.
621 """
622 assert expectedStatus==self.status, ("Bad status received, %s instead"
623 " of %s"%(self.status, expectedStatus))
624
625 @utils.document
626 def assertValidatesXSD(self):
627 """checks whether the returned data are XSD valid.
628
629 This uses DaCHS built-in XSD validator with the built-in schema
630 files; it hence will in general not retrieve schema files from
631 external sources.
632 """
633 from gavo.helpers import testtricks
634 msgs = testtricks.getXSDErrors(self.data)
635 if msgs:
636 raise AssertionError("Response not XSD valid. Validator output"
637 " starts with\n%s"%(msgs[:160]))
638
639 XPATH_NAMESPACE_MAP = {
640 "v": "http://www.ivoa.net/xml/VOTable/v1.3",
641 "v2": "http://www.ivoa.net/xml/VOTable/v1.2",
642 "v1": "http://www.ivoa.net/xml/VOTable/v1.1",
643 "o": "http://www.openarchives.org/OAI/2.0/",
644 "h": "http://www.w3.org/1999/xhtml",
645 "m": "http://www.ivoa.net/xml/mivot",
646 }
647
648 @utils.document
649 def assertXpath(self, path, assertions):
650 """checks an xpath assertion.
651
652 path is an xpath (as understood by lxml), with namespace
653 prefixes statically mapped; there's currently v2 (VOTable
654 1.2), v1 (VOTable 1.1), v (whatever VOTable version
655 is the current DaCHS default), h (the namespace of the
656 XHTML elements DaCHS generates), m (the provisional MIVOT namespace)
657 and o (OAI-PMH 2.0).
658
659 If you need more prefixes, hack the source and feed back
660 your changes (or just add to self.XPATH_NAMESPACE_MAP
661 locally).
662
663 path must match exactly one element.
664
665 assertions is a dictionary mapping attribute names to
666 their expected value. Use the key None to check the
667 element content, and match for None if you expect an
668 empty element. To match against a namespaced attribute, you
669 have to give the full URI; prefixes are not applied here.
670 This would look like::
671
672 "{http://www.w3.org/2001/XMLSchema-instance}type": "vg:OAIHTTP"
673
674 If you need an RE match rather than equality, there's
675 EqualingRE in your code's namespace.
676 """
677 if not hasattr(self, "cached parsed tree"):
678 setattr(self, "cached parsed tree", lxtree.fromstring(self.data))
679 tree = getattr(self, "cached parsed tree")
680 res = tree.xpath(path, namespaces=self.XPATH_NAMESPACE_MAP)
681 if len(res)==0:
682 raise AssertionError("Element not found: %s"%path)
683 elif len(res)!=1:
684 raise AssertionError("More than one item matched for %s"%path)
685
686 el = res[0]
687 for key, val in assertions.items():
688 if key is None:
689 try:
690 foundVal = el.text
691 except AttributeError:
692 # assume the expression was for an attribute and just use the
693 # value
694 foundVal = el
695 else:
696 foundVal = el.attrib[key]
697 assert val==foundVal, "Trouble with %s: %s (%s, %s)"%(
698 key or "content", path, repr(val), repr(foundVal))
699
700 @utils.document
701 def getXpath(self, path, element=None):
702 """returns the equivalent of tree.xpath(path) for an lxml etree
703 of the current document or in element, if passed in.
704
705 This uses the same namespace conventions as assertXpath.
706 """
707 if element is None:
708 if not hasattr(self, "_parsedTree"):
709 self._parsedTree = lxtree.fromstring(self.data)
710 element = self._parsedTree
711
712 return element.xpath(path, namespaces=self.XPATH_NAMESPACE_MAP)
713
714 @utils.document
715 def assertHeader(self, key, value):
716 """checks that header key has value in the response headers.
717
718 keys are compared case-insensitively, values are compared literally.
719 """
720 try:
721 foundValue = getHeaderValue(self.headers, key)
722 self.assertEqual(value, foundValue)
723 except KeyError:
724 raise AssertionError("Header %s not found in %s"%(
725 key, self.headers))
726
727 @utils.document
728 def getFirstVOTableRow(self, rejectExtras=True):
729 """interprets data as a VOTable and returns the first row as a dictionary
730
731 It will normally ensure that only one row is returned. To make it
732 silently discard extra rows, make sure the result is sorted, or you will
733 get randomly failing tests. Database-querying cores (which is where order
734 is an issue) also honor _DBOPTIONS_ORDER).
735 """
736 data, metadata = votable.loads(self.data)
737 if metadata is None:
738 raise AssertionError("Response did not contain a TABLE -- is it"
739 " an error message?")
740
741 rows = metadata.iterDicts(data)
742 result = next(rows)
743
744 if rejectExtras:
745 try:
746 secondRow = next(rows)
747 except StopIteration:
748 pass
749 else:
750 raise AssertionError(
751 f"getFirstVOTableRow swallows a row: {secondRow}")
752
753 return result
754
755 @utils.document
756 def getVOTableRows(self):
757 """parses the first table in a result VOTable and returns the contents
758 as a sequence of dictionaries.
759 """
760 data, metadata = votable.loads(self.data)
761 if metadata is None:
762 raise AssertionError("Response did not contain a TABLE -- is it"
763 " an error message?")
764 return list(metadata.iterDicts(data))
765
766 @utils.document
767 def getUnique(self, seq):
768 """returns seq[0], asserting at the same time that len(seq) is 1.
769
770 The idea is that you can say row = self.getUnique(self.getVOTableRows())
771 and have a nice test on the side -- and no ugly IndexError on an
772 empty resposne.
773 """
774 self.assertEqual(len(seq), 1)
775 return seq[0]
776
777 @utils.document
778 def datalinkBySemantics(self):
779 """returns a mapping of semantics -> datalink row for a datalink
780 table.
781 """
782 bySemantics = {}
783 for r in self.getVOTableRows():
784 bySemantics.setdefault(r["semantics"], []).append(r)
785 return bySemantics
786
787
788 class RegTestSuite(base.Structure):
789 """A suite of regression tests.
790 """
791 name_ = "regSuite"
792
793 _tests = base.StructListAttribute("tests",
794 childFactory=RegTest,
795 description="Tests making up this suite",
796 copyable=False)
797
798 _title = base.NWUnicodeAttribute("title",
799 description="A short, human-readable phrase describing what this"
800 " suite is about.")
801
802 _sequential = base.BooleanAttribute("sequential",
803 description="Set to true if the individual tests need to be run"
804 " in sequence.",
805 default=False)
806
807 def itertests(self, tags, keywords):
808 for test in self.tests:
809 if test.tags and not test.tags&tags:
810 continue
811 if keywords and not keywords.match(test.title):
812 continue
813 yield test
814
815 def completeElement(self, ctx):
816 if self.title is None:
817 self.title = "Test suite from %s"%self.parent.sourceId
818 super().completeElement(ctx)
819
820 def expand(self, *args, **kwargs):
821 """hand macro expansion to the RD.
822 """
823 return self.parent.expand(*args, **kwargs)
824
825
826 #################### Running Tests
827
828 class TestStatistics(object):
829 """A statistics gatherer/reporter for the regression tests.
830 """
831 def __init__(self, verbose=True):
832 self.verbose = False
833 self.runs = []
834 self.oks, self.fails, self.total = 0, 0, 0
835 self.globalStart = time.time()
836 self.lastTimestamp = time.time()+1
837 self.timeSum = 0
838
839 def add(self, status, runTime, title, payload, srcRD):
840 """adds a test result to the statistics.
841
842 status is either OK, FAIL, or ERROR, runTime is the time
843 spent in running the test, title is the test's title,
844 and payload is "something" associated with failures that
845 should help diagnosing them.
846 """
847 if status=="OK":
848 self.oks += 1
849 else:
850 if self.verbose:
851 print(">>>>>>>>", status)
852 self.fails += 1
853 self.total += 1
854 self.timeSum += runTime
855 #XXX TODO: Payload can use a lot of memory -- I'm nuking it for now
856 # -- maybe use an on-disk database to store this and allow later debugging?
857 self.runs.append((runTime, status, title,
858 None, #str(payload),
859 srcRD))
860 self.lastTimestamp = time.time()
861
862 def getReport(self):
863 """returns a string representation of a short report on how the tests
864 fared.
865 """
866 try:
867 return ("%d of %d bad. avg %.2f, min %.2f, max %.2f. %.1f/s, par %.1f"
868 )%(self.fails, self.fails+self.oks, self.timeSum/len(self.runs),
869 min(self.runs)[0], max(self.runs)[0], float(self.total)/(
870 self.lastTimestamp-self.globalStart),
871 self.timeSum/(self.lastTimestamp-self.globalStart))
872 except ZeroDivisionError:
873 return "No tests run (probably did not find any)."
874
875 def getFailures(self):
876 """returns a string containing some moderately verbose info on the
877 failures collected.
878 """
879 failures = {}
880 for runTime, status, title, payload, srcRD in self.runs:
881 if status!="OK":
882 failures.setdefault(srcRD, []).append("%s %s"%(status, title))
883
884 return "\n".join("From %s:\n %s\n\n"%(srcRD,
885 "\n ".join(badTests))
886 for srcRD, badTests in failures.items())
887
888 def save(self, target):
889 """saves the entire test statistics to target.
890
891 This is a pickle of basically what's added with add. No tools
892 for doing something with this are provided so far.
893 """
894 with open(target, "wb") as f:
895 pickle.dump(self.runs, f)
896
897
898 class TestRunner(object):
899 """A runner for regression tests.
900
901 It is constructed with a sequence of suites (RegTestSuite instances)
902 and allows running these in parallel. It honors the suites' wishes
903 as to being executed sequentially.
904 """
905
906 # The real trick here are the test suites with state (sequential=True). For
907 # those, the individual tests must be serialized, which happens using the magic
908 # followUp attribute on the tests.
909
910 def __init__(self, suites, serverURL=None,
911 verbose=True, dumpNegative=False, tags=None,
912 timeout=45, failFile=None, nRepeat=1,
913 execDelay=0, nThreads=8, printTitles=False,
914 keywords=None):
915 self.verbose, self.dumpNegative = verbose, dumpNegative
916 self.failFile, self.nRepeat = failFile, nRepeat
917 self.printTitles = printTitles
918 if tags:
919 self.tags = tags
920 else:
921 self.tags = frozenset()
922 self.timeout = timeout
923 self.execDelay = execDelay
924 self.nThreads = nThreads
925 self.keywords = keywords
926
927 self.serverURL = serverURL or base.getConfig("web", "serverurl")
928 self.curRunning = {}
929 self.threadId = 0
930 self._makeTestList(suites)
931 self.stats = TestStatistics(verbose=self.verbose)
932 self.resultsQueue = queue.Queue()
933
934 @classmethod
935 def fromRD(cls, rd, **kwargs):
936 """constructs a TestRunner for a single ResourceDescriptor.
937 """
938 return cls(rd.tests, **kwargs)
939
940 @classmethod
941 def fromSuite(cls, suite, **kwargs):
942 """constructs a TestRunner for a RegTestSuite suite
943 """
944 return cls([suite], **kwargs)
945
946 @classmethod
947 def fromTest(cls, test, **kwargs):
948 """constructs a TestRunner for a single RegTest
949 """
950 return cls([base.makeStruct(RegTestSuite, tests=[test],
951 parent_=test.parent.parent)],
952 **kwargs)
953
954 def _makeTestList(self, suites):
955 """puts all individual tests from all test suites in a deque.
956 """
957 self.testList = collections.deque()
958 for suite in suites:
959 if suite.sequential:
960 self._makeTestsWithState(suite)
961 else:
962 self.testList.extend(suite.itertests(self.tags, self.keywords))
963
964 def _makeTestsWithState(self, suite):
965 """helps _makeTestList by putting suite's test in a way that they are
966 executed sequentially.
967 """
968 # technically, this is done by just entering the suite's "head"
969 # and have that pull all the other tests in the suite behind it.
970 tests = list(suite.itertests(self.tags, self.keywords))
971 if tests:
972 firstTest = tests.pop(0)
973 self.testList.append(firstTest)
974 for test in tests:
975 firstTest.followUp = test
976 firstTest = test
977
978 def _spawnThread(self):
979 """starts a new test in a thread of its own.
980 """
981 test = self.testList.popleft()
982 if self.printTitles:
983 sys.stderr.write(" <%s> "%test.title)
984 sys.stderr.flush()
985
986 newThread = threading.Thread(target=self.runOneTest,
987 args=(test, self.threadId, self.execDelay))
988 newThread.description = test.description
989 newThread.setDaemon(True)
990 self.curRunning[self.threadId] = newThread
991 self.threadId += 1
992 newThread.start()
993
994 if test.runCount<self.nRepeat:
995 test.runCount += 1
996 self.testList.append(test)
997
998 def runOneTest(self, test, threadId, execDelay):
999 """runs test and puts the results in the result queue.
1000
1001 This is usually run in a thread. However, threadId is only
1002 used for reporting, so you may run this without threads.
1003
1004 To support sequential execution, if test has a followUp attribute,
1005 this followUp is queued after the test has run.
1006
1007 If the execDelay argument is non-zero, the thread delays its execution
1008 by that many seconds.
1009 """
1010 if execDelay:
1011 time.sleep(execDelay)
1012 startTime = time.time()
1013 try:
1014 try:
1015 test.retrieveData(self.serverURL, timeout=self.timeout)
1016 test.compile()(test)
1017 self.resultsQueue.put(("OK", test, None, None, time.time()-startTime))
1018
1019 except KeyboardInterrupt:
1020 raise
1021
1022 except AssertionError as ex:
1023 self.resultsQueue.put(("FAIL", test, ex, None,
1024 time.time()-startTime))
1025 # races be damned
1026 if self.dumpNegative:
1027 print("Content of failing test:\n%s\n"%test.data)
1028 if self.failFile:
1029 with open(self.failFile, "wb") as f:
1030 f.write(test.data)
1031
1032 except Exception as ex:
1033 if self.failFile and getattr(test, "data", None) is not None:
1034 with open(self.failFile, "wb") as f:
1035 f.write(test.data)
1036
1037 f = io.StringIO()
1038 traceback.print_exc(file=f)
1039 self.resultsQueue.put(("ERROR", test, ex, f.getvalue(),
1040 time.time()-startTime))
1041
1042 finally:
1043 if hasattr(test, "followUp"):
1044 self.resultsQueue.put(("addTest", test.followUp, None, None, 0))
1045
1046 if threadId is not None:
1047 self.resultsQueue.put(("collectThread", threadId, None, None, 0))
1048
1049 def _printStat(self, state, test, payload, traceback):
1050 """gives feedback to the user about the result of a test.
1051 """
1052 if not self.verbose:
1053 return
1054 if state=="FAIL":
1055 print("**** Test failed: %s -- %s\n"%(
1056 test.title, test.getDataSource()))
1057 print(">>>>", payload)
1058 elif state=="ERROR":
1059 print("**** Internal Failure: %s -- %s\n"%(test.title,
1060 test.url.httpURL))
1061 print(traceback)
1062
1063 def _runTestsReal(self, showDots=False):
1064 """executes the tests, taking tests off the queue and spawning
1065 threads until the queue is empty.
1066
1067 showDots, if True, instructs the runner to push one dot to stderr
1068 per test spawned.
1069 """
1070 while self.testList or self.curRunning:
1071 while len(self.curRunning)<self.nThreads and self.testList:
1072 self._spawnThread()
1073
1074 evType, test, payload, traceback, dt = self.resultsQueue.get(
1075 timeout=self.timeout)
1076 if evType=="addTest":
1077 self.testList.appendleft(test)
1078 elif evType=="collectThread":
1079 deadThread = self.curRunning.pop(test)
1080 deadThread.join()
1081 else:
1082 self.stats.add(evType, dt, test.title, "", test.rd.sourceId)
1083 if showDots:
1084 if evType=="OK":
1085 sys.stderr.write(".")
1086 else:
1087 sys.stderr.write("E")
1088 sys.stderr.flush()
1089 self._printStat(evType, test, payload, traceback)
1090
1091 if showDots:
1092 sys.stderr.write("\n")
1093
1094 def runTests(self, showDots=False):
1095 """executes the tests in a random order and in parallel.
1096 """
1097 random.shuffle(self.testList)
1098 try:
1099 self._runTestsReal(showDots=showDots)
1100 except queue.Empty:
1101 sys.stderr.write("******** Hung jobs\nCurrently executing:\n")
1102 for thread in list(self.curRunning.values()):
1103 sys.stderr.write("%s\n"%thread.description)
1104
1105 def runTestsInOrder(self):
1106 """runs all tests sequentially and in the order they were added.
1107 """
1108 for test in self.testList:
1109 self.runOneTest(test, None, self.execDelay)
1110 try:
1111 while True:
1112 evType, test, payload, traceback, dt = self.resultsQueue.get(False)
1113 if evType=="addTest":
1114 self.testList.appendleft(test)
1115 else:
1116 self.stats.add(evType, dt, test.title, "", test.rd.sourceId)
1117 self._printStat(evType, test, payload, traceback)
1118 except queue.Empty:
1119 pass
1120
1121
1122 ################### command line interface
1123
1124
1125 def urlToURL():
1126 """converts HTTP (GET) URLs to URL elements.
1127 """
1128 # This is what's invoked by the makeTestURLs command.
1129 while True:
1130 parts = urllib.parse.urlparse(input())
1131 print("<url %s>%s</url>"%(
1132 " ".join('%s="%s"'%(k,v[0])
1133 for k,v in urllib.parse.parse_qs(parts.query).items()),
1134 parts.path))
1135
1136
1137 def _getRunnerForAll(runnerArgs, showProgress):
1138 from gavo.registry import publication
1139 from gavo import api
1140
1141 suites = []
1142 for rdId in publication.findAllRDs():
1143 if showProgress:
1144 sys.stdout.write(rdId+" ")
1145 sys.stdout.flush()
1146
1147 try:
1148 rd = api.getRD(rdId, doQueries=False)
1149 except Exception as msg:
1150 base.ui.notifyError("Error loading RD %s (%s). Ignoring."%(
1151 rdId, utils.safe_str(msg)))
1152 suites.extend(rd.tests)
1153
1154 return TestRunner(suites, **runnerArgs)
1155
1156
1157 def _getRunnerForSingle(testId, runnerArgs):
1158 from gavo import api
1159
1160 testElement = common.getReferencedElement(testId, doQueries=False)
1161
1162 if isinstance(testElement, api.RD):
1163 runner = TestRunner.fromRD(testElement, **runnerArgs)
1164 elif isinstance(testElement, RegTestSuite):
1165 runner = TestRunner.fromSuite(testElement, **runnerArgs)
1166 elif isinstance(testElement, RegTest):
1167 runner = TestRunner.fromTest(testElement, **runnerArgs)
1168 else:
1169 raise base.ReportableError("%s is not a testable element."%testId,
1170 hint="Only RDs, regSuites, or regTests are eligible for testing.")
1171 return runner
1172
1173
1174 def parseCommandLine(args=None):
1175 """parses the command line for main()
1176 """
1177 parser = argparse.ArgumentParser(description="Run tests embedded in RDs")
1178 parser.add_argument("id", type=str,
1179 help="RD id or cross-RD identifier for a testable thing.")
1180 parser.add_argument("-v", "--verbose", help="Dump info on failed test",
1181 action="store_true", dest="verbose")
1182 parser.add_argument("-V", "--titles", help="Write title when starting"
1183 " a test.",
1184 action="store_true", dest="printTitles")
1185 parser.add_argument("-d", "--dump-negative", help="Dump the content of"
1186 " failing tests to stdout",
1187 action="store_true", dest="dumpNegative")
1188 parser.add_argument("-t", "--tag", help="Also run tests tagged with TAG.",
1189 action="store", dest="tag", default=None, metavar="TAG")
1190 parser.add_argument("-R", "--n-repeat", help="Run each test N times",
1191 action="store", dest="nRepeat", type=int, default=1, metavar="N")
1192 parser.add_argument("-T", "--timeout", help="Abort and fail requests"
1193 " after inactivity of SECONDS",
1194 action="store", dest="timeout", type=int, default=15, metavar="SECONDS")
1195 parser.add_argument("-D", "--dump-to", help="Dump the content of"
1196 " last failing test to FILE", metavar="FILE",
1197 action="store", type=str, dest="failFile",
1198 default=None)
1199 parser.add_argument("-w", "--wait", help="Wait SECONDS before executing"
1200 " a request", metavar="SECONDS", action="store",
1201 dest="execDelay", type=int, default=0)
1202 parser.add_argument("-u", "--serverURL", help="URL of the DaCHS root"
1203 " at the server to test",
1204 action="store", type=str, dest="serverURL",
1205 default=base.getConfig("web", "serverURL"))
1206 parser.add_argument("-n", "--number-par", help="Number of requests"
1207 " to be run in parallel",
1208 action="store", type=int, dest="nThreads",
1209 default=8)
1210 parser.add_argument("--seed", help="Seed the RNG with this number."
1211 " Note that this doesn't necessarily make the execution sequence"
1212 " predictable, just the submission sequence.",
1213 action="store", type=int, dest="randomSeed", default=None)
1214 parser.add_argument("-k", "--keywords", help="Only run tests"
1215 " with descriptions containing all (whitespace-separated) keywords."
1216 " Sequential tests will be run in full, nevertheless, if their head test"
1217 " matches.",
1218 action=Keywords, type=str, dest="keywords")
1219 parser.add_argument("-p", "--progress", help="Show progress when"
1220 " parsing RDs.",
1221 action="store_true", dest="showProgress")
1222
1223 return parser.parse_args(args)
1224
1225
1226 def main(args=None):
1227 """user interaction for gavo test.
1228 """
1229 tags = None
1230 args = parseCommandLine(args)
1231 if args.randomSeed:
1232 random.seed(args.randomSeed)
1233 if args.tag:
1234 tags = set([args.tag])
1235 if args.serverURL:
1236 args.serverURL = args.serverURL.rstrip("/")
1237
1238 runnerArgs = {
1239 "verbose": args.verbose,
1240 "dumpNegative": args.dumpNegative,
1241 "serverURL": args.serverURL,
1242 "tags": tags,
1243 "failFile": args.failFile,
1244 "nRepeat": args.nRepeat,
1245 "timeout": args.timeout,
1246 "execDelay": args.execDelay,
1247 "nThreads": args.nThreads,
1248 "printTitles": args.printTitles,
1249 "keywords": args.keywords,
1250 }
1251
1252 if args.id=="ALL":
1253 runner = _getRunnerForAll(runnerArgs, args.showProgress)
1254 else:
1255 runner = _getRunnerForSingle(args.id, runnerArgs)
1256
1257 runner.runTests(showDots=True)
1258 print(runner.stats.getReport())
1259 if runner.stats.fails:
1260 print(runner.stats.getFailures())
1261 sys.exit(1)