|
| 1 | +import importlib |
| 2 | +import json |
| 3 | +from inspect import signature |
| 4 | +from types import FunctionType |
| 5 | +from typing import Type, Iterable |
| 6 | + |
| 7 | +from testing.abstract_test import AbstractTest |
| 8 | +from testing.result import Result |
| 9 | +from utils.list_node import ListNode, list_to_linked_list, linked_list_to_list |
| 10 | +from utils.style import Style |
| 11 | +from utils.tree_node import TreeNode, list_to_binary_tree, binary_tree_to_list |
| 12 | + |
| 13 | + |
| 14 | +SOLUTION_MODULE_NAME = 'solution' |
| 15 | +solution_module = importlib.import_module(SOLUTION_MODULE_NAME) |
| 16 | + |
| 17 | +Solution = tuple(v for v in vars(solution_module).values() if type(v) is type and v.__module__ == SOLUTION_MODULE_NAME) |
| 18 | +if not Solution: |
| 19 | + raise NotImplementedError(f'Module {SOLUTION_MODULE_NAME} has no class') |
| 20 | + |
| 21 | +Solution = Solution[0] |
| 22 | +solution_method_names = tuple( |
| 23 | + v.__name__ for v in Solution.__dict__.values() |
| 24 | + if type(v) == FunctionType and v.__name__[0] != '_' |
| 25 | +) |
| 26 | +if not solution_method_names: |
| 27 | + raise NotImplementedError(f'Class {Solution.__name__} from module {SOLUTION_MODULE_NAME} has no methods') |
| 28 | + |
| 29 | + |
| 30 | +class TestDataError(Exception): |
| 31 | + def __init__(self, msg: str): |
| 32 | + self.msg = msg |
| 33 | + super().__init__() |
| 34 | + |
| 35 | + def __str__(self): |
| 36 | + return self.msg |
| 37 | + |
| 38 | + |
| 39 | +def get_params_signature(func): |
| 40 | + return tuple(signature(func).parameters.items()) |
| 41 | + |
| 42 | + |
| 43 | +def proc_args_by_func(args: Iterable, func) -> list: |
| 44 | + proc_args = [] |
| 45 | + signatures = get_params_signature(func) |
| 46 | + |
| 47 | + for arg, (_, param_type) in zip(args, signatures): |
| 48 | + if ListNode.__name__ in str(param_type): |
| 49 | + if isinstance(arg, list): |
| 50 | + if len(arg) and isinstance(arg[0], list): |
| 51 | + arg = [list_to_linked_list(el) or [] for el in arg] |
| 52 | + else: |
| 53 | + arg = list_to_linked_list(arg) or [] |
| 54 | + |
| 55 | + if TreeNode.__name__ in str(param_type): |
| 56 | + if isinstance(arg, list): |
| 57 | + if len(arg) and isinstance(arg[0], list): |
| 58 | + arg = [list_to_binary_tree(el) or [] for el in arg] |
| 59 | + else: |
| 60 | + arg = list_to_binary_tree(arg) or [] |
| 61 | + |
| 62 | + proc_args.append(arg) |
| 63 | + |
| 64 | + return proc_args |
| 65 | + |
| 66 | + |
| 67 | +def proc_result(result): |
| 68 | + if isinstance(result, ListNode): |
| 69 | + return linked_list_to_list(result) or [] |
| 70 | + |
| 71 | + if isinstance(result, TreeNode): |
| 72 | + return binary_tree_to_list(result) or [] |
| 73 | + |
| 74 | + return result |
| 75 | + |
| 76 | + |
| 77 | +def print_test_results(): |
| 78 | + style = Style.BOLD + Style.UNDERLINE |
| 79 | + if Result.count_passed() == Result.count_runs(): |
| 80 | + style += Style.GREEN |
| 81 | + else: |
| 82 | + style += Style.YELLOW |
| 83 | + |
| 84 | + print(f'{style}Tests passed: {Result.count_passed()}/{Result.count_runs()}') |
| 85 | + |
| 86 | + |
| 87 | +def testing( |
| 88 | + cls: Type[AbstractTest], |
| 89 | + tests_data: str |
| 90 | +): |
| 91 | + """ |
| 92 | + Тестирование класса, находящегося в solution.py. |
| 93 | +
|
| 94 | + :param cls: Тестирующий класс. |
| 95 | + :param tests_data: Текст с тестовыми данными. |
| 96 | + Его парсинг определяется тестирующим классом. |
| 97 | + """ |
| 98 | + lines = [line.strip() for line in tests_data.strip().splitlines()] |
| 99 | + lines = [lines[i] for i in range(len(lines)) |
| 100 | + if i == 0 or not(lines[i] == '' and lines[i-1] == '')] |
| 101 | + |
| 102 | + tests_data = '\n'.join(lines).split('\n\n') |
| 103 | + for data in tests_data: |
| 104 | + lines = [json.loads(line) for line in data.splitlines()] |
| 105 | + obj, expected = cls.parse(lines) |
| 106 | + obj.run().validate(expected) |
| 107 | + |
| 108 | + print_test_results() |
| 109 | + |
| 110 | + |
| 111 | +def generate_and_testing( |
| 112 | + cls: Type[AbstractTest], |
| 113 | + generate_args_func, |
| 114 | + validation_func, |
| 115 | + count: int |
| 116 | +): |
| 117 | + """ |
| 118 | + Генерация тестовых данных и тестирование ими класса, |
| 119 | + находящегося в solution.py. |
| 120 | +
|
| 121 | + :param cls: Тестирующий класс. |
| 122 | + :param generate_args_func: Функция генерации аргументов. |
| 123 | + Ничего не принимает, возвращает итерируемый объект с аргументами. |
| 124 | + :param validation_func: Функция валидации возвращенного результата. |
| 125 | + Принимает результат работы функции, возвращает логическое значение. |
| 126 | + :param count: Количество тестов. |
| 127 | + """ |
| 128 | + for _ in range(count): |
| 129 | + args = generate_args_func() |
| 130 | + cls(*args).run().validate(validation_func) |
| 131 | + |
| 132 | + print_test_results() |
0 commit comments