| 1 |
# -*- coding: utf-8 -*- |
| 2 |
""" |
| 3 |
Helper classes for the DaCHS' unit tests. |
| 4 |
|
| 5 |
WARNING: This messes up some global state. DO NOT import into modules |
| 6 |
doing regular work. testtricks is the module for that kind for stuff. |
| 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 http.server |
| 16 |
import contextlib |
| 17 |
import gc |
| 18 |
import io |
| 19 |
import os |
| 20 |
import pathlib |
| 21 |
import pickle |
| 22 |
import re |
| 23 |
import subprocess |
| 24 |
import sys |
| 25 |
import threading |
| 26 |
import time |
| 27 |
import traceback |
| 28 |
import unittest |
| 29 |
import warnings |
| 30 |
|
| 31 |
try: |
| 32 |
import coverage |
| 33 |
except ImportError: |
| 34 |
# we only need this if someone set COVERAGE_FILE; don't do that |
| 35 |
# if you don't have coverage.py installed. |
| 36 |
pass |
| 37 |
|
| 38 |
|
| 39 |
# This sets up a test environment of the DaCHS software. |
| 40 |
# |
| 41 |
# To make this work, the current user must be allowed to run |
| 42 |
# createdb (in practice, you should have done something like |
| 43 |
# |
| 44 |
# sudo -u postgres -s `id -nu` |
| 45 |
# |
| 46 |
# ). You should be able to tear both ~/_gavo_test and the database |
| 47 |
# down, and this should automatically recreate everything. That's |
| 48 |
# an integration test for DaCHS, too. |
| 49 |
# |
| 50 |
# This must be run before anything else from gavo is imported because |
| 51 |
# it manipulates the config stuff; this, in turn, runs as soon as |
| 52 |
# base is imported. |
| 53 |
|
| 54 |
# The following forces tests to be run from the tests directory. |
| 55 |
# Reasonable, I'd say. |
| 56 |
# |
| 57 |
# All the custom setup can be suppressed by setting a GAVO_OOTTEST |
| 58 |
# env var before importing this. That's for "out of tree test" |
| 59 |
# and is used by several unittest-like things in various resources |
| 60 |
# (e.g., rr). |
| 61 |
|
| 62 |
def ensureResources(): |
| 63 |
# overridden below if necessary |
| 64 |
pass |
| 65 |
|
| 66 |
if "GAVO_OOTTEST" in os.environ: |
| 67 |
from gavo import base |
| 68 |
|
| 69 |
else: |
| 70 |
TEST_BASE = pathlib.Path.cwd() |
| 71 |
originalEnvironment = os.environ.copy() |
| 72 |
os.environ["GAVOCUSTOM"] = "/invalid" |
| 73 |
os.environ["GAVOSETTINGS"] = str(TEST_BASE / "test_data" / "test-gavorc") |
| 74 |
if not os.path.exists(os.environ["GAVOSETTINGS"]): |
| 75 |
warnings.warn("testhelpers imported from non-test directory. This" |
| 76 |
" is almost certainly not what you want (or set GAVO_OOTTEST).") |
| 77 |
|
| 78 |
# keep import base from touching the DB in case the test environment |
| 79 |
# is not present yet; we're calling initPsycopg manually later. |
| 80 |
os.environ["GAVO_INIT_RUNNING"] = "1" |
| 81 |
from gavo import base #noflake: import above is conditional |
| 82 |
del os.environ["GAVO_INIT_RUNNING"] |
| 83 |
|
| 84 |
if base.getConfig("rootDir").exists(): |
| 85 |
# we're assuming the test environment is complete then |
| 86 |
# (i.e., including the test database) |
| 87 |
from gavo.base import sqlsupport |
| 88 |
sqlsupport.initPsycopg() |
| 89 |
|
| 90 |
else: |
| 91 |
from gavo.user import initdachs |
| 92 |
dbname = "dachstest" |
| 93 |
dsn = initdachs.DSN(dbname) |
| 94 |
initdachs.createFSHierarchy(dsn, "test") |
| 95 |
|
| 96 |
with open(base.getConfig("configDir") / "defaultmeta.txt", "a", |
| 97 |
encoding="utf-8") as f: |
| 98 |
f.write("!organization.description: Mein wüster Club\n") |
| 99 |
f.write("!contact.email: [email protected]\n") |
| 100 |
|
| 101 |
with open(base.getConfig("configDir") / "vanitynames.txt", "w") as f: |
| 102 |
f.write('http://sofo-hd.de sofo !redirect\n' |
| 103 |
'data/cores/scs/scs.xml fromvanitynames\n') |
| 104 |
|
| 105 |
from gavo.base import config, meta |
| 106 |
meta.makeFallbackMeta(reload=True) |
| 107 |
os.symlink(TEST_BASE / "test_data", |
| 108 |
base.getConfig("inputsDir") / "data") |
| 109 |
(base.getConfig("inputsDir") / "test").mkdir(exist_ok=True) |
| 110 |
(base.getConfig("inputsDir") / "__system").mkdir(exist_ok=True) |
| 111 |
|
| 112 |
subprocess.check_call(["createdb", "--template=template0", |
| 113 |
"--encoding=UTF-8", "--locale=C", dbname]) |
| 114 |
initdachs.initDB(dsn) |
| 115 |
from gavo.base import sqlsupport |
| 116 |
sqlsupport.initPsycopg() |
| 117 |
|
| 118 |
def ensureResources(): #noflake: deliberate override |
| 119 |
# delay everything that needs DB connectivity until |
| 120 |
# after the import; otherwise, we may create a conn pool |
| 121 |
# and that, as used in DaCHS, may create a thread. That means |
| 122 |
# risking a deadlock while python is importing. |
| 123 |
try: |
| 124 |
from gavo.registry import publication |
| 125 |
from gavo import rsc |
| 126 |
from gavo import rscdesc #noflake: caches registration |
| 127 |
from gavo.protocols import creds |
| 128 |
|
| 129 |
publication.updateServiceList([base.caches.getRD("//rds")]) |
| 130 |
publication.updateServiceList([base.caches.getRD("//services")]) |
| 131 |
publication.updateServiceList([base.caches.getRD("//tap")]) |
| 132 |
publication.updateServiceList([base.caches.getRD("data/cores")]) |
| 133 |
publication.updateServiceList([base.caches.getRD("data/ssatest")]) |
| 134 |
|
| 135 |
# Import some resources necessary in trial tests |
| 136 |
from gavo.user import importing |
| 137 |
importing.process(rsc.getParseOptions(), ["//tap_user"]) |
| 138 |
importing.process(rsc.getParseOptions(), ["//obscore"]) |
| 139 |
importing.process(rsc.getParseOptions(), ["//biblinks"]) |
| 140 |
|
| 141 |
# clear the RD cache so we see the new publications |
| 142 |
base.caches.clearCaches() |
| 143 |
from gavo.rscdef.common import getIvoidsForRDId |
| 144 |
getIvoidsForRDId.cache_clear() |
| 145 |
|
| 146 |
with base.getWritableAdminConn() as conn: |
| 147 |
rsc.makeData(base.resolveCrossId("//uws#enable_useruws"), |
| 148 |
connection=conn) |
| 149 |
creds.addUser(conn, "testing", "testing", "powerless test user") |
| 150 |
creds.addUser(conn, "other", "other", "another test user") |
| 151 |
|
| 152 |
except: |
| 153 |
traceback.print_exc() |
| 154 |
sys.stderr.write("Creation of test environment failed. Remove %s\n" |
| 155 |
" before trying again.\n"%(base.getConfig("rootDir"))) |
| 156 |
sys.exit(1) |
| 157 |
|
| 158 |
|
| 159 |
# we really don't want to send mail from the test suite, so override |
| 160 |
# osinter.sendMail with a no-op |
| 161 |
from gavo.base import osinter |
| 162 |
osinter.sendMail = lambda *args, **kwargs: None |
| 163 |
|
| 164 |
from gavo import utils |
| 165 |
from gavo.base import config #noflake: previous import conditional |
| 166 |
from gavo.base import sqlsupport |
| 167 |
from gavo.adql import ufunctions |
| 168 |
|
| 169 |
|
| 170 |
class FakeSimbad(object): |
| 171 |
"""we monkeypatch simbadinterface such that we don't query simbad during |
| 172 |
tests. |
| 173 |
|
| 174 |
Also, we don't persist cached Simbad responses. It's a bit sad that |
| 175 |
that functionality therefore doesn't get exercised. |
| 176 |
""" |
| 177 |
simbadData = {'Aldebaran': {'RA': 68.98016279, |
| 178 |
'dec': 16.50930235, |
| 179 |
'oname': 'Aldebaran', |
| 180 |
'otype': 'LP?'}, |
| 181 |
'M1': {'RA': 83.63308333, 'dec': 22.0145, 'oname': 'M1', 'otype': 'SNR'}, |
| 182 |
'Wozzlfoo7xx': None} |
| 183 |
|
| 184 |
def __init__(self, *args, **kwargs): |
| 185 |
pass |
| 186 |
|
| 187 |
def query(self, ident): |
| 188 |
return self.simbadData.get(ident) |
| 189 |
|
| 190 |
|
| 191 |
# Here's the deal on TestResource: When setting up complicated stuff for |
| 192 |
# tests (like, a DB table), define a TestResource for it. Override |
| 193 |
# the make(dependents) method returning something and the clean(res) |
| 194 |
# method to destroy whatever you created in make(). |
| 195 |
# |
| 196 |
# Then, in VerboseTests, have a class attribute |
| 197 |
# resource = [(name1, res1), (name2, res2)] |
| 198 |
# giving attribute names and resource *instances*. |
| 199 |
# There's an example in adqltest.py |
| 200 |
# |
| 201 |
# If you use this and you have a setUp of your own, you *must* call |
| 202 |
# the superclass's setUp method. |
| 203 |
|
| 204 |
import testresources |
| 205 |
|
| 206 |
class ResourceInstance(object): |
| 207 |
"""A helper class for TestResource. |
| 208 |
|
| 209 |
See that docstring for info on what this is about; in case you |
| 210 |
encounter one of these but need the real thing, just pull |
| 211 |
.original. |
| 212 |
""" |
| 213 |
def __init__(self, original): |
| 214 |
self.original = original |
| 215 |
|
| 216 |
def __getattr__(self, name): |
| 217 |
return getattr(self.original, name) |
| 218 |
|
| 219 |
def __getitem__(self, index): |
| 220 |
return self.original[index] |
| 221 |
|
| 222 |
def __iter__(self): |
| 223 |
return iter(self.original) |
| 224 |
|
| 225 |
def __str__(self): |
| 226 |
return str(self.original) |
| 227 |
|
| 228 |
def __len__(self): |
| 229 |
return len(self.original) |
| 230 |
|
| 231 |
def __contains__(self, other): |
| 232 |
return other in self.original |
| 233 |
|
| 234 |
|
| 235 |
class TestResource(testresources.TestResource): |
| 236 |
"""A wrapper for testresources maintaining some backward compatibility. |
| 237 |
|
| 238 |
testresources 2.0.1 pukes into the namespaces of what's |
| 239 |
returned from make. I've not really researched what they |
| 240 |
intend people to return from make these days, but in order |
| 241 |
to avoid major surgery on the code, this class simply wraps |
| 242 |
objects that don't allow arbitrary attributes with ResourceInstance |
| 243 |
when returned from make. |
| 244 |
|
| 245 |
To make that happen, I need to override code from testresources itself, |
| 246 |
which is a pity. In case this breaks: Take all methods that call .make |
| 247 |
and replace make with _make_and_wrap. |
| 248 |
|
| 249 |
Caution: when you implement reset(), you'll have to wrap the |
| 250 |
result with testhelpers.ResourceInstance manually; but then you'd |
| 251 |
have to copy dependencies manually, which is crazy, and so I think |
| 252 |
manual reset currently really is broken. |
| 253 |
""" |
| 254 |
def _make_and_wrap(self, deps): |
| 255 |
res = self.make(deps) |
| 256 |
try: |
| 257 |
# see if we can set attributes and return if so... |
| 258 |
res.improbably_named_attribute = None |
| 259 |
del res.improbably_named_attribute |
| 260 |
return res |
| 261 |
except AttributeError: |
| 262 |
# ...else wrap the result |
| 263 |
return ResourceInstance(res) |
| 264 |
|
| 265 |
##### Methods adapted from testresources |
| 266 |
|
| 267 |
def _make_all(self, result): |
| 268 |
"""Make the dependencies of this resource and this resource.""" |
| 269 |
self._call_result_method_if_exists(result, "startMakeResource", self) |
| 270 |
dependency_resources = {} |
| 271 |
for name, resource in self.resources: |
| 272 |
dependency_resources[name] = resource.getResource() |
| 273 |
resource = self._make_and_wrap(dependency_resources) |
| 274 |
for name, value in list(dependency_resources.items()): |
| 275 |
setattr(resource, name, value) |
| 276 |
self._call_result_method_if_exists(result, "stopMakeResource", self) |
| 277 |
return resource |
| 278 |
|
| 279 |
def _reset(self, resource, dependency_resources): |
| 280 |
"""Override this to reset resources other than via clean+make. |
| 281 |
|
| 282 |
This method should reset the self._dirty flag (assuming the manager can |
| 283 |
ever be clean) and return either the old resource cleaned or a fresh |
| 284 |
one. |
| 285 |
|
| 286 |
:param resource: The resource to reset. |
| 287 |
:param dependency_resources: A dict mapping name -> resource instance |
| 288 |
for the resources specified as dependencies. |
| 289 |
""" |
| 290 |
self.clean(resource) |
| 291 |
return self._make_and_wrap(dependency_resources) |
| 292 |
|
| 293 |
|
| 294 |
from gavo.helpers.testtricks import ( #noflake: exported names |
| 295 |
XSDTestMixin, testFile, getMemDiffer, getXMLTree, collectedEvents, |
| 296 |
pickSingle) |
| 297 |
|
| 298 |
|
| 299 |
class ForkingSubprocess(subprocess.Popen): |
| 300 |
"""A subprocess that doesn't exec but fork. |
| 301 |
""" |
| 302 |
def __init__(self, *args, **kwargs): |
| 303 |
self.input = kwargs.pop("input", None) |
| 304 |
super().__init__(*args, **kwargs) |
| 305 |
|
| 306 |
def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 307 |
pass_fds, cwd, env, |
| 308 |
startupinfo, creationflags, shell, |
| 309 |
p2cread, p2cwrite, |
| 310 |
c2pread, c2pwrite, |
| 311 |
errread, errwrite, |
| 312 |
restore_signals, |
| 313 |
# post-3.7, some additional parameters were added, which |
| 314 |
# fortunately we don't need. |
| 315 |
*ignored_args): |
| 316 |
# stolen largely from 2.7 subprocess. Unfortunately, I can't just override the |
| 317 |
# exec action; so, I'm replacing the the whole exec shebang with a simple |
| 318 |
# call to executable(). |
| 319 |
# |
| 320 |
# Also, I'm doing some extra hack to collect coverage info if it looks |
| 321 |
# like we're collecting coverage. |
| 322 |
# |
| 323 |
# The signature (and a few inside parts) is from 3.7 subprocess. We're |
| 324 |
# ignoring everything that 2.7 hasn't known under the bold assumption that our |
| 325 |
# simple testing forks that doesn't matter (which ought to be true for |
| 326 |
# start_new_session at least:-). |
| 327 |
# |
| 328 |
# Since we don't exec, I'm catching and communicating subprocess exceptions |
| 329 |
# while the function is running. This means that the parent will |
| 330 |
# hang in a read while the subprocess is running. In turn, this means |
| 331 |
# that you can't subprocess.communicate because the parent isn't running. |
| 332 |
# You can pass in small amounts of input, though (but things will hang |
| 333 |
# if it'd fill up a buffer and the child crashes before it can read. |
| 334 |
|
| 335 |
sys.argv = args |
| 336 |
if executable is None: |
| 337 |
executable = args[0] |
| 338 |
|
| 339 |
def _close_in_parent(fd): |
| 340 |
try: |
| 341 |
os.close(fd) |
| 342 |
except os.error: |
| 343 |
# fd can be a bad file descriptor under circumstances I have |
| 344 |
# not investigated. If it is, don't bail out; it's better |
| 345 |
# if we at least close whatever is left. |
| 346 |
pass |
| 347 |
|
| 348 |
# For transferring possible exec failure from child to parent. |
| 349 |
# Data format: "exception name:hex errno:description" |
| 350 |
# Pickle is not used; it is complex and involves memory allocation. |
| 351 |
errpipe_read, errpipe_write = os.pipe() |
| 352 |
|
| 353 |
try: |
| 354 |
gc_was_enabled = gc.isenabled() |
| 355 |
# Disable gc to avoid bug where gc -> file_dealloc -> |
| 356 |
# write to stderr -> hang. http://bugs.python.org/issue1336 |
| 357 |
gc.disable() |
| 358 |
try: |
| 359 |
self.pid = os.fork() |
| 360 |
except: |
| 361 |
if gc_was_enabled: |
| 362 |
gc.enable() |
| 363 |
raise |
| 364 |
self._child_created = True |
| 365 |
if self.pid == 0: |
| 366 |
# Child |
| 367 |
try: |
| 368 |
# Close parent's pipe ends |
| 369 |
if p2cwrite!=-1: |
| 370 |
os.close(p2cwrite) |
| 371 |
if c2pread!=-1: |
| 372 |
os.close(c2pread) |
| 373 |
if errread!=-1: |
| 374 |
os.close(errread) |
| 375 |
os.close(errpipe_read) |
| 376 |
|
| 377 |
# When duping fds, if there arises a situation |
| 378 |
# where one of the fds is either 0, 1 or 2, it |
| 379 |
# is possible that it is overwritten (#12607). |
| 380 |
if c2pwrite == 0: |
| 381 |
c2pwrite = os.dup(c2pwrite) |
| 382 |
if errwrite == 0 or errwrite == 1: |
| 383 |
errwrite = os.dup(errwrite) |
| 384 |
|
| 385 |
# Dup fds for child |
| 386 |
def _dup2(a, b): |
| 387 |
# dup2() removes the CLOEXEC flag but |
| 388 |
# we must do it ourselves if dup2() |
| 389 |
# would be a no-op (issue #10806). |
| 390 |
if a == b: |
| 391 |
self._set_cloexec_flag(a, False) |
| 392 |
elif a!=-1: |
| 393 |
os.dup2(a, b) |
| 394 |
_dup2(p2cread, 0) |
| 395 |
_dup2(c2pwrite, 1) |
| 396 |
_dup2(errwrite, 2) |
| 397 |
|
| 398 |
# Close pipe fds. Make sure we don't close the |
| 399 |
# same fd more than once, or standard fds. |
| 400 |
closed = set([-1]) |
| 401 |
for fd in [p2cread, c2pwrite, errwrite]: |
| 402 |
if fd not in closed and fd > 2: |
| 403 |
os.close(fd) |
| 404 |
closed.add(fd) |
| 405 |
|
| 406 |
if cwd is not None: |
| 407 |
os.chdir(cwd) |
| 408 |
|
| 409 |
if "COVERAGE_FILE" in os.environ: |
| 410 |
cov = coverage.Coverage(data_file="forked.cov", |
| 411 |
source=["gavo"], |
| 412 |
auto_data=True) |
| 413 |
cov.config.disable_warnings = ["module-not-measured"] |
| 414 |
cov.start() |
| 415 |
|
| 416 |
if preexec_fn: |
| 417 |
preexec_fn() |
| 418 |
|
| 419 |
exitcode = 0 |
| 420 |
try: |
| 421 |
executable() |
| 422 |
except SystemExit as ex: |
| 423 |
exitcode = ex.code |
| 424 |
|
| 425 |
except: |
| 426 |
exc_type, exc_value, tb = sys.exc_info() |
| 427 |
# Save the traceback and attach it to the exception object |
| 428 |
exc_lines = traceback.format_exception(exc_type, |
| 429 |
exc_value, |
| 430 |
tb) |
| 431 |
exc_value.child_traceback = ''.join(exc_lines) |
| 432 |
os.write(errpipe_write, pickle.dumps(exc_value)) |
| 433 |
os.close(errpipe_write) |
| 434 |
os._exit(255) |
| 435 |
|
| 436 |
os.close(errpipe_write) |
| 437 |
if "COVERAGE_FILE" in os.environ: |
| 438 |
cov.stop() |
| 439 |
cov.save() |
| 440 |
sys.stderr.close() |
| 441 |
sys.stdout.close() |
| 442 |
os._exit(exitcode) |
| 443 |
|
| 444 |
|
| 445 |
# Parent |
| 446 |
os.close(errpipe_write) |
| 447 |
if gc_was_enabled: |
| 448 |
gc.enable() |
| 449 |
|
| 450 |
if self.input: |
| 451 |
# this is lame as it will hang if the child crashes |
| 452 |
# early and we fill the buffer. But I'd like to avoid |
| 453 |
# re-implementing subprocess.communicate here... |
| 454 |
os.write(p2cwrite, self.input) |
| 455 |
# I need to close p2cwrite so children waiting for eof |
| 456 |
# run... |
| 457 |
_close_in_parent(p2cwrite) |
| 458 |
p2cwrite = -1 |
| 459 |
# keep subprocess.communicate from trying to close again. |
| 460 |
self.stdin = None |
| 461 |
|
| 462 |
# Now wait for the child to come up (at which point it will |
| 463 |
# close its error pipe) |
| 464 |
errpipe_data = bytearray() |
| 465 |
while True: |
| 466 |
part = os.read(errpipe_read, 50000) |
| 467 |
errpipe_data += part |
| 468 |
if not part or len(errpipe_data)>50000: |
| 469 |
break |
| 470 |
if errpipe_data: |
| 471 |
child_exception = pickle.loads(errpipe_data) |
| 472 |
raise child_exception |
| 473 |
|
| 474 |
finally: |
| 475 |
# close the FDs used by the child if they were opened |
| 476 |
if p2cread!=-1 and p2cwrite!=-1: |
| 477 |
_close_in_parent(p2cread) |
| 478 |
if c2pwrite!=-1 and c2pread!=-1: |
| 479 |
_close_in_parent(c2pwrite) |
| 480 |
if errwrite!=-1 and errread!=-1: |
| 481 |
_close_in_parent(errwrite) |
| 482 |
|
| 483 |
# be sure the error pipe FD is eventually no matter what |
| 484 |
_close_in_parent(errpipe_read) |
| 485 |
|
| 486 |
|
| 487 |
class VerboseTest(testresources.ResourcedTestCase): |
| 488 |
"""A TestCase with a couple of convenient assert methods. |
| 489 |
""" |
| 490 |
def assertEqualForArgs(self, callable, result, *args): |
| 491 |
self.assertEqual(callable(*args), result, |
| 492 |
"Failed for arguments %s. Expected result is: %s, result found" |
| 493 |
" was: %s"%(str(args), repr(result), repr(callable(*args)))) |
| 494 |
|
| 495 |
def assertRaisesVerbose(self, exception, callable, args, msg): |
| 496 |
try: |
| 497 |
callable(*args) |
| 498 |
except exception: |
| 499 |
return |
| 500 |
except: |
| 501 |
raise |
| 502 |
else: |
| 503 |
raise self.failureException(msg) |
| 504 |
|
| 505 |
def assertRaisesWithMsg(self, exception, errMsg, callable, args, msg=None, |
| 506 |
**kwargs): |
| 507 |
try: |
| 508 |
value = callable(*args, **kwargs) |
| 509 |
except exception as ex: |
| 510 |
if errMsg==str(ex): |
| 511 |
pass # make sure we decide on __eq__ for EqualingRE's sake |
| 512 |
else: |
| 513 |
raise self.failureException( |
| 514 |
"Expected %r, got %r as exception message"%(errMsg, str(ex))) |
| 515 |
return ex |
| 516 |
except: |
| 517 |
raise |
| 518 |
else: |
| 519 |
raise self.failureException(msg or |
| 520 |
"%s not raised (function returned %s)"%( |
| 521 |
str(exception), repr(value))) |
| 522 |
|
| 523 |
def assertRuns(self, callable, args, msg=None): |
| 524 |
try: |
| 525 |
callable(*args) |
| 526 |
except Exception as ex: |
| 527 |
raise self.failureException("Should run, but raises %s (%s) exception"%( |
| 528 |
ex.__class__.__name__, str(ex))) |
| 529 |
|
| 530 |
def assertAlmostEqualVector(self, first, second, places=7, msg=None): |
| 531 |
def getnulls(vec): |
| 532 |
return [val is None or val!=val for val in vec] |
| 533 |
|
| 534 |
if getnulls(first)!=getnulls(second): |
| 535 |
raise AssertionError(f"{first} and {second} have a different null mask") |
| 536 |
|
| 537 |
first = [val for val in first if val is not None and val==val] |
| 538 |
second = [val for val in second if val is not None and val==val] |
| 539 |
|
| 540 |
try: |
| 541 |
for f, s in zip(first, second): |
| 542 |
self.assertAlmostEqual(f/s, 1, places) |
| 543 |
except AssertionError: |
| 544 |
if msg: |
| 545 |
raise AssertionError(msg) |
| 546 |
else: |
| 547 |
raise AssertionError("%s != %s within %d places"%( |
| 548 |
first, second, places)) |
| 549 |
|
| 550 |
def assertEqualToWithin(self, a, b, ratio=1e-7, msg=None): |
| 551 |
"""asserts that abs(a-b/(a+b))<ratio. |
| 552 |
|
| 553 |
If a+b are an underflow, we error out right now. |
| 554 |
""" |
| 555 |
if msg is None: |
| 556 |
msg = "%s != %s to within %s of the sum"%(a, b, ratio) |
| 557 |
denom = abs(a+b) |
| 558 |
self.assertTrue(abs(a-b)/denom<ratio, msg) |
| 559 |
|
| 560 |
def assertOutput(self, toExec, argList, expectedStdout=None, |
| 561 |
expectedStderr="", expectedRetcode=0, input=None, |
| 562 |
stdoutStrings=None): |
| 563 |
"""checks that execName called with argList has the given output and return |
| 564 |
value. |
| 565 |
|
| 566 |
expectedStdout and expectedStderr can be functions. In that case, |
| 567 |
the output is passed to the function, and an assertionError is raised |
| 568 |
if the functions do not return true. |
| 569 |
|
| 570 |
The 0th argument in argList is automatically added, only pass "real" |
| 571 |
command line arguments. |
| 572 |
|
| 573 |
toExec may also be a zero-argument python function. In that case, the |
| 574 |
process is forked and the function is called, with sys.argv according to |
| 575 |
argList. This helps to save startup time for python main functions. |
| 576 |
""" |
| 577 |
for name in ["output.stderr", "output.stdout"]: |
| 578 |
try: |
| 579 |
os.unlink(name) |
| 580 |
except os.error: |
| 581 |
pass |
| 582 |
|
| 583 |
if isinstance(toExec, str): |
| 584 |
p = subprocess.Popen([toExec]+argList, executable=toExec, |
| 585 |
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
| 586 |
out, err = p.communicate(input=utils.bytify(input)) |
| 587 |
else: |
| 588 |
p = ForkingSubprocess(["test harness"]+argList, executable=toExec, |
| 589 |
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, |
| 590 |
input=utils.bytify(input)) |
| 591 |
out, err = p.communicate() |
| 592 |
retcode = p.wait() |
| 593 |
|
| 594 |
try: |
| 595 |
if isinstance(expectedStderr, (bytes, str)): |
| 596 |
self.assertEqual(err, utils.bytify(expectedStderr)) |
| 597 |
elif isinstance(expectedStderr, list): |
| 598 |
for sample in expectedStderr: |
| 599 |
self.assertTrue(utils.bytify(sample) in err, |
| 600 |
"%s missing in stderr"%repr(sample)) |
| 601 |
else: |
| 602 |
self.assertTrue(expectedStderr(err), "Stderr didn't match functional" |
| 603 |
" expectation: %s"%err.decode("ascii", "?")) |
| 604 |
|
| 605 |
self.assertEqual(expectedRetcode, retcode) |
| 606 |
except AssertionError: |
| 607 |
with open("output.stdout", "wb") as f: |
| 608 |
f.write(out) |
| 609 |
with open("output.stderr", "wb") as f: |
| 610 |
f.write(err) |
| 611 |
raise |
| 612 |
|
| 613 |
try: |
| 614 |
if isinstance(expectedStdout, (bytes, str)): |
| 615 |
self.assertEqual(out, utils.bytify(expectedStdout)) |
| 616 |
elif isinstance(expectedStdout, list): |
| 617 |
for sample in expectedStdout: |
| 618 |
self.assertTrue(utils.bytify(sample) in out, |
| 619 |
"%s missing in stdout"%repr(sample)) |
| 620 |
elif expectedStdout is not None: |
| 621 |
self.assertTrue(expectedStdout(out)) |
| 622 |
except AssertionError: |
| 623 |
with open("output.stdout", "wb") as f: |
| 624 |
f.write(out) |
| 625 |
raise |
| 626 |
|
| 627 |
def assertEqualIgnoringAliases(self, result, expectation): |
| 628 |
pat = re.escape(re.sub(r"\s+", " ", expectation) |
| 629 |
).replace("ASWHATEVER", "AS [a-z]+")+"$" |
| 630 |
if not re.match(pat, re.sub(r"\s+", " ", result)): |
| 631 |
raise AssertionError("%r != %r"%(result, expectation)) |
| 632 |
|
| 633 |
|
| 634 |
_xmlJunkPat = re.compile("|".join([ |
| 635 |
r'(xmlns(:[a-z0-9]+)?="[^"]*"\s*)', |
| 636 |
r'((frame_|coord_system_)?id="[^"]*")', |
| 637 |
r'(xsi:schemaLocation="[^"]*"\s*)'])) |
| 638 |
|
| 639 |
|
| 640 |
def cleanXML(aString): |
| 641 |
"""removes IDs and some other detritus from XML literals. |
| 642 |
|
| 643 |
The result will be invalid XML, and all this assumes the fixed-prefix |
| 644 |
logic of the DC software. |
| 645 |
|
| 646 |
For new tests, you should just getXMLTree and XPath tests. |
| 647 |
|
| 648 |
aString can be bytes, in which case it will be interpreted as ASCII. |
| 649 |
cleanXML returns a string in any case. |
| 650 |
""" |
| 651 |
return re.sub(r"\s+", " ", |
| 652 |
_xmlJunkPat.sub('', |
| 653 |
utils.debytify(aString))).strip( |
| 654 |
).replace(" />", "/>").replace(" >", ">") |
| 655 |
|
| 656 |
|
| 657 |
class SamplesBasedAutoTest(type): |
| 658 |
"""A metaclass that builds tests out of a samples attribute of a class. |
| 659 |
|
| 660 |
To use this, give the class a samples attribute containing a sequence |
| 661 |
of anything, and a _runTest(sample) method receiving one item of |
| 662 |
that sequence. |
| 663 |
|
| 664 |
The metaclass will create one test<n> method for each sample. |
| 665 |
""" |
| 666 |
def __new__(cls, name, bases, dict): |
| 667 |
for sampInd, sample in enumerate(dict.get("samples", ())): |
| 668 |
def testFun(self, sample=sample): |
| 669 |
self._runTest(sample) |
| 670 |
dict["test%02d"%sampInd] = testFun |
| 671 |
return type.__new__(cls, name, bases, dict) |
| 672 |
|
| 673 |
|
| 674 |
class SimpleSampleComparisonTest(VerboseTest, metaclass=SamplesBasedAutoTest): |
| 675 |
"""A base class for tests that simply run a function and compare |
| 676 |
for equality. |
| 677 |
|
| 678 |
The function to be called is in the functionToRun attribute (wrap |
| 679 |
it in a staticmethod). |
| 680 |
|
| 681 |
The samples are pairs of (input, output). Output may be an |
| 682 |
exception (or just the serialised form of the exception). |
| 683 |
""" |
| 684 |
|
| 685 |
def _runTest(self, sample): |
| 686 |
val, expected = sample |
| 687 |
try: |
| 688 |
self.assertEqual(self.functionToRun(val), |
| 689 |
expected) |
| 690 |
except AssertionError: |
| 691 |
raise |
| 692 |
except Exception as ex: |
| 693 |
if str(ex)!=str(expected): |
| 694 |
raise |
| 695 |
|
| 696 |
|
| 697 |
def computeWCSKeys(pos, size, cutCrap=False): |
| 698 |
"""returns a dictionary containing a 2D WCS structure for an image |
| 699 |
centered at pos with angular size. Both are 2-tuples in degrees. |
| 700 |
""" |
| 701 |
imgPix = (1000., 1000.) |
| 702 |
res = { |
| 703 |
"CRVAL1": pos[0], |
| 704 |
"CRVAL2": pos[1], |
| 705 |
"CRPIX1": imgPix[0]/2., |
| 706 |
"CRPIX2": imgPix[1]/2., |
| 707 |
"CUNIT1": "deg", |
| 708 |
"CUNIT2": "deg", |
| 709 |
"CD1_1": size[0]/imgPix[0], |
| 710 |
"CD1_2": 0, |
| 711 |
"CD2_2": size[1]/imgPix[1], |
| 712 |
"CD2_1": 0, |
| 713 |
"NAXIS1": imgPix[0], |
| 714 |
"NAXIS2": imgPix[1], |
| 715 |
"NAXIS": 2, |
| 716 |
"CTYPE1": 'RA---TAN-SIP', |
| 717 |
"CTYPE2": 'DEC--TAN-SIP', |
| 718 |
"LONPOLE": 180.} |
| 719 |
if not cutCrap: |
| 720 |
res.update({"imageTitle": "test image at %s"%repr(pos), |
| 721 |
"instId": None, |
| 722 |
"dateObs":55300+pos[0], |
| 723 |
"refFrame": None, |
| 724 |
"wcs_equinox": None, |
| 725 |
"bandpassId": None, |
| 726 |
"bandpassUnit": None, |
| 727 |
"bandpassRefval": None, |
| 728 |
"bandpassLo": pos[0]+0.0001, |
| 729 |
"bandpassHi": pos[0]+size[0], |
| 730 |
"pixflags": None, |
| 731 |
"accref": "image/%s/%s"%(pos, size), |
| 732 |
"accsize": (30+int(pos[0]+pos[1]+size[0]+size[1]))*1024, |
| 733 |
"embargo": None, |
| 734 |
"owner": None, |
| 735 |
}) |
| 736 |
return res |
| 737 |
|
| 738 |
|
| 739 |
class StandIn(object): |
| 740 |
"""A class having the attributes passed as kwargs to the constructor. |
| 741 |
""" |
| 742 |
def __init__(self, **kwargs): |
| 743 |
for key, value in list(kwargs.items()): |
| 744 |
setattr(self, key, value) |
| 745 |
|
| 746 |
|
| 747 |
def getTestRD(id="test.rd"): |
| 748 |
from gavo import rscdesc #noflake: import above is conditional |
| 749 |
from gavo import base |
| 750 |
return base.caches.getRD("data/%s"%id) |
| 751 |
|
| 752 |
|
| 753 |
def getTestTable(tableName, id="test.rd"): |
| 754 |
return getTestRD(id).getTableDefById(tableName) |
| 755 |
|
| 756 |
|
| 757 |
def getTestData(dataId): |
| 758 |
return getTestRD().getDataById(dataId) |
| 759 |
|
| 760 |
|
| 761 |
def hasUDF(udfName): |
| 762 |
"""returns true if this system has an ADQL user defined function named |
| 763 |
udfName. |
| 764 |
|
| 765 |
This is intended to be used as in:: |
| 766 |
|
| 767 |
@unittest.skipUnless(testhelpers.hasUDF("GAVO_FOO"), "...") |
| 768 |
|
| 769 |
Caution: UDF names are upper case here. |
| 770 |
""" |
| 771 |
return udfName in ufunctions.UFUNC_REGISTRY |
| 772 |
|
| 773 |
|
| 774 |
def captureOutput(callable, args=(), kwargs={}): |
| 775 |
"""runs ``callable(*args, **kwargs)`` and captures the output. |
| 776 |
|
| 777 |
The function returns a tuple of return value, stdout output, stderr output. |
| 778 |
""" |
| 779 |
realOut, realErr = sys.stdout, sys.stderr |
| 780 |
sys.stdout, sys.stderr = io.StringIO(), io.StringIO() |
| 781 |
try: |
| 782 |
retVal = 2 # in case the callable sys.exits |
| 783 |
try: |
| 784 |
retVal = callable(*args, **kwargs) |
| 785 |
except SystemExit: |
| 786 |
# don't terminate just because someone thinks it's a good idea |
| 787 |
pass |
| 788 |
finally: |
| 789 |
outCont, errCont = sys.stdout.getvalue(), sys.stderr.getvalue() |
| 790 |
sys.stdout, sys.stderr = realOut, realErr |
| 791 |
return retVal, outCont, errCont |
| 792 |
|
| 793 |
|
| 794 |
class CatchallUI(object): |
| 795 |
"""A replacement for base.ui, collecting the messages being sent. |
| 796 |
|
| 797 |
This is to write tests against producing UI events. Use it with |
| 798 |
the messageCollector context manager below. |
| 799 |
""" |
| 800 |
def __init__(self): |
| 801 |
self.events = [] |
| 802 |
|
| 803 |
def record(self, evType, args, kwargs): |
| 804 |
self.events.append((evType, args, kwargs)) |
| 805 |
|
| 806 |
def __getattr__(self, attName): |
| 807 |
if attName.startswith("notify"): |
| 808 |
return lambda *args, **kwargs: self.record(attName[6:], args, kwargs) |
| 809 |
|
| 810 |
|
| 811 |
@contextlib.contextmanager |
| 812 |
def messageCollector(): |
| 813 |
"""A context manager recording UI events. |
| 814 |
|
| 815 |
The object returned by the context manager is a CatchallUI; get the |
| 816 |
events accumulated during the run time in its events attribute. |
| 817 |
""" |
| 818 |
tempui = CatchallUI() |
| 819 |
realui = base.ui |
| 820 |
try: |
| 821 |
base.ui = tempui |
| 822 |
yield tempui |
| 823 |
finally: |
| 824 |
base.ui = realui |
| 825 |
|
| 826 |
|
| 827 |
@contextlib.contextmanager |
| 828 |
def fakeTime(t): |
| 829 |
"""makes time.time() return t within the controlled block. |
| 830 |
""" |
| 831 |
time_time = time.time |
| 832 |
try: |
| 833 |
time.time = lambda *args: t |
| 834 |
yield |
| 835 |
finally: |
| 836 |
time.time = time_time |
| 837 |
|
| 838 |
|
| 839 |
def getServerInThread(data, onlyOnce=False, contentType="text/plain"): |
| 840 |
"""runs a server in a thread and returns thread and base url. |
| 841 |
|
| 842 |
onlyOnce will configure the server such that it destroys itself |
| 843 |
after having handled one request. The thread would still need |
| 844 |
to be joined. |
| 845 |
|
| 846 |
So, better use the DataServer context manager. |
| 847 |
""" |
| 848 |
if isinstance(data, str): |
| 849 |
data = data.encode("utf-8") |
| 850 |
|
| 851 |
class Handler(http.server.BaseHTTPRequestHandler): |
| 852 |
def log_request(self, *args): |
| 853 |
pass |
| 854 |
|
| 855 |
def do_404(self): |
| 856 |
self.send_response(404, "Not Found") |
| 857 |
self.send_header("Content-Type", "text/plain") |
| 858 |
self.end_headers() |
| 859 |
self.wfile.write(b"You know this wouldn't be here") |
| 860 |
|
| 861 |
def do_GET(self): |
| 862 |
if self.path.endswith("does-not-exist"): |
| 863 |
return self.do_404() |
| 864 |
|
| 865 |
self.send_response(200, "Ok") |
| 866 |
self.send_header("Content-Type", contentType) |
| 867 |
self.end_headers() |
| 868 |
self.wfile.write(data) |
| 869 |
do_POST = do_GET |
| 870 |
|
| 871 |
port = 34000 |
| 872 |
httpd = http.server.HTTPServer(('', port), Handler) |
| 873 |
|
| 874 |
if onlyOnce: |
| 875 |
serve = httpd.handle_request |
| 876 |
else: |
| 877 |
serve = httpd.serve_forever |
| 878 |
|
| 879 |
t = threading.Thread(target=serve) |
| 880 |
t.setDaemon(True) |
| 881 |
t.start() |
| 882 |
return httpd, t, "http://localhost:%s"%port |
| 883 |
|
| 884 |
|
| 885 |
@contextlib.contextmanager |
| 886 |
def DataServer(data): |
| 887 |
"""a context manager for briefly running a web server returning data. |
| 888 |
|
| 889 |
This yields the base URL the server is listening on. |
| 890 |
""" |
| 891 |
httpd, t, baseURL = getServerInThread(data) |
| 892 |
|
| 893 |
try: |
| 894 |
yield baseURL |
| 895 |
finally: |
| 896 |
httpd.shutdown() |
| 897 |
t.join(10) |
| 898 |
|
| 899 |
|
| 900 |
@contextlib.contextmanager |
| 901 |
def userconfigContent(content): |
| 902 |
"""a context manager to temporarily set some content to userconfig. |
| 903 |
|
| 904 |
This cleans up after itself and clears any userconfig cache before |
| 905 |
it sets to work. |
| 906 |
|
| 907 |
content are RD elements without the root (resource) tag. |
| 908 |
""" |
| 909 |
from gavo import rscdesc |
| 910 |
|
| 911 |
userConfigPath = rscdesc.USERCONFIG_RD_PATH |
| 912 |
base.caches.clearForName(str(userConfigPath)) |
| 913 |
with open(userConfigPath.with_suffix(".rd"), "w") as f: |
| 914 |
f.write('<resource schema="__system">\n' |
| 915 |
+content |
| 916 |
+'\n</resource>\n') |
| 917 |
try: |
| 918 |
yield |
| 919 |
finally: |
| 920 |
os.unlink(userConfigPath.with_suffix(".rd")) |
| 921 |
base.caches.clearForName(str(userConfigPath)) |
| 922 |
|
| 923 |
|
| 924 |
@contextlib.contextmanager |
| 925 |
def tempConfig(*items): |
| 926 |
"""sets (sect, key, value) pairs in the config temporarily and re-sets |
| 927 |
the original values after the controlled block. |
| 928 |
""" |
| 929 |
origValues = [] |
| 930 |
for sect, key, val in items: |
| 931 |
origValues.append((sect, key, config.get(sect, key))) |
| 932 |
config.set(sect, key, val) |
| 933 |
|
| 934 |
try: |
| 935 |
yield |
| 936 |
finally: |
| 937 |
for sect, key, val in origValues: |
| 938 |
config.getitem(sect, key).value = val |
| 939 |
|
| 940 |
|
| 941 |
@contextlib.contextmanager |
| 942 |
def forceConnection(conn): |
| 943 |
"""makes the sqlsupport connection context managers return conn |
| 944 |
in the controlled block. |
| 945 |
|
| 946 |
It is up to the programmer to make sure that actually makes sense |
| 947 |
in a given test. As opposed to the originals, there will be no |
| 948 |
automatic commits here. Caveat emptor. |
| 949 |
""" |
| 950 |
symbols = ["getUntrustedConn", "getTableConn", "getAdminConn", |
| 951 |
"getWritableUntrustedConn", "getWritableTableConn", "getWritableAdminConn"] |
| 952 |
|
| 953 |
def _(): |
| 954 |
yield conn |
| 955 |
cm = contextlib.contextmanager(_) |
| 956 |
|
| 957 |
originals = [] |
| 958 |
for sym in symbols: |
| 959 |
originals.append(getattr(sqlsupport, sym)) |
| 960 |
setattr(sqlsupport, sym, cm) |
| 961 |
|
| 962 |
try: |
| 963 |
yield |
| 964 |
finally: |
| 965 |
originals.reverse() |
| 966 |
for sym in symbols: |
| 967 |
originals.append(getattr(sqlsupport, sym)) |
| 968 |
setattr(sqlsupport, sym, originals.pop()) |
| 969 |
|
| 970 |
|
| 971 |
def main(testClass, methodPrefix=None): |
| 972 |
ensureResources() |
| 973 |
|
| 974 |
if os.environ.get("GAVO_LOG")!="no": |
| 975 |
base.DEBUG = True |
| 976 |
from gavo.user import logui |
| 977 |
logui.LoggingUI(base.ui) |
| 978 |
|
| 979 |
# we used to auto-upgrade the environment here. That was a drag in |
| 980 |
# terms of runtime for simple tests, and I'd say an explicit testgavo |
| 981 |
# upgrade is even preferable. The last commit that had that was |
| 982 |
# e2471d548 |
| 983 |
|
| 984 |
className, methodPrefix = None, None |
| 985 |
try: |
| 986 |
# two args: first one is class name, locate it in caller's globals |
| 987 |
# and ignore anything before any dot for cut'n'paste convenience |
| 988 |
if len(sys.argv)==3: |
| 989 |
className = sys.argv[1].split(".")[-1] |
| 990 |
methodPrefix = sys.argv[2] |
| 991 |
|
| 992 |
# one arg: dissect dots and decide what to do then |
| 993 |
elif len(sys.argv)==2: |
| 994 |
parts = sys.argv[1].split(".") |
| 995 |
if len(parts)==3: |
| 996 |
className, methodPrefix = parts[1:] |
| 997 |
elif len(parts)==2: |
| 998 |
className, methodPrefix = parts |
| 999 |
elif len(parts)==1: |
| 1000 |
className = parts[0] |
| 1001 |
else: |
| 1002 |
sys.exit(f"{className}?") |
| 1003 |
|
| 1004 |
elif len(sys.argv)==1: |
| 1005 |
pass |
| 1006 |
|
| 1007 |
else: |
| 1008 |
sys.exit("usage: test-id or class-name test-prefix") |
| 1009 |
|
| 1010 |
if className is None: |
| 1011 |
suite = testresources.TestLoader().loadTestsFromModule( |
| 1012 |
sys.modules["__main__"]) |
| 1013 |
else: |
| 1014 |
testClass = getattr(sys.modules["__main__"], className) |
| 1015 |
loader = testresources.TestLoader() |
| 1016 |
loader.testMethodPrefix = methodPrefix or "test" |
| 1017 |
suite = loader.loadTestsFromTestCase(testClass) |
| 1018 |
|
| 1019 |
runner = unittest.TextTestRunner( |
| 1020 |
verbosity=int(os.environ.get("TEST_VERBOSITY", 1))) |
| 1021 |
|
| 1022 |
result = runner.run(suite) |
| 1023 |
|
| 1024 |
if result.errors or result.failures: |
| 1025 |
sys.exit(1) |
| 1026 |
else: |
| 1027 |
sys.exit(0) |
| 1028 |
except (SystemExit, KeyboardInterrupt): |
| 1029 |
raise |
| 1030 |
except: |
| 1031 |
base.showHints = True |
| 1032 |
from gavo.user import errhandle |
| 1033 |
traceback.print_exc() |
| 1034 |
errhandle.raiseAndCatch(base) |
| 1035 |
sys.exit(1) |