| 1 |
""" |
| 2 |
Helper functions and classes for unit tests and similar. |
| 3 |
|
| 4 |
Whatever is useful to unit tests from here should be imported into |
| 5 |
testhelpers, too. Unit test modules should not be forced to import |
| 6 |
this. |
| 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 contextlib |
| 16 |
import gzip |
| 17 |
import os |
| 18 |
import re |
| 19 |
import tempfile |
| 20 |
|
| 21 |
from lxml import etree |
| 22 |
|
| 23 |
from gavo import base |
| 24 |
from gavo import utils |
| 25 |
from gavo.formal.testing import ( #noflake: exported names |
| 26 |
FakeRequest, assertHasStrings) |
| 27 |
from gavo.utils import stanxml |
| 28 |
|
| 29 |
|
| 30 |
def _nukeNamespaces(xmlString): |
| 31 |
"""removes namespace declarations from xmlString (which must be bytes). |
| 32 |
|
| 33 |
This is for writing more compact tests and should of course not be |
| 34 |
used outside of tests; in particular, you could easily fool the |
| 35 |
mechanism to wreck your XML. |
| 36 |
|
| 37 |
This always returns bytes. |
| 38 |
""" |
| 39 |
nsCleaner = re.compile(rb'^(</?)(?:[a-z0-9]+:)') |
| 40 |
return re.sub(b"(?s)<[^>]*>", |
| 41 |
lambda mat: nsCleaner.sub(rb"\1", mat.group()), |
| 42 |
re.sub(b'xmlns="[^"]*"', b"", xmlString)) |
| 43 |
|
| 44 |
|
| 45 |
def pickSingle(seq): |
| 46 |
"""gets the first item for a 1-item sequence and raises an AssertionError |
| 47 |
if there's more. |
| 48 |
""" |
| 49 |
if len(seq)!=1: |
| 50 |
raise AssertionError(f"!= one item in {seq}") |
| 51 |
return seq[0] |
| 52 |
|
| 53 |
|
| 54 |
class _WrappedEtree: |
| 55 |
"""a wrapper adding a few methods to an lxml etree. |
| 56 |
|
| 57 |
This is done as a wrapper because you can't monkeypatch _Element. |
| 58 |
|
| 59 |
See getXMLTree for what this about; it's essentially an implementation |
| 60 |
detail of that function. |
| 61 |
""" |
| 62 |
def __init__(self, tree): |
| 63 |
self._tree = tree |
| 64 |
|
| 65 |
def __getattr__(self, name): |
| 66 |
return getattr(self._tree, name) |
| 67 |
|
| 68 |
def __getitem__(self, index): |
| 69 |
return self._tree[index] |
| 70 |
|
| 71 |
def uniqueXpath(self, path): |
| 72 |
res = self.xpath(path) |
| 73 |
assert len(res)==1, "Xpath %s gave %d matches"%(path, len(res)) |
| 74 |
return res[0] |
| 75 |
|
| 76 |
def getById(self, id): |
| 77 |
return self.uniqueXpath("//*[@id='%s']"%id) |
| 78 |
|
| 79 |
def getByID(self, id): |
| 80 |
return self.uniqueXpath("//*[@ID='%s']"%id) |
| 81 |
|
| 82 |
def asString(self): |
| 83 |
return etree.tostring(self._tree).decode("utf-8") |
| 84 |
|
| 85 |
|
| 86 |
def getXMLTree(xmlString, debug=False): |
| 87 |
"""returns an ``libxml2`` etree-like object for ``xmlString``, where, |
| 88 |
for convenience, all namespaces on elements are nuked. |
| 89 |
|
| 90 |
This will only accept strings. |
| 91 |
|
| 92 |
The libxml2 etree lets you do xpath searching using the ``xpath`` method. |
| 93 |
|
| 94 |
Nuking namespaces is of course not a good idea in general, so you |
| 95 |
might want to think again before you use this in production code. |
| 96 |
|
| 97 |
To facilitate writing tests, in addition to lxml.etree methods the returned |
| 98 |
object also has the following methods: |
| 99 |
|
| 100 |
* uniqueXpath(xpath), returning a single match if it's there |
| 101 |
and raises an assertion error otherwise. |
| 102 |
* getById(id), returning the unique element with id and raising an |
| 103 |
assertion error if that doesn't exist. |
| 104 |
* getByID(id), as getById, by for VOTable-style ID. |
| 105 |
* asString(), returning a string representation of the tree |
| 106 |
""" |
| 107 |
tree = etree.fromstring(_nukeNamespaces(xmlString)) |
| 108 |
|
| 109 |
if debug: |
| 110 |
etree.dump(tree) |
| 111 |
return _WrappedEtree(tree) |
| 112 |
|
| 113 |
|
| 114 |
class XSDResolver(etree.Resolver): |
| 115 |
"""A resolver for external entities only returning in-tree files. |
| 116 |
""" |
| 117 |
def __init__(self): |
| 118 |
self.basePath = "schemata" |
| 119 |
|
| 120 |
def getPathForName(self, name): |
| 121 |
xsdName = name.split("/")[-1] |
| 122 |
return base.getPathForDistFile( |
| 123 |
os.path.join(self.basePath, xsdName)) |
| 124 |
|
| 125 |
def resolve(self, url, pubid, context): |
| 126 |
try: |
| 127 |
# resolve namespace URIs, too |
| 128 |
try: |
| 129 |
url = stanxml.NSRegistry.getSchemaForNS(url) |
| 130 |
except base.NotFoundError: |
| 131 |
# it's not a (known) namespace URI, try on |
| 132 |
pass |
| 133 |
|
| 134 |
path = self.getPathForName(url) |
| 135 |
res = self.resolve_filename(path, context) |
| 136 |
if res is not None: |
| 137 |
return res |
| 138 |
except: |
| 139 |
pass # fall through to error message |
| 140 |
base.ui.notifyError("Did not find local file for schema %s --" |
| 141 |
" this will fall back to network resources and thus probably" |
| 142 |
" be slow"%url) |
| 143 |
|
| 144 |
|
| 145 |
RESOLVER = XSDResolver() |
| 146 |
XSD_PARSER = etree.XMLParser() |
| 147 |
XSD_PARSER.resolvers.add(RESOLVER) |
| 148 |
|
| 149 |
|
| 150 |
@contextlib.contextmanager |
| 151 |
def MyParser(): |
| 152 |
if etree.get_default_parser is XSD_PARSER: |
| 153 |
yield |
| 154 |
else: |
| 155 |
etree.set_default_parser(XSD_PARSER) |
| 156 |
try: |
| 157 |
yield |
| 158 |
finally: |
| 159 |
etree.set_default_parser() |
| 160 |
|
| 161 |
class QNamer(object): |
| 162 |
"""A hack that generates QNames through getattr. |
| 163 |
|
| 164 |
Construct with the desired namespace. |
| 165 |
""" |
| 166 |
def __init__(self, ns): |
| 167 |
self.ns = ns |
| 168 |
|
| 169 |
def __getattr__(self, name): |
| 170 |
return etree.QName(self.ns, name.strip("_")) |
| 171 |
|
| 172 |
XS = QNamer("http://www.w3.org/2001/XMLSchema") |
| 173 |
|
| 174 |
|
| 175 |
VO_SCHEMATA = [ |
| 176 |
"Characterisation.xsd", |
| 177 |
"Colstats.xsd", # remove once it's in VODataService |
| 178 |
"ConeSearch.xsd", |
| 179 |
"DaCHS.xsd", |
| 180 |
"DataModel.xsd", |
| 181 |
"DocRegExt.xsd", |
| 182 |
"eudat-core.xsd", |
| 183 |
"oai_dc.xsd", |
| 184 |
"OAI-PMH.xsd", |
| 185 |
"RegistryInterface.xsd", |
| 186 |
"SIA.xsd", |
| 187 |
"SLAP.xsd", |
| 188 |
"SSA.xsd", |
| 189 |
"StandardsRegExt.xsd", |
| 190 |
"stc.xsd", |
| 191 |
"stc-v1.20.xsd", |
| 192 |
"coords-v1.20.xsd", |
| 193 |
"region-v1.20.xsd", |
| 194 |
"TAPRegExt.xsd", |
| 195 |
"UWS.xsd", |
| 196 |
"VODataService.xsd", |
| 197 |
"VOEvent.xsd", |
| 198 |
"VOEventRegExt.xsd", |
| 199 |
"VORegistry.xsd", |
| 200 |
"VOResource.xsd", |
| 201 |
"VOSIAvailability.xsd", |
| 202 |
"VOSICapabilities.xsd", |
| 203 |
"VOSITables.xsd", |
| 204 |
"VOTable-1.1.xsd", |
| 205 |
"VOTable-1.2.xsd", |
| 206 |
"VOTable.xsd", |
| 207 |
"mivot.xsd", |
| 208 |
"vo-dml.xsd", |
| 209 |
"xlink.xsd", |
| 210 |
"XMLSchema.xsd", |
| 211 |
"xml.xsd",] |
| 212 |
|
| 213 |
|
| 214 |
def getJointValidator(schemaPaths): |
| 215 |
"""returns an lxml validator containing the schemas in schemaPaths. |
| 216 |
|
| 217 |
schemaPaths must be actual file paths, absolute or |
| 218 |
trunk/schema-relative. |
| 219 |
""" |
| 220 |
with MyParser(): |
| 221 |
subordinates = [] |
| 222 |
for fName in schemaPaths: |
| 223 |
fPath = RESOLVER.getPathForName(fName) |
| 224 |
root = etree.parse(fPath).getroot() |
| 225 |
subordinates.append(( |
| 226 |
"http://vo.ari.uni-heidelberg.de/docs/schemata/"+fName, |
| 227 |
root.get("targetNamespace"))) |
| 228 |
|
| 229 |
root = etree.Element( |
| 230 |
XS.schema, attrib={"targetNamespace": "urn:combiner"}) |
| 231 |
for schemaLocation, tns in subordinates: |
| 232 |
etree.SubElement(root, XS.import_, attrib={ |
| 233 |
"namespace": tns, "schemaLocation": schemaLocation}) |
| 234 |
|
| 235 |
doc = etree.ElementTree(root) |
| 236 |
return etree.XMLSchema(doc) |
| 237 |
|
| 238 |
|
| 239 |
def getDefaultValidator(extraSchemata=[]): |
| 240 |
"""returns a validator that knows the schemata typically useful within |
| 241 |
the VO. |
| 242 |
|
| 243 |
This will currently only work if DaCHS is installed from an SVN |
| 244 |
checkout with setup.py develop. |
| 245 |
|
| 246 |
What's returned has a method assertValid(et) that raises an exception |
| 247 |
if the elementtree et is not valid. You can simply call it to |
| 248 |
get back True for valid and False for invalid. |
| 249 |
""" |
| 250 |
return getJointValidator(VO_SCHEMATA+extraSchemata) |
| 251 |
|
| 252 |
|
| 253 |
def _makeLXMLValidator(): |
| 254 |
"""returns an lxml-based schema validating function for the VO XSDs |
| 255 |
|
| 256 |
This is not happening at import time as it is time-consuming, and the |
| 257 |
DaCHS server probably doesn't even validate anything. |
| 258 |
|
| 259 |
This is used below to build getXSDErrorsLXML. |
| 260 |
""" |
| 261 |
VALIDATOR = getDefaultValidator() |
| 262 |
|
| 263 |
def getErrors(data, leaveOffending=False): |
| 264 |
"""returns error messages for the XSD validation of the string in data. |
| 265 |
""" |
| 266 |
try: |
| 267 |
with MyParser(): |
| 268 |
if hasattr(data, "xpath"): |
| 269 |
# we believe it's already parsed stuff |
| 270 |
tree = data |
| 271 |
else: |
| 272 |
tree = etree.fromstring(data) |
| 273 |
|
| 274 |
if VALIDATOR.validate(tree): |
| 275 |
return None |
| 276 |
else: |
| 277 |
if leaveOffending: |
| 278 |
if hasattr(data, "xpath"): |
| 279 |
data = etree.tostring(data, encoding="utf-8") |
| 280 |
with open("badDocument.xml", "wb") as of: |
| 281 |
of.write(data) |
| 282 |
return str(VALIDATOR.error_log) |
| 283 |
except Exception as msg: |
| 284 |
return str(msg) |
| 285 |
|
| 286 |
return getErrors |
| 287 |
|
| 288 |
|
| 289 |
def getXSDErrorsLXML(data, leaveOffending=False): |
| 290 |
"""returns error messages for the XSD validation of the string in data. |
| 291 |
""" |
| 292 |
if not hasattr(getXSDErrorsLXML, "validate"): |
| 293 |
getXSDErrorsLXML.validate = _makeLXMLValidator() |
| 294 |
return getXSDErrorsLXML.validate(data, leaveOffending) |
| 295 |
|
| 296 |
|
| 297 |
getXSDErrors = getXSDErrorsLXML |
| 298 |
|
| 299 |
|
| 300 |
class XSDTestMixin(object): |
| 301 |
"""provides a assertValidates method doing XSD validation. |
| 302 |
|
| 303 |
assertValidates raises an assertion error with the validator's |
| 304 |
messages on an error. You can optionally pass a leaveOffending |
| 305 |
argument to make the method store the offending document in |
| 306 |
badDocument.xml. |
| 307 |
""" |
| 308 |
def assertValidates(self, xmlSource, leaveOffending=False): |
| 309 |
messages = getXSDErrors(xmlSource, leaveOffending) |
| 310 |
if messages: |
| 311 |
raise AssertionError(messages) |
| 312 |
|
| 313 |
def assertWellformed(self, xmlSource): |
| 314 |
try: |
| 315 |
etree.fromstring(xmlSource) |
| 316 |
except Exception as msg: |
| 317 |
raise AssertionError("XML not well-formed (%s)"%msg) |
| 318 |
|
| 319 |
|
| 320 |
def getMemDiffer(ofClass=base.Structure): |
| 321 |
"""returns a function to call that returns a list of new DaCHS structures |
| 322 |
since this was called. |
| 323 |
|
| 324 |
If you watch everything, things get hairy because of course the state |
| 325 |
of this function (for instance) also creates references. Hence, pass |
| 326 |
ofClass to choose what the function will track. |
| 327 |
|
| 328 |
This will call a gc.collect itself (and wouldn't make sense without that) |
| 329 |
""" |
| 330 |
import gc |
| 331 |
gc.collect() |
| 332 |
seen_ids = set() |
| 333 |
for ob in gc.get_objects(): |
| 334 |
try: |
| 335 |
if isinstance(ob, ofClass): |
| 336 |
seen_ids.add(id(ob)) |
| 337 |
except ReferenceError: |
| 338 |
# object is already essentially gone, don't worry about it. |
| 339 |
pass |
| 340 |
del ob |
| 341 |
|
| 342 |
def getNewObjects(): |
| 343 |
gc.collect() |
| 344 |
newObjects = [] |
| 345 |
for ob in gc.get_objects(): |
| 346 |
try: |
| 347 |
if id(ob) not in seen_ids and isinstance(ob, ofClass): |
| 348 |
newObjects.append(ob) |
| 349 |
except ReferenceError: |
| 350 |
# again, don't worry about disappearing objects |
| 351 |
pass |
| 352 |
|
| 353 |
return newObjects |
| 354 |
|
| 355 |
return getNewObjects |
| 356 |
|
| 357 |
|
| 358 |
def getUnreferenced(items): |
| 359 |
"""returns a list of elements in items that do not have a reference |
| 360 |
from any other in items. |
| 361 |
""" |
| 362 |
import gc |
| 363 |
itemids = set(id(i) for i in items) |
| 364 |
unreferenced = [] |
| 365 |
for i in items: |
| 366 |
intrefs = set(id(r) for r in gc.get_referrers(i)) & itemids |
| 367 |
if not intrefs: |
| 368 |
unreferenced.append(i) |
| 369 |
return unreferenced |
| 370 |
|
| 371 |
|
| 372 |
def debugReferenceChain(ob): |
| 373 |
"""a sort-of-interactive way to investigate where ob is referenced. |
| 374 |
|
| 375 |
* d -- enter pdb (look at ob, perhaps at nob) |
| 376 |
* u -- follow |
| 377 |
* x -- continue execution |
| 378 |
""" |
| 379 |
import gc |
| 380 |
while True: |
| 381 |
print("Current object: ", repr(ob)) |
| 382 |
refs = gc.get_referrers(ob) |
| 383 |
if not refs: |
| 384 |
print("Not referenced -- exiting") |
| 385 |
break |
| 386 |
|
| 387 |
while refs: |
| 388 |
nob = refs.pop() |
| 389 |
print(len(refs), utils.makeEllipsis(repr(nob))) |
| 390 |
res = input("?") |
| 391 |
|
| 392 |
if res=="d": |
| 393 |
import pdb;pdb.Pdb(nosigint=True).set_trace() |
| 394 |
|
| 395 |
elif res=="x": |
| 396 |
return |
| 397 |
|
| 398 |
elif res=="u": |
| 399 |
ob = nob |
| 400 |
break |
| 401 |
|
| 402 |
elif res=="?": |
| 403 |
print("d, x, u, <empty>") |
| 404 |
|
| 405 |
elif not refs: |
| 406 |
print("Referrers exhausted, warping") |
| 407 |
|
| 408 |
|
| 409 |
NEWIDS = set() |
| 410 |
|
| 411 |
def memdebug(watchClass=base.Structure): |
| 412 |
"""a debug method to track memory usage after some code has run. |
| 413 |
|
| 414 |
This is typically run from ArchiveService.getChild, since request |
| 415 |
processing should be idempotent wrt memory after initial caching. |
| 416 |
|
| 417 |
This is for editing in place by DaCHS plumbers; accordingly, you're |
| 418 |
not supposed to make sense of this. |
| 419 |
""" |
| 420 |
import gc |
| 421 |
print(">>>>>> total managed:", len(gc.get_objects())) |
| 422 |
|
| 423 |
if hasattr(base, "getNewStructs"): |
| 424 |
ns = base.getNewStructs() |
| 425 |
print(">>>>>> new objects:", len(ns)) |
| 426 |
if len(ns)<11000: |
| 427 |
ur = getUnreferenced(ns) |
| 428 |
print(">>>>>> new externally referenced:", len(ur)) |
| 429 |
del ur |
| 430 |
print([ob for ob in ns if isinstance(ob, watchClass)]) |
| 431 |
if True: |
| 432 |
try: |
| 433 |
debugReferenceChain( |
| 434 |
[ob for ob in ns if isinstance(ob, watchClass)][0]) |
| 435 |
except IndexError: |
| 436 |
pass |
| 437 |
|
| 438 |
base.getNewStructs = getMemDiffer(ofClass=watchClass) |
| 439 |
|
| 440 |
|
| 441 |
@contextlib.contextmanager |
| 442 |
def testFile(name, |
| 443 |
content, |
| 444 |
writeGz=False, |
| 445 |
inDir=base.getConfig("tempDir"), |
| 446 |
timestamp=None): |
| 447 |
"""a context manager that creates a file name with content in inDir. |
| 448 |
|
| 449 |
The full path name is returned. |
| 450 |
|
| 451 |
content can be bytes or str; in the latter case, it's utf-8 encoded |
| 452 |
before writing. |
| 453 |
|
| 454 |
With writeGz=True, content is gzipped on the fly (don't do this if |
| 455 |
the data already is gzipped). |
| 456 |
|
| 457 |
You can pass in name=None to get a temporary file name if you don't care |
| 458 |
about the name. |
| 459 |
|
| 460 |
inDir will be created as a side effect if it doesn't exist but (right |
| 461 |
now, at least), not be removed. |
| 462 |
""" |
| 463 |
if not os.path.isdir(inDir): |
| 464 |
os.makedirs(inDir) |
| 465 |
|
| 466 |
if name is None: |
| 467 |
handle, destName = tempfile.mkstemp(dir=inDir) |
| 468 |
os.close(handle) |
| 469 |
else: |
| 470 |
destName = os.path.join(inDir, name) |
| 471 |
|
| 472 |
if writeGz: |
| 473 |
f = gzip.GzipFile(destName, mode="wb") |
| 474 |
else: |
| 475 |
f = open(destName, "wb") |
| 476 |
|
| 477 |
f.write(utils.bytify(content)) |
| 478 |
f.close() |
| 479 |
|
| 480 |
if timestamp: |
| 481 |
os.utime(destName, times=(timestamp, timestamp)) |
| 482 |
|
| 483 |
try: |
| 484 |
yield destName |
| 485 |
finally: |
| 486 |
try: |
| 487 |
os.unlink(destName) |
| 488 |
except os.error: |
| 489 |
pass |
| 490 |
|
| 491 |
|
| 492 |
@contextlib.contextmanager |
| 493 |
def collectedEvents(*kinds): |
| 494 |
"""a context manager collecting event arguments for a while. |
| 495 |
|
| 496 |
The yielded thing is a list that contains tuples of event name and |
| 497 |
the event arguments. |
| 498 |
""" |
| 499 |
collected = [] |
| 500 |
|
| 501 |
def makeHandler(evType): |
| 502 |
def handler(*args): |
| 503 |
collected.append((evType,)+args) |
| 504 |
return handler |
| 505 |
|
| 506 |
handlers = [(kind, makeHandler(kind)) for kind in kinds] |
| 507 |
for kind, handler in handlers: |
| 508 |
base.ui.subscribe(kind, handler) |
| 509 |
|
| 510 |
try: |
| 511 |
yield collected |
| 512 |
finally: |
| 513 |
for kind, handler in handlers: |
| 514 |
base.ui.unsubscribe(kind, handler) |