| 1 |
""" |
| 2 |
Helpers for testing code using gavo.formal |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import io |
| 12 |
import math |
| 13 |
|
| 14 |
from twisted.internet import defer |
| 15 |
from twisted.python import failure |
| 16 |
from twisted.python import urlpath |
| 17 |
from twisted.trial.unittest import TestCase as TrialTest |
| 18 |
from twisted.web import http |
| 19 |
from twisted.web import resource |
| 20 |
from twisted.web import server |
| 21 |
from twisted.web.test.requesthelper import DummyRequest |
| 22 |
|
| 23 |
|
| 24 |
def debug(arg): |
| 25 |
import pdb; pdb.set_trace() |
| 26 |
return arg |
| 27 |
|
| 28 |
|
| 29 |
def bytify(s): |
| 30 |
"""returns s utf-8 encoded if it is a string, unmodified otherwise. |
| 31 |
""" |
| 32 |
if isinstance(s, str): |
| 33 |
return s.encode("utf-8") |
| 34 |
return s |
| 35 |
|
| 36 |
|
| 37 |
def debytify(b): |
| 38 |
"""returns b utf-8 decoded if it is bytes, unmodified otherwise. |
| 39 |
""" |
| 40 |
if isinstance(b, bytes): |
| 41 |
return b.decode("utf-8") |
| 42 |
return b |
| 43 |
|
| 44 |
|
| 45 |
def assertHasStrings(content, strings, inverse=False): |
| 46 |
"""asserts that all strings in the list strings are in content. |
| 47 |
|
| 48 |
If inverse is True, it asserts the strings are not in content. |
| 49 |
|
| 50 |
For generality, both content and strings will be bytified if they're |
| 51 |
not bytes already, and only then compared. |
| 52 |
|
| 53 |
When the assertion fails, the bytified content will be dumped to a |
| 54 |
file remote.data in the current directory. |
| 55 |
""" |
| 56 |
content = bytify(content) |
| 57 |
try: |
| 58 |
for s in strings: |
| 59 |
if inverse: |
| 60 |
assert bytify(s) not in content, f"'{s}' in remote.data" |
| 61 |
else: |
| 62 |
assert bytify(s) in content, f"'{s}' not in remote.data" |
| 63 |
except AssertionError: |
| 64 |
with open("remote.data", "wb") as f: |
| 65 |
f.write(content) |
| 66 |
raise |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
def raiseException(failure): |
| 71 |
failure.raiseException() |
| 72 |
|
| 73 |
|
| 74 |
def bytify_seq(s): |
| 75 |
"""returns a list from s with any elements bytified. |
| 76 |
|
| 77 |
s must be a sequence or None. Oh, for convenience we also accept plain |
| 78 |
bytes and strings. |
| 79 |
""" |
| 80 |
if s is None: |
| 81 |
return None |
| 82 |
if isinstance(s, (bytes, str)): |
| 83 |
s = [s] |
| 84 |
if not isinstance(s, (list, tuple)): |
| 85 |
raise Exception("bytify_seq really wants a sequence, not %s"%repr(s)) |
| 86 |
return [bytify(item) for item in s] |
| 87 |
|
| 88 |
|
| 89 |
class FakeFile: |
| 90 |
"""a fake file upload. |
| 91 |
|
| 92 |
Construct this with a file name and a payload, both of which can be |
| 93 |
bytes or str (which will be utf-8-encoded). |
| 94 |
""" |
| 95 |
def __init__(self, file_name, payload): |
| 96 |
self.file_name = bytify(file_name) |
| 97 |
self.file_object = io.BytesIO(bytify(payload)) |
| 98 |
|
| 99 |
|
| 100 |
class FakeRequest(DummyRequest): |
| 101 |
"""A request for test purposes. |
| 102 |
|
| 103 |
We furnish t.w's DummyRequest with some extra facilities to let us |
| 104 |
be a bit lazy in having rather macro tests. |
| 105 |
|
| 106 |
Also, stock twisted DummyRequest produces an endless loop with push |
| 107 |
producers (which is what we have), so we fix that, too. |
| 108 |
|
| 109 |
You can pass in args as a str -> str mapping; the strings will be |
| 110 |
encoded as utf-8 so request.args is bytes -> [bytes]. For |
| 111 |
convenience, we'll turn single values to lists. |
| 112 |
|
| 113 |
For uploads, you can pass (single) args with FakeFile-valued arguments. |
| 114 |
""" |
| 115 |
|
| 116 |
method = b"GET" |
| 117 |
session = None |
| 118 |
startedWriting = 0 |
| 119 |
|
| 120 |
# some code tests for a live connection using client |
| 121 |
client = True |
| 122 |
|
| 123 |
def __init__(self, uri=b'', headers=None, args=None, avatar=None, |
| 124 |
currentSegments=None, cookies=None, |
| 125 |
user="", password="", isSecure=False): |
| 126 |
uri = bytify(uri) |
| 127 |
if uri.startswith(b"/"): |
| 128 |
uri = uri[1:] |
| 129 |
postpath = [] |
| 130 |
if uri: |
| 131 |
postpath = uri.split(b"/") |
| 132 |
|
| 133 |
DummyRequest.__init__(self, uri) |
| 134 |
|
| 135 |
self.files, self.args = {}, {} |
| 136 |
if args: |
| 137 |
for k,v in args.items(): |
| 138 |
if isinstance(v, FakeFile): |
| 139 |
self.files[debytify(k)] = [v] |
| 140 |
|
| 141 |
else: |
| 142 |
self.args[bytify(k)] = bytify_seq(v) |
| 143 |
else: |
| 144 |
self.args = {} |
| 145 |
|
| 146 |
self.uri = uri |
| 147 |
self.postpath = postpath |
| 148 |
self.code = 200 |
| 149 |
self.user, self.password = user, password |
| 150 |
self.deferred = defer.Deferred() |
| 151 |
self.accumulator = b"" |
| 152 |
self.prepath = [] |
| 153 |
self.finished = False |
| 154 |
self.secure = False |
| 155 |
self.channel = 1 # must be non-None for custom hangup detection |
| 156 |
self.lastModified = None |
| 157 |
|
| 158 |
def setPayload(self, payload, mediaType): |
| 159 |
# payload needs to be a file |
| 160 |
self.content = payload |
| 161 |
self.requestHeaders.addRawHeader("content-type", mediaType) |
| 162 |
|
| 163 |
def setHeader(self, name, value): |
| 164 |
# overridden because t.w.t doesn't overwrite |
| 165 |
self.responseHeaders.setRawHeaders(name, [value]) |
| 166 |
|
| 167 |
def write(self, data): |
| 168 |
if not self.startedWriting: |
| 169 |
if self.lastModified is not None: |
| 170 |
self.responseHeaders.setRawHeaders( |
| 171 |
b"last-modified", |
| 172 |
[http.datetimeToString(self.lastModified)]) |
| 173 |
self.startedWriting = True |
| 174 |
|
| 175 |
self.accumulator += bytify(data) |
| 176 |
|
| 177 |
def notifyFinish(self): |
| 178 |
return self.deferred |
| 179 |
|
| 180 |
def prePathURL(self): |
| 181 |
return 'http://%s/%s'%(self.getHost(), '/'.join(self.prepath)) |
| 182 |
|
| 183 |
def setLastModified(self, when): |
| 184 |
# copied from twisted.web.server.Request |
| 185 |
when = int(math.ceil(when)) |
| 186 |
if (not self.lastModified) or (self.lastModified < when): |
| 187 |
self.lastModified = when |
| 188 |
|
| 189 |
modifiedSince = self.getHeader(b"if-modified-since") |
| 190 |
if modifiedSince: |
| 191 |
firstPart = modifiedSince.split(b";", 1)[0] |
| 192 |
try: |
| 193 |
modifiedSince = http.stringToDatetime(firstPart) |
| 194 |
except ValueError: |
| 195 |
return None |
| 196 |
if modifiedSince >= self.lastModified: |
| 197 |
self.setResponseCode(http.NOT_MODIFIED) |
| 198 |
return http.CACHED |
| 199 |
return None |
| 200 |
|
| 201 |
def finish(self): |
| 202 |
self.finished = True |
| 203 |
self.deferred.callback((self.accumulator, self)) |
| 204 |
|
| 205 |
def finishCallback(self, arg): |
| 206 |
if isinstance(arg, failure.Failure): |
| 207 |
arg.raiseException() |
| 208 |
if not self.finished: |
| 209 |
self.finish() |
| 210 |
|
| 211 |
def setHost(self, host, port): |
| 212 |
self.host = host |
| 213 |
|
| 214 |
def getHost(self): |
| 215 |
return self.host |
| 216 |
|
| 217 |
def setResponseCode(self, code): |
| 218 |
self.code = code |
| 219 |
|
| 220 |
def URLPath(self): |
| 221 |
return urlpath.URLPath.fromString(self.path.decode("utf-8")) |
| 222 |
|
| 223 |
@property |
| 224 |
def path(self): |
| 225 |
return self.uri |
| 226 |
|
| 227 |
def isSecure(self): |
| 228 |
return self.secure |
| 229 |
|
| 230 |
def getLocationValue(self): |
| 231 |
"""returns a location header if this requests redirects, and raises |
| 232 |
an AssertionError otherwise. |
| 233 |
""" |
| 234 |
if not self.code or self.code//100!=3: |
| 235 |
raise AssertionError("Trying to get a redirection target for" |
| 236 |
" request with status %s"%self.code) |
| 237 |
|
| 238 |
return self.getResponseHeader("location") |
| 239 |
|
| 240 |
def processWithRoot(self, page): |
| 241 |
"""runs this request on page. |
| 242 |
|
| 243 |
This is probably a bad idea all around, and we should just be using |
| 244 |
trial. But since sync tests are quite a bit more convenient, |
| 245 |
here this is. Of course, it only works if resource effectively |
| 246 |
renders sync (or has a renderSync method). |
| 247 |
""" |
| 248 |
rsc = resource.getChildForRequest(page, self) |
| 249 |
|
| 250 |
res = getattr(rsc, "renderSync", rsc.render)(self) |
| 251 |
if res: |
| 252 |
if isinstance(res, int) and res==server.NOT_DONE_YET: |
| 253 |
# this will only work if the thing is actually sync. |
| 254 |
# see servicetest._syncvosi for an inspration there. |
| 255 |
# But in that case, accumulator will have it all. |
| 256 |
pass |
| 257 |
else: |
| 258 |
return res |
| 259 |
|
| 260 |
return self.accumulator |
| 261 |
|
| 262 |
def registerProducer(self, producer, isPush): |
| 263 |
self.producer = producer |
| 264 |
if not isPush: |
| 265 |
DummyRequest.registerProducer( |
| 266 |
self, producer, isPush) |
| 267 |
|
| 268 |
def unregisterProducer(self): |
| 269 |
# stop twisted pull producers, too |
| 270 |
self.go = 0 |
| 271 |
self.channel = None |
| 272 |
del self.producer |
| 273 |
|
| 274 |
def getResponseHeader(self, headerName): |
| 275 |
return self.responseHeaders.getRawHeaders(headerName, [None])[0] |
| 276 |
|
| 277 |
def addUpload(self, name, content): |
| 278 |
self.files.setdefault(name, []).append( |
| 279 |
FakeFile(name, content)) |
| 280 |
|
| 281 |
|
| 282 |
def _doRender(page, request): |
| 283 |
result = page.render(request) |
| 284 |
|
| 285 |
if isinstance(result, int) and result==server.NOT_DONE_YET: |
| 286 |
# the thing is set up in a way that eventually some deferred |
| 287 |
# will fire and complete |
| 288 |
return request.deferred |
| 289 |
|
| 290 |
elif isinstance(result, bytes): |
| 291 |
request.write(result) |
| 292 |
request.finish() |
| 293 |
return request.deferred |
| 294 |
|
| 295 |
else: |
| 296 |
raise Exception("Unsupported render result: %s"%repr(result)) |
| 297 |
|
| 298 |
|
| 299 |
def _buildRequest( |
| 300 |
method, |
| 301 |
path, |
| 302 |
args, |
| 303 |
moreHeaders=None, |
| 304 |
requestClass=None): |
| 305 |
if requestClass is None: |
| 306 |
requestClass = FakeRequest |
| 307 |
req = requestClass(path, args=args) |
| 308 |
|
| 309 |
req.headers = {} |
| 310 |
if moreHeaders: |
| 311 |
for k, v in moreHeaders.items(): |
| 312 |
req.requestHeaders.setRawHeaders(k, [v]) |
| 313 |
|
| 314 |
req.method = bytify(method) |
| 315 |
return req |
| 316 |
|
| 317 |
|
| 318 |
def runQuery(page, |
| 319 |
method, |
| 320 |
path, |
| 321 |
args, |
| 322 |
moreHeaders=None, |
| 323 |
requestMogrifier=None, |
| 324 |
requestClass=None, |
| 325 |
produceErrorDocument=None): |
| 326 |
"""runs a query on a page. |
| 327 |
|
| 328 |
The query should look like it's coming from localhost. |
| 329 |
|
| 330 |
The thing returns a deferred firing a pair of the result (a string) |
| 331 |
and the request (from which you can glean headers and such). |
| 332 |
|
| 333 |
errorHandler must be a callable accepting a failure and the request |
| 334 |
if you want to exercise your error handling, too. If you don't |
| 335 |
pass it in, exceptions during request handling will be re-raised. |
| 336 |
""" |
| 337 |
req = _buildRequest( |
| 338 |
method, path, args, moreHeaders=moreHeaders, requestClass=requestClass) |
| 339 |
if requestMogrifier is not None: |
| 340 |
requestMogrifier(req) |
| 341 |
|
| 342 |
try: |
| 343 |
rsc = resource.getChildForRequest(page, req) |
| 344 |
return _doRender(rsc, req) |
| 345 |
except Exception as ex: |
| 346 |
if produceErrorDocument: |
| 347 |
produceErrorDocument(failure.Failure(ex), req) |
| 348 |
return req.deferred |
| 349 |
raise |
| 350 |
|
| 351 |
|
| 352 |
class RenderTest(TrialTest): |
| 353 |
"""a base class for tests of twisted web resources. |
| 354 |
""" |
| 355 |
renderer = None # Override with the resource to be tested. |
| 356 |
errorHandler = None # override with a runQuery produceErrorDocument |
| 357 |
runQuery = staticmethod(runQuery) |
| 358 |
|
| 359 |
def assertStringsIn(self, result, strings, inverse=False, |
| 360 |
customTest=None): |
| 361 |
# this wraps testhelpers.assertHasStrings to work better with |
| 362 |
# twisted results; in particular, we need to return the result. |
| 363 |
content = result[0] |
| 364 |
assertHasStrings(content, strings, inverse) |
| 365 |
try: |
| 366 |
if customTest is not None: |
| 367 |
customTest(content) |
| 368 |
except AssertionError: |
| 369 |
with open("remote.data", "wb") as f: |
| 370 |
f.write(content) |
| 371 |
raise |
| 372 |
return result |
| 373 |
|
| 374 |
def assertResultHasStrings(self, method, path, args, strings, |
| 375 |
rm=None, inverse=False, customTest=None): |
| 376 |
return self.runQuery( |
| 377 |
self.renderer, method, |
| 378 |
path, args, |
| 379 |
requestMogrifier=rm, |
| 380 |
produceErrorDocument=self.errorHandler |
| 381 |
).addCallback(self.assertStringsIn, strings, inverse=inverse, |
| 382 |
customTest=customTest) |
| 383 |
|
| 384 |
def assertGETHasStrings(self, path, args, strings, rm=None, |
| 385 |
customTest=None): |
| 386 |
return self.assertResultHasStrings("GET", |
| 387 |
path, args, strings, rm=rm, customTest=customTest) |
| 388 |
|
| 389 |
def assertGETLacksStrings(self, path, args, strings, rm=None): |
| 390 |
return self.assertResultHasStrings("GET", |
| 391 |
path, args, strings, rm=rm, inverse=True) |
| 392 |
|
| 393 |
def assertPOSTHasStrings(self, path, args, strings, rm=None): |
| 394 |
return self.assertResultHasStrings("POST", path, args, strings, |
| 395 |
rm=rm) |
| 396 |
|
| 397 |
def assertStatus(self, path, status, args={}, rm=None): |
| 398 |
def check(res): |
| 399 |
self.assertEqual(res[1].code, status) |
| 400 |
return res |
| 401 |
return self.runQuery( |
| 402 |
self.renderer, "GET", |
| 403 |
path, args, |
| 404 |
requestMogrifier=rm, |
| 405 |
produceErrorDocument=self.errorHandler |
| 406 |
).addCallback(check) |
| 407 |
|
| 408 |
def assertGETRaises(self, path, args, exc, alsoCheck=None): |
| 409 |
def cb(res): |
| 410 |
raise AssertionError("%s not raised (returned %s instead)"%( |
| 411 |
exc, res)) |
| 412 |
def eb(flr): |
| 413 |
flr.trap(exc) |
| 414 |
if alsoCheck is not None: |
| 415 |
alsoCheck(flr) |
| 416 |
|
| 417 |
return self.runQuery(self.renderer, "GET", |
| 418 |
path, args, |
| 419 |
produceErrorDocument=self.errorHandler |
| 420 |
).addCallback(cb |
| 421 |
).addErrback(eb) |
| 422 |
|
| 423 |
def assertGETIsValid(self, path, args={}): |
| 424 |
return self.runQuery(self.renderer, "GET", |
| 425 |
path, args, |
| 426 |
produceErrorDocument=self.errorHandler |
| 427 |
).addCallback(self.assertResponseIsValid) |