|
| 1 | +import json |
| 2 | +import yaml |
| 3 | +from typing import Union |
| 4 | + |
| 5 | +class TestFile: |
| 6 | + """An abstraction over a test file, which may be in one of several different formats. |
| 7 | + Currently, JSON and YAML are supported. |
| 8 | + """ |
| 9 | + |
| 10 | + def __init__(self, path: str) -> None: |
| 11 | + self.groups = [] |
| 12 | + |
| 13 | + # Attempt to open the given file. Exit with an error if this |
| 14 | + # is not possible. |
| 15 | + file_content = "" |
| 16 | + try: |
| 17 | + with open(path, "r") as test_file: |
| 18 | + file_content = test_file.read() |
| 19 | + except IOError as e: |
| 20 | + raise Exception(f'Failed to open test file: "{e}"') |
| 21 | + |
| 22 | + # Get the file extension to determine which format should be used. |
| 23 | + extension = path.split(".")[-1] |
| 24 | + if extension == "json": |
| 25 | + try: |
| 26 | + questions = json.loads(file_content) |
| 27 | + |
| 28 | + for question in questions: |
| 29 | + out = [] |
| 30 | + title = question["title"] |
| 31 | + for part in question["parts"]: |
| 32 | + for response_area in part["responseAreas"]: |
| 33 | + params = response_area["params"] |
| 34 | + answer = response_area["answer"] |
| 35 | + for test in response_area["tests"]: |
| 36 | + test.update({"answer": answer}) |
| 37 | + test.update({"params": params}) |
| 38 | + out.append(SingleTest(test)) |
| 39 | + self.groups.append({"title": title, "tests": out}) |
| 40 | + |
| 41 | + except KeyError as e: |
| 42 | + raise Exception(f'The key "{e.args[0]}" doesn\'t exist, or is in the wrong place.') |
| 43 | + except json.JSONDecodeError as e: |
| 44 | + raise Exception(f'Error parsing JSON: "{e}"') |
| 45 | + elif extension == "yaml": |
| 46 | + try: |
| 47 | + # Tests are organised in groups of separate YAML documents (separated by "---") |
| 48 | + docs = yaml.safe_load_all(file_content) |
| 49 | + for test_group in docs: |
| 50 | + tests = [] |
| 51 | + title = test_group.get("title", "") |
| 52 | + for test in test_group.get("tests", []): |
| 53 | + # Add an empty params field if none was provided. |
| 54 | + if test.get("params") == None: |
| 55 | + test["params"] = {} |
| 56 | + |
| 57 | + # Does this test have sub-tests? |
| 58 | + sub_tests = test.get("sub_tests") |
| 59 | + if sub_tests != None: |
| 60 | + params = test["params"] |
| 61 | + answer = test["answer"] |
| 62 | + |
| 63 | + for sub_test in sub_tests: |
| 64 | + sub_test["params"] = params |
| 65 | + sub_test["answer"] = answer |
| 66 | + tests.append(SingleTest(sub_test)) |
| 67 | + else: |
| 68 | + tests.append(SingleTest(test)) |
| 69 | + |
| 70 | + self.groups.append({"title": title, "tests": tests}) |
| 71 | + except yaml.YAMLError as e: |
| 72 | + raise Exception(f'Error parsing YAML: {e}') |
| 73 | + else: |
| 74 | + raise Exception(f'"{extension}" files are not supported as a test format.') |
| 75 | + |
| 76 | +class SingleTest: |
| 77 | + def __init__(self, test_dict: dict): |
| 78 | + self.response = test_dict.get("response", "") |
| 79 | + self.answer = test_dict.get("answer", "") |
| 80 | + self.params = test_dict.get("params", {}) |
| 81 | + expected_result = test_dict.get("expected_result") |
| 82 | + if not expected_result: |
| 83 | + raise Exception("No expected result given for test") |
| 84 | + self.is_correct = expected_result.get("is_correct") |
| 85 | + self.results = expected_result |
| 86 | + self.desc = test_dict.get("description", "") |
| 87 | + |
| 88 | + def evaluate(self, func) -> dict: |
| 89 | + return func(self.response, self.answer, self.params) |
| 90 | + |
| 91 | + def compare(self, eval_result: dict) -> tuple[bool, str]: |
| 92 | + eval_correct = eval_result["is_correct"] |
| 93 | + |
| 94 | + if eval_correct != self.is_correct: |
| 95 | + return ( |
| 96 | + False, |
| 97 | + f"response \"{self.response}\" with answer \"{self.answer}\" was {'' if eval_correct else 'in'}correct: {eval_result['feedback']}\nTest description: {self.desc}" |
| 98 | + ) |
| 99 | + |
| 100 | + # Are there any other fields in the eval function result that need to be checked? |
| 101 | + if self.results != None: |
| 102 | + # Check each one in turn |
| 103 | + for key, value in self.results.items(): |
| 104 | + actual_result_val = eval_result.get(key) |
| 105 | + if actual_result_val == None: |
| 106 | + return (False, f"No value returned for \"{key}\"") |
| 107 | + |
| 108 | + if actual_result_val != value: |
| 109 | + return ( |
| 110 | + False, |
| 111 | + f"expected {key} = \"{value}\", got {key} = \"{actual_result_val}\"\nTest description: {self.desc}" |
| 112 | + ) |
| 113 | + |
| 114 | + return (True, "") |
| 115 | + |
| 116 | + |
| 117 | +def auto_test(path, func): |
| 118 | + """A decorator that adds the necessary infrastructure to run tests defined |
| 119 | + in an external data file.\n |
| 120 | + `path`: the path to the data file, relative to the eval function root.\n |
| 121 | + `func`: the function to test. Should usually be `evaluation_function`. |
| 122 | + """ |
| 123 | + def _auto_test(orig_class): |
| 124 | + def test_auto(self): |
| 125 | + # Creating a TestFile can fail for several reasons. |
| 126 | + # If so, an exception is raised with a suitable error message |
| 127 | + try: |
| 128 | + tests = TestFile(path) |
| 129 | + except Exception as e: |
| 130 | + self.fail(e) |
| 131 | + |
| 132 | + # Successfully loaded |
| 133 | + for group in tests.groups: |
| 134 | + for test in group["tests"]: |
| 135 | + results = test.evaluate(func) |
| 136 | + self.assertTrue(*test.compare(results.to_dict())) |
| 137 | + |
| 138 | + orig_class.test_auto = test_auto # Add the test_auto function to the class |
| 139 | + return orig_class |
| 140 | + return _auto_test |
0 commit comments