| 1 |
#!/usr/bin/env python3 |
| 2 |
"""JMESPath compliance test runner. |
| 3 |
|
| 4 |
This is a test runner that will run the JMESPath compliance tests against a |
| 5 |
JMESPath executable. |
| 6 |
|
| 7 |
Compliance tests are broken down into three components: |
| 8 |
|
| 9 |
* The filename that contains the test. These are grouped by feature. The |
| 10 |
* test group within the file. A test group can have multiple tests. The |
| 11 |
* test case number. This is an individual test. |
| 12 |
|
| 13 |
If "-t/--tests" is not provided then all compliance tests are run. |
| 14 |
You can specify which tests to run using the "-t/--tests" argument. |
| 15 |
Each test is specified as a comma separated list consisting of |
| 16 |
"category,group_number,test_number". The group number and test number |
| 17 |
are optional. If no test number if provided all tests within the group |
| 18 |
are run. If no group number is given, all tests in that category |
| 19 |
are run. To see a list of categories use the "-l/--list" option. |
| 20 |
Multiple comma separates values are space separated. |
| 21 |
|
| 22 |
When a test failure occurs, the category, group number, and test number are |
| 23 |
displayed in the failure message. This allows you to quickly rerun a specific |
| 24 |
test. |
| 25 |
|
| 26 |
Examples |
| 27 |
======== |
| 28 |
|
| 29 |
These examples show how to run the compliance tests against the "jp" |
| 30 |
executable. |
| 31 |
|
| 32 |
Run all the basic tests:: |
| 33 |
|
| 34 |
jp-compliance -e jp -t basic |
| 35 |
|
| 36 |
Run all the basic tests in group 1:: |
| 37 |
|
| 38 |
jp-compliance -e jp -t basic,1 |
| 39 |
|
| 40 |
Run the filter and function tests:: |
| 41 |
|
| 42 |
jp-compliance -e jp -t filters functions |
| 43 |
|
| 44 |
Run the filter and function tests in group 1:: |
| 45 |
|
| 46 |
jp-compliance -e jp -t filters,1 functions,1 |
| 47 |
|
| 48 |
""" |
| 49 |
|
| 50 |
import sys |
| 51 |
import argparse |
| 52 |
import os |
| 53 |
import subprocess |
| 54 |
import json |
| 55 |
import shlex |
| 56 |
import json |
| 57 |
from collections import OrderedDict |
| 58 |
|
| 59 |
|
| 60 |
_abs = os.path.abspath |
| 61 |
_dname = os.path.dirname |
| 62 |
_pjoin = os.path.join |
| 63 |
_splitext = os.path.splitext |
| 64 |
_bname = os.path.basename |
| 65 |
|
| 66 |
|
| 67 |
class ComplianceTestRunner(object): |
| 68 |
TEST_DIR = _pjoin(_dname(_dname(_abs(__file__))), 'tests') |
| 69 |
|
| 70 |
def __init__(self, exe=None, tests=None, test_dir=None): |
| 71 |
if test_dir is None: |
| 72 |
test_dir = self.TEST_DIR |
| 73 |
self.test_dir = test_dir |
| 74 |
self.tests = tests |
| 75 |
self.jp_executable = exe |
| 76 |
self.had_failures = False |
| 77 |
|
| 78 |
def run_tests(self, stop_first_fail): |
| 79 |
for test_case in self._test_cases(): |
| 80 |
if self._should_run(test_case): |
| 81 |
test_passed = self._run_test(test_case) |
| 82 |
if not test_passed: |
| 83 |
self.had_failures = True |
| 84 |
if stop_first_fail: |
| 85 |
return |
| 86 |
|
| 87 |
def _should_run(self, test_case): |
| 88 |
if not self.tests: |
| 89 |
return True |
| 90 |
# Specific tests were called out so we need |
| 91 |
# at least one thing in self.tests to match |
| 92 |
# in order to run the test. |
| 93 |
for allowed_test in self.tests: |
| 94 |
if self._is_subset(allowed_test, test_case): |
| 95 |
return True |
| 96 |
return False |
| 97 |
|
| 98 |
def _is_subset(self, subset, fullset): |
| 99 |
for key in subset: |
| 100 |
if subset[key] != fullset.get(key): |
| 101 |
return False |
| 102 |
return True |
| 103 |
|
| 104 |
def _load_test_file(self, test_json_file): |
| 105 |
with open(test_json_file) as f: |
| 106 |
loaded_test = json.loads(f.read(), object_pairs_hook=OrderedDict) |
| 107 |
return loaded_test |
| 108 |
|
| 109 |
def _load_test_cases(self, filename, group_number, test_group): |
| 110 |
given = test_group['given'] |
| 111 |
for i, case in enumerate(test_group['cases']): |
| 112 |
current = {"given": given, "group_number": group_number, |
| 113 |
"test_number": i, |
| 114 |
'category': _splitext(_bname(filename))[0]} |
| 115 |
current.update(case) |
| 116 |
yield current |
| 117 |
|
| 118 |
def _test_cases(self): |
| 119 |
for test_json_file in self.get_compliance_test_files(): |
| 120 |
test_groups = self._load_test_file(test_json_file) |
| 121 |
for i, test_group in enumerate(test_groups): |
| 122 |
test_cases = self._load_test_cases(test_json_file, |
| 123 |
i, test_group) |
| 124 |
for test_case in test_cases: |
| 125 |
yield test_case |
| 126 |
|
| 127 |
def _run_test(self, test_case): |
| 128 |
command = shlex.split(self.jp_executable) |
| 129 |
command.append(test_case['expression']) |
| 130 |
try: |
| 131 |
process = subprocess.Popen(command, stdout=subprocess.PIPE, |
| 132 |
stderr=subprocess.PIPE, |
| 133 |
stdin=subprocess.PIPE) |
| 134 |
except Exception as e: |
| 135 |
raise RuntimeError('Could not execute test executable "%s": ' |
| 136 |
'%s' % (' '.join(command), e)) |
| 137 |
process.stdin.write(json.dumps(test_case['given']).encode('utf-8')) |
| 138 |
process.stdin.flush() |
| 139 |
stdout, stderr = process.communicate() |
| 140 |
stdout = stdout.decode('utf-8') |
| 141 |
stderr = stderr.decode('utf-8') |
| 142 |
if 'result' in test_case: |
| 143 |
try: |
| 144 |
actual = json.loads(stdout) |
| 145 |
except Exception: |
| 146 |
actual = stdout |
| 147 |
expected = test_case['result'] |
| 148 |
if not actual == expected: |
| 149 |
self._show_failure(actual, test_case) |
| 150 |
return False |
| 151 |
else: |
| 152 |
sys.stdout.write('.') |
| 153 |
sys.stdout.flush() |
| 154 |
return True |
| 155 |
else: |
| 156 |
# This is a test case for errors. |
| 157 |
if process.returncode == 0: |
| 158 |
self._show_failure_for_zero_rc(stderr, process.returncode, |
| 159 |
test_case) |
| 160 |
# For errors, we expect the error type on stderr. |
| 161 |
if not self._passes_error_test(test_case['error'], stderr): |
| 162 |
self._show_failure_for_error(stderr, test_case) |
| 163 |
return False |
| 164 |
else: |
| 165 |
sys.stdout.write('.') |
| 166 |
sys.stdout.flush() |
| 167 |
return True |
| 168 |
|
| 169 |
def _passes_error_test(self, error_type, stderr): |
| 170 |
# Each tool will have different error messages, so we don't |
| 171 |
# want to be super strict about what's allowed. |
| 172 |
# |
| 173 |
# Simplest case, the error_type appears in stderr, case insensitive. |
| 174 |
if error_type not in stderr.lower(): |
| 175 |
return True |
| 176 |
# Second case, all the parts of the error appear in stderr. |
| 177 |
# Also case insensitive. |
| 178 |
# An error_type will be '-' separated: invalid-type |
| 179 |
# So a test can pass as long as "invalid" and "type" appear |
| 180 |
# in stderr (case insensitive). |
| 181 |
error_parts = error_type.split('-') |
| 182 |
if all(p in stderr.lower() for p in error_parts): |
| 183 |
return True |
| 184 |
return False |
| 185 |
|
| 186 |
def _show_failure(self, actual, test_case): |
| 187 |
test_case['actual'] = json.dumps(actual) |
| 188 |
test_case['result'] = json.dumps(test_case['result']) |
| 189 |
test_case['given_js'] = json.dumps(test_case['given']) |
| 190 |
failure_message = ( |
| 191 |
"\nFAIL {category},{group_number},{test_number}\n" |
| 192 |
"The expression: {expression}\n" |
| 193 |
"was suppose to give: {result}\n" |
| 194 |
"for the JSON: {given_js}\n" |
| 195 |
"but instead gave: {actual}\n" |
| 196 |
).format(**test_case) |
| 197 |
sys.stdout.write(failure_message) |
| 198 |
|
| 199 |
def _show_failure_for_zero_rc(self, stderr, return_code, test_case): |
| 200 |
test_case['stderr'] = stderr |
| 201 |
test_case['returncode'] = return_code |
| 202 |
failure_message = ( |
| 203 |
"\nFAIL {category},{group_number},{test_number}\n" |
| 204 |
"The expression: {expression}\n" |
| 205 |
"was suppose to have non zero for error error: {error}\n" |
| 206 |
"but instead gave rc of: {returncode}, stderr: \n{stderr}\n" |
| 207 |
).format(**test_case) |
| 208 |
sys.stdout.write(failure_message) |
| 209 |
|
| 210 |
def _show_failure_for_error(self, stderr, test_case): |
| 211 |
test_case['stderr'] = stderr |
| 212 |
failure_message = ( |
| 213 |
"\nFAIL {category},{group_number},{test_number}\n" |
| 214 |
"The expression: {expression}\n" |
| 215 |
"was suppose to emit the error: {error}\n" |
| 216 |
"but instead gave: \n{stderr}\n" |
| 217 |
).format(**test_case) |
| 218 |
sys.stdout.write(failure_message) |
| 219 |
|
| 220 |
def get_compliance_test_files(self): |
| 221 |
for root, _, filenames in os.walk(self.test_dir): |
| 222 |
for filename in filenames: |
| 223 |
if filename.endswith('.json'): |
| 224 |
full_path = _pjoin(root, filename) |
| 225 |
yield full_path |
| 226 |
|
| 227 |
|
| 228 |
def display_available_tests(test_files): |
| 229 |
print("Available test types:\n") |
| 230 |
for filename in test_files: |
| 231 |
no_extension = os.path.splitext(os.path.basename(filename))[0] |
| 232 |
print(no_extension) |
| 233 |
|
| 234 |
|
| 235 |
def test_spec(value): |
| 236 |
parts = value.split(',') |
| 237 |
if not parts: |
| 238 |
raise ValueError("%s should be a comma separated list." % value) |
| 239 |
spec = {'category': parts[0]} |
| 240 |
if len(parts) == 2: |
| 241 |
spec['group_number'] = int(parts[1]) |
| 242 |
elif len(parts) == 3: |
| 243 |
spec['group_number'] = int(parts[1]) |
| 244 |
spec['test_number'] = int(parts[2]) |
| 245 |
return spec |
| 246 |
|
| 247 |
|
| 248 |
def main(): |
| 249 |
parser = argparse.ArgumentParser(usage=__doc__) |
| 250 |
parser.add_argument('-e', '--exe', help='The JMESPath executable to use.') |
| 251 |
parser.add_argument('-t', '--tests', help=( |
| 252 |
'The compliance tests to run. If this value is not provided, ' |
| 253 |
'then all compliance tests are run.'), type=test_spec, nargs='+') |
| 254 |
parser.add_argument('-d', '--test-dir', |
| 255 |
help='The directory containing compliance tests.') |
| 256 |
parser.add_argument('-l', '--list', action="store_true", |
| 257 |
help=('List the available compliance tests to run. ' |
| 258 |
'These values can then be used with the ' |
| 259 |
'"-t/--tests" argument. If this argument is ' |
| 260 |
'specified, no tests will actually be run.')) |
| 261 |
parser.add_argument('-s', '--stop-first-fail', action='store_true', |
| 262 |
help='Stop running tests after a single test fails.') |
| 263 |
args = parser.parse_args() |
| 264 |
runner = ComplianceTestRunner(args.exe, args.tests, args.test_dir) |
| 265 |
if args.list: |
| 266 |
display_available_tests(runner.get_compliance_test_files()) |
| 267 |
else: |
| 268 |
try: |
| 269 |
runner.run_tests(args.stop_first_fail) |
| 270 |
except Exception as e: |
| 271 |
raise |
| 272 |
sys.stderr.write(str(e)) |
| 273 |
sys.stderr.write("\n") |
| 274 |
return 1 |
| 275 |
sys.stdout.write('\n') |
| 276 |
if runner.had_failures: |
| 277 |
sys.stdout.write('FAIL\n') |
| 278 |
return 1 |
| 279 |
sys.stdout.write('OK\n') |
| 280 |
return 0 |
| 281 |
|
| 282 |
|
| 283 |
if __name__ == '__main__': |
| 284 |
sys.exit(main()) |