|
| 1 | +import sys |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +import re |
| 5 | +import json |
| 6 | + |
| 7 | + |
| 8 | +def getBinDir(): |
| 9 | + if len(sys.argv) != 2: |
| 10 | + raise Exception("binary directory not provided") |
| 11 | + return sys.argv[1] |
| 12 | + |
| 13 | + |
| 14 | +class ExamplesTest: |
| 15 | + def __init__(self, binDir): |
| 16 | + self.binDir = binDir |
| 17 | + self.examplesPaths = self.__getAvailableExamples() |
| 18 | + self.expectedTestMap = self.__getExpectedTestMap() |
| 19 | + |
| 20 | + def __getAvailableExamples(self): |
| 21 | + paths = [os.path.join(self.binDir, f) for f in os.listdir(self.binDir) if "Example" in f] |
| 22 | + return [f for f in paths if os.path.isfile(f)] |
| 23 | + |
| 24 | + def __getExpectedTestMap(self): |
| 25 | + with open('expectedTestData.json') as data: |
| 26 | + return json.load(data) |
| 27 | + |
| 28 | + def __runTest(self, examplePath, expected): |
| 29 | + if expected is None: |
| 30 | + raise Exception(f"example was not expected") |
| 31 | + result = subprocess.run([examplePath], capture_output=True, text=True) |
| 32 | + if result.returncode: |
| 33 | + raise Exception(f"example returned non zero code {result.returncode}") |
| 34 | + if not re.search(expected, result.stdout): |
| 35 | + raise Exception(f"result of running example: '{result.stdout}' does not match expected: '{expected}'") |
| 36 | + |
| 37 | + def __runTestAndSummarize(self, examplePath): |
| 38 | + name = os.path.basename(examplePath).split('.')[-1].replace("Example", "") |
| 39 | + try: |
| 40 | + self.__runTest(examplePath, self.expectedTestMap.get(name)) |
| 41 | + print(f"{name} example test succeeded") |
| 42 | + return True |
| 43 | + except Exception as e: |
| 44 | + print(f"{name} example test failed: {e}") |
| 45 | + finally: |
| 46 | + del self.expectedTestMap[name] |
| 47 | + return False |
| 48 | + |
| 49 | + def run(self): |
| 50 | + allTests = len(self.examplesPaths) |
| 51 | + succeededTests = 0 |
| 52 | + for count, examplePath in enumerate(self.examplesPaths, start=1): |
| 53 | + print(f"Test {count}/{allTests}") |
| 54 | + succeededTests += self.__runTestAndSummarize(examplePath) |
| 55 | + if len(self.expectedTestMap): |
| 56 | + raise Exception(f"Some expected tests were not run: {self.expectedTestMap.keys()}") |
| 57 | + if succeededTests == allTests: |
| 58 | + print(f"All test succeeded: {succeededTests}/{allTests}") |
| 59 | + else: |
| 60 | + raise Exception(f"Some tests failed: {allTests - succeededTests}/{allTests}") |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + ExamplesTest(getBinDir()).run() |
0 commit comments