2020-09-28 06:18:19 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
import importlib.util
|
|
|
|
import json
|
|
|
|
import pathlib
|
|
|
|
from types import ModuleType
|
2020-10-13 10:11:12 +00:00
|
|
|
from typing import Dict, List
|
2020-09-28 06:18:19 +00:00
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
PROJECT_EULER_DIR_PATH = pathlib.Path.cwd().joinpath("project_euler")
|
2020-10-24 13:37:33 +00:00
|
|
|
PROJECT_EULER_ANSWERS_PATH = pathlib.Path.cwd().joinpath(
|
|
|
|
"scripts", "project_euler_answers.json"
|
2020-09-28 06:18:19 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
|
2020-10-13 10:11:12 +00:00
|
|
|
PROBLEM_ANSWERS: Dict[str, str] = json.load(file_handle)
|
2020-09-28 06:18:19 +00:00
|
|
|
|
|
|
|
|
2020-10-13 10:11:12 +00:00
|
|
|
def convert_path_to_module(file_path: pathlib.Path) -> ModuleType:
|
|
|
|
"""Converts a file path to a Python module"""
|
|
|
|
spec = importlib.util.spec_from_file_location(file_path.name, str(file_path))
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
spec.loader.exec_module(module)
|
|
|
|
return module
|
|
|
|
|
|
|
|
|
|
|
|
def collect_solution_file_paths() -> List[pathlib.Path]:
|
|
|
|
"""Collects all the solution file path in the Project Euler directory"""
|
|
|
|
solution_file_paths = []
|
|
|
|
for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
|
|
|
|
if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"):
|
2020-09-28 06:18:19 +00:00
|
|
|
continue
|
2020-10-13 10:11:12 +00:00
|
|
|
for file_path in problem_dir_path.iterdir():
|
|
|
|
if file_path.suffix != ".py" or file_path.name.startswith(("_", "test")):
|
|
|
|
continue
|
|
|
|
solution_file_paths.append(file_path)
|
|
|
|
return solution_file_paths
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2020-10-15 07:13:28 +00:00
|
|
|
"solution_path",
|
|
|
|
collect_solution_file_paths(),
|
|
|
|
ids=lambda path: f"{path.parent.name}/{path.name}",
|
2020-10-13 10:11:12 +00:00
|
|
|
)
|
|
|
|
def test_project_euler(solution_path: pathlib.Path):
|
|
|
|
"""Testing for all Project Euler solutions"""
|
2020-10-15 07:13:28 +00:00
|
|
|
# problem_[extract this part] and pad it with zeroes for width 3
|
|
|
|
problem_number: str = solution_path.parent.name[8:].zfill(3)
|
2020-10-13 10:11:12 +00:00
|
|
|
expected: str = PROBLEM_ANSWERS[problem_number]
|
|
|
|
solution_module = convert_path_to_module(solution_path)
|
|
|
|
answer = str(solution_module.solution())
|
|
|
|
assert answer == expected, f"Expected {expected} but got {answer}"
|