Debian Codegraph @

tests/runAllTests.py

raw
1 """
2 Runs all unit tests defined for DaCHS.
3
4 This script *asssumes* it is run from tests subdirectory of the code
5 tree and silently won't work (properly) otherwise.
6
7 If ran with no arguments, it executes the tests from the current directory
8 and then tries to locate further, data-specific unit test suites.
9
10 If ran with the single argument "data", the program will read
11 $GAVO_INPUTS/__tests/__unitpaths__, interpret each line as a
12 inputs-relative directory name and run out-of-tree unittests there.
13
14 Location of unit tests: pyunit-based test suites are files matching
15 *test.py, trial-based suites are found by looking for test_*.py.
16 """
17
18 #c Copyright 2008-2025, the GAVO project <[email protected]>
19 #c
20 #c This program is free software, covered by the GNU GPL. See the
21 #c COPYING file in the source distribution.
22
23
24 import os
25 import sys
26
27 if len(sys.argv)==1:
28 pass
29 elif len(sys.argv)==2 and sys.argv[1]=="data":
30 os.environ["GAVO_OOTTEST"] = "dontcare"
31 else:
32 raise sys.exit(
33 '%s takes zero arguments or just "data"'%sys.argv[0])
34
35 os.environ["GAVO_LOG"] = "no"
36
37 import unittest
38 import doctest
39 import glob
40 import subprocess
41
42
43 from gavo.helpers import testhelpers
44
45 import testresources
46
47 from gavo import base
48
49
50 def hasDoctest(fName):
51 f = open(fName, "rb")
52 tx = f.read()
53 f.close()
54 return b"doctest.testmod" in tx
55
56
57 def getDoctests():
58 doctests = []
59 for dir, dirs, names in os.walk("../gavo"):
60 parts = dir.split("/")[1:]
61 for name in [n for n in names if n.endswith(".py")]:
62 try:
63 if hasDoctest(os.path.join(dir, name)):
64 name = ".".join(parts+[name[:-3]])
65 doctests.append(doctest.DocTestSuite(name))
66 except Exception:
67 sys.stderr.write("*** While collecting doctests from %s:\n\n"%
68 os.path.join(dir, name))
69 raise
70 return unittest.TestSuite(doctests)
71
72
73 def runTrialTests():
74 """runs trial-based tests, suppressing output, but raising an error if
75 any of the tests failed.
76 """
77 try:
78 del os.environ["GAVO_INPUTSDIR"]
79 except KeyError:
80 pass
81 trialTests = glob.glob("test_*.py")
82 if trialTests:
83 print("\nTrial-based tests:")
84
85 args = ["-m", "twisted.trial", "--reporter", "text"
86 ]+[n[:-3] for n in trialTests]
87
88 if "COVERAGE_FILE" in os.environ:
89 os.environ["COVERAGE_FILE"] = "trial.cov"
90 executor = ["python3-coverage", "run", "--source", "gavo"]
91 # TODO: I think there's a pyannotate command line thingy that
92 # we could run here as in python3-coverage. However, merging
93 # the two annotations doesn't look trivial, so I'm skipping this
94 # for now.
95 else:
96 executor = ["python3"]
97
98 subprocess.call(executor+args)
99
100
101 def runAllTests(includeDoctests=True):
102 testhelpers.ensureResources()
103 pyunitSuite = testresources.TestLoader().loadTestsFromNames(
104 [n[:-3] for n in glob.glob("*test.py")])
105 runner = unittest.TextTestRunner(
106 verbosity=int(os.environ.get("TEST_VERBOSITY", 1)))
107 if includeDoctests:
108 pyunitSuite = unittest.TestSuite([pyunitSuite, getDoctests()])
109 runner.run(pyunitSuite)
110 runTrialTests()
111
112
113 def runDataTests():
114 """reads directory names from __tests/__unitpaths__ and then runs
115 tests defined there.
116 """
117 inputsDir = base.getConfig("inputsDir")
118 dirFile = os.path.join(inputsDir, "__tests", "__unitpaths__")
119 if not os.path.exists(dirFile):
120 return
121 with open(dirFile) as f:
122 for dirName in f:
123 dirName = dirName.strip()
124 if dirName and not dirName.startswith("#"):
125 os.chdir(os.path.join(inputsDir, dirName))
126 curDir = os.getcwd()
127 sys.path[0:0] = [curDir]
128
129 print("\n\nTests from %s:\n\n"%dirName)
130 runAllTests(includeDoctests=False)
131 sys.path.remove(curDir)
132
133
134 def typesFilenameFilter(filename):
135 """normalises filename for pyannotate.
136
137 That's None if the things shouldn't filter in the first place, a
138 package-relative path.
139
140 (actually, we're just looking for the last "gavo" in the path, but that
141 should usually work well enough).
142 """
143 if filename not in typesFilenameFilter.knownFiles:
144 normalised = []
145 for part in reversed(filename.split("/")):
146 if part=="gavo":
147 typesPath = "/".join(reversed(normalised))
148 break
149 normalised.append(part)
150 else:
151 typesPath = None
152
153 typesFilenameFilter.knownFiles[filename] = typesPath
154
155 return typesFilenameFilter.knownFiles[filename]
156
157 typesFilenameFilter.knownFiles = {}
158
159
160 if __name__=="__main__":
161 base.DEBUG = False
162
163 if len(sys.argv)==1:
164 TYPE_STATS = os.environ.get("TYPE_STATS")
165 if TYPE_STATS:
166 from pyannotate_runtime import collect_types
167 collect_types.init_types_collection(typesFilenameFilter)
168 collect_types.collect()
169 collect_types.start()
170
171 try:
172 runAllTests()
173 finally:
174 if TYPE_STATS:
175 collect_types.stop()
176 collect_types.dump_stats(TYPE_STATS)
177
178 # Restart to let data tests run in non-testing environment.
179 # We have to do that because data test don't sit in the test
180 # inputs, and we can't really put them there. Of course, that
181 # lets unit tests ruin production data if worse comes to worst.
182 subprocess.check_call(["python3", "runAllTests.py", "data"],
183 env=testhelpers.originalEnvironment)
184
185 elif sys.argv[1]=="data":
186 runDataTests()
187
188 else:
189 sys.exit(f"Can't recognise arguments: {sys.argv}")