forked from curl/trurl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
209 lines (175 loc) · 7.03 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
import sys
from os import getcwd, path
import re
import json
import shlex
from subprocess import PIPE, run
from dataclasses import dataclass, asdict
from typing import Any, Optional
from packaging.version import parse as parse_version
PROGNAME = "trurl"
TESTFILE = "tests.json"
VALGRINDTEST = "valgrind"
VALGRINDARGS = ["--error-exitcode=1", "--leak-check=full", "-q"]
RED = "\033[91m" # used to mark unsuccessful tests
NOCOLOR = "\033[0m"
@dataclass
class CommandOutput:
stdout: Any
returncode: int
stderr: str
class TestCase:
def __init__(self, testIndex, baseCmd, **testCase):
self.testIndex = testIndex
self.baseCmd = baseCmd
self.arguments = testCase["input"]["arguments"]
self.expected = testCase["expected"]
self.commandOutput: CommandOutput = None
self.testPassed: bool = False
def runCommand(self, cmdfilter: Optional[str], runWithValgrind: bool):
# Skip test if none of the arguments contain the keyword
if cmdfilter and all(cmdfilter not in arg for arg in self.arguments):
return False
cmd = [self.baseCmd]
args = self.arguments
if runWithValgrind:
cmd = [VALGRINDTEST]
args = VALGRINDARGS + [self.baseCmd] + self.arguments
output = run(
cmd + args,
stdout=PIPE, stderr=PIPE,
encoding="utf-8"
)
if type(self.expected["stdout"]) == str:
stdout = output.stdout
else:
# if we dont expect string, parse to json
try:
stdout = json.loads(output.stdout)
except json.decoder.JSONDecodeError:
stdout = None
# assume stderr is always going to be string
stderr = output.stderr
self.commandOutput = CommandOutput(stdout, output.returncode, stderr)
return True
def test(self):
# return true only if stdout, stderr and errorcode is equal to the ones found in testfile
tests = []
for item in self.expected:
passed = self.expected[item] == asdict(self.commandOutput)[item]
tests.append(passed)
self.testPassed = all(tests)
return self.testPassed
def printVerbose(self):
print(RED, end="")
self.printConcise()
print(NOCOLOR, end="")
for item in self.expected:
itemFail = self.expected[item] != asdict(self.commandOutput)[item]\
and self.commandOutput.returncode == 1
print(f"--- {item} --- ")
print("expected:")
print(f"{self.expected[item]!r}")
print("got:")
if itemFail:
print(RED, end="")
print(f"{asdict(self.commandOutput)[item]!r}")
if itemFail:
print(NOCOLOR, end="")
print()
def printConcise(self):
result = 'passed' if self.testPassed else 'failed'
print(f"{self.testIndex}: {result}\t{shlex.join(self.arguments)}")
def main(argc, argv):
ret = 0
baseDir = path.dirname(path.realpath(argv[0]))
# python on windows does not always seem to find the
# executable if it is in a different output directory than
# the python script, even if it is in the current working
# directory, using absolute paths to the executable and json
# file makes it reliably find the executable
baseCmd = path.join(getcwd(), PROGNAME)
# the .exe on the end is necessary when using absolute paths
if sys.platform == "win32" or sys.platform == "cygwin":
baseCmd += ".exe"
# check if the trurl executable exists
if path.isfile(baseCmd):
# get the run-time and build-time libcurl versions
output = run(
[baseCmd, "--version"],
stdout=PIPE, stderr=PIPE,
encoding="utf-8"
)
version_re = r' libcurl\/([\w\.\-]+) \[built\-with ([\w\.\-]+)\]$'
match = re.findall(version_re, output.stdout)
libcurl_runtime, libcurl_buildtime = match[0]
libcurl_runtime = parse_version(libcurl_runtime)
libcurl_buildtime = parse_version(libcurl_buildtime)
with open(path.join(baseDir, TESTFILE), "r") as file:
allTests = json.load(file)
testIndexesToRun = []
# if argv[1] exists and starts with int
cmdfilter = ""
testIndexesToRun = list(range(len(allTests)))
runWithValgrind = False
if argc > 1:
for arg in argv[1:]:
if arg[0].isnumeric():
# run only test cases separated by ","
testIndexesToRun = []
for caseIndex in arg.split(","):
testIndexesToRun.append(int(caseIndex))
elif arg == "--with-valgrind":
runWithValgrind = True
else:
cmdfilter = argv[1]
numTestsFailed = 0
numTestsPassed = 0
numTestsSkipped = 0
for testIndex in testIndexesToRun:
# skip tests if the run-time libcurl version is too low
if "minruntime" in allTests[testIndex]:
minruntime = allTests[testIndex]["minruntime"]
minruntime = parse_version(minruntime)
if libcurl_runtime < minruntime:
skipMessage = "libcurl run-time version is too low: "
skipMessage += f"{libcurl_runtime} < {minruntime}"
print(f"{testIndex + 1}: skipped\t{skipMessage}")
numTestsSkipped += 1
continue
# skip tests if the build-time libcurl version is too low
if "minbuildtime" in allTests[testIndex]:
minbuildtime = allTests[testIndex]["minbuildtime"]
minbuildtime = parse_version(minbuildtime)
if libcurl_buildtime < minbuildtime:
skipMessage = "libcurl build-time version is too low: "
skipMessage += f"{libcurl_buildtime} < {minbuildtime}"
print(f"{testIndex + 1}: skipped\t{skipMessage}")
numTestsSkipped += 1
continue
test = TestCase(testIndex + 1, baseCmd, **allTests[testIndex])
if test.runCommand(cmdfilter, runWithValgrind):
if test.test(): # passed
test.printConcise()
numTestsPassed += 1
else:
test.printVerbose()
numTestsFailed += 1
# finally print the results to terminal
print("Finished:")
result = ", ".join([
f"Failed: {numTestsFailed}",
f"Passed: {numTestsPassed}",
f"Skipped: {numTestsSkipped}",
f"Total: {len(testIndexesToRun)}"
])
if (numTestsFailed == 0):
print("Passed! - ", result)
else:
ret = f"Failed! - {result}"
else:
ret = f" error: File \"{baseCmd}\" not found!"
return ret
if __name__ == "__main__":
sys.exit(main(len(sys.argv), sys.argv))