Debian Codegraph @

gavo/helpers/trialhelpers.py

raw
1 """
2 Helpers for trial-based tests, in particular retrieving pages.
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 functools
12 import os
13
14 from twisted.python import failure #noflake: exported name
15
16 from gavo.helpers.testhelpers import ( #noflake: exported names
17 getTestRD, DataServer, getXMLTree, tempConfig, testFile)
18
19 from gavo import base
20 base.setConfig("web", "enabletests", "True")
21
22 from gavo import rsc
23 from gavo.formal import testing
24 from gavo import svcs
25 from gavo import web
26 from gavo.helpers import testtricks
27 from gavo.web import common as webcommon
28 from gavo.web import root
29 from gavo.formal.testing import ( #noflake: exported names
30 RenderTest, assertHasStrings)
31
32
33 class ArchiveTest(RenderTest):
34 """the main class for writing trial-based tests in DaCHS.
35
36 It comes preconfigured to handle URLs as the running server and will
37 return roughly the same error responses.
38
39 It also has a method to XSD-validate documents against DaCHS' built-in
40 schemas.
41 """
42 renderer = root.ArchiveService()
43 errorHandler = staticmethod(webcommon.produceErrorDocument)
44
45 def assertResponseIsValid(self, res):
46 errs = testtricks.getXSDErrors(res[0], True)
47 if errs:
48 with open("remote.data", "wb") as f:
49 f.write(res[0])
50 raise AssertionError(errs)
51
52
53 @functools.lru_cache(1)
54 def getImportConnection():
55 # we cannot use the connection pools here since they may create threads.
56 return base.getDBConnection("admin")
57
58
59 def provideRDData(rdName, ddId, _imported=set()):
60 """makes ddId from rdName and returns a cleanup function.
61
62 This is for creating temporary data for tests; it's supposed to be used
63 as in::
64
65 atexit.register(provideRDData("test", "import_fitsprod"))
66
67 This keeps track of (rdName, ddId) pairs it's already loaded and
68 doesn't import them again.
69 """
70 if (rdName, ddId) in _imported:
71 return lambda: None
72
73 dd = getTestRD(rdName).getById(ddId)
74 conn = getImportConnection()
75 dataCreated = rsc.makeData(dd, connection=conn)
76 conn.commit()
77 _imported.add((rdName, ddId))
78
79 # rsc may already be gone in atexit
80 nvArg = rsc.parseNonValidating
81
82 def cleanup():
83 dataCreated.dropTables(nvArg)
84
85 return cleanup
86
87
88 def makeRequestArgs(aDict=None, **kwargs):
89 """returns a request.args compatible dict form aDict.
90
91 In particular, simple values will be put into lists.
92 """
93 if aDict is None:
94 aDict = {}
95 aDict.update(kwargs)
96 return dict((k,v if isinstance(v, list) else [v])
97 for k, v in aDict.items())
98
99
100 class FakeRequest(testing.FakeRequest, web.Request):
101 # our request class has a few frills that we want to exercise, too,
102 # so we mix it into the standard fake request
103 class host:
104 host = 'this.is.no.ip.address'
105 testing.FakeRequest = FakeRequest
106
107 # for convenience, expose FakeFile, too
108 FakeFile = testing.FakeFile
109
110
111 def addCreds(request, user="testing", password="testing"):
112 # testhelpers sets up testing in the users table
113 request.user = user
114 request.password = password
115
116
117 def runSvcWith(service, renderer, args, reqargs={}):
118 """runs svc through renderers, passing a dict args.
119
120 args maps to single values, *not* to lists as in t.w. Unless, of course,
121 you actually have lists to begin with.
122 """
123 req = FakeRequest(args=args, **reqargs)
124 queryMeta = svcs.QueryMeta.fromRequest(req)
125 return service.run(renderer, args, queryMeta)
126
127
128 runQuery = functools.partial(testing.runQuery,
129 produceErrorDocument=webcommon.produceErrorDocument)
130
131
132 if os.environ.get("GAVO_LOG")!="no":
133 from gavo.user import logui
134 logui.LoggingUI(base.ui)