|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 | + |
| 4 | +""" |
| 5 | +Helper functions for loading structured test data for unit tests. |
| 6 | +
|
| 7 | +Provides functions to locate JSON test_data files based on the |
| 8 | +location of the test script in tests/unit/ and to return the data |
| 9 | +as lists of tuples for use in pytest parameterization. |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +CURRENT_FILE = Path(__file__).resolve() # Current file abs path |
| 16 | +UNIT_TESTS_DIR = CURRENT_FILE.parents[1] # project_root/tests/unit |
| 17 | +# Relative path from project root to unit tests dir - tests/unit |
| 18 | +ROOT_TO_UNIT_TESTS = CURRENT_FILE.parents[1].relative_to(CURRENT_FILE.parents[3]) |
| 19 | + |
| 20 | + |
| 21 | +def load_test_data(script_dir: Path, file_name: str, use_subfold: bool = True) -> list: |
| 22 | + """ |
| 23 | + Load structured test data for a test file. |
| 24 | +
|
| 25 | + The directory structure is derived from: |
| 26 | + tests/unit/<unit_test_dir>/<optional_subfolder>/... |
| 27 | +
|
| 28 | + Args: |
| 29 | + test_script_dir: Directory containing the test file. |
| 30 | + file_name: Name of the test_data folder to load. |
| 31 | + use_sub: Dive into same subfolders as script_dir in test_data |
| 32 | +
|
| 33 | + Returns: |
| 34 | + List of tuples extracted from the JSON file. |
| 35 | + """ |
| 36 | + try: |
| 37 | + # Normal environments: script_dir is resolved under same path tests/unit |
| 38 | + units_to_test_file: list = script_dir.relative_to(UNIT_TESTS_DIR).parts |
| 39 | + except ValueError: |
| 40 | + # Fallback for tox/CI virtual environments where path tests/unit differ |
| 41 | + # Find the path fragment "tests/unit" and slice from there |
| 42 | + parts = list(script_dir.parts) |
| 43 | + try: |
| 44 | + idx = parts.index(UNIT_TESTS_DIR.parts[-1]) # project/tests/unit/... |
| 45 | + units_to_test_file: list = parts[idx + 1 :] |
| 46 | + except ValueError: |
| 47 | + # Last-resort fallback: treat as having no subfolder |
| 48 | + units_to_test_file = () |
| 49 | + |
| 50 | + unit_test_dir: str = units_to_test_file[0] if len(units_to_test_file) > 0 else "" |
| 51 | + subfolder = Path(*units_to_test_file[1:]) if len(units_to_test_file) > 1 else None |
| 52 | + |
| 53 | + # Build data.json path |
| 54 | + base = ROOT_TO_UNIT_TESTS / unit_test_dir / "test_data" |
| 55 | + if subfolder and use_subfold: |
| 56 | + base /= subfolder |
| 57 | + |
| 58 | + data_file = base / f"{file_name}.json" |
| 59 | + |
| 60 | + with data_file.open("r", encoding="utf-8") as f: |
| 61 | + data = json.load(f) |
| 62 | + |
| 63 | + return [tuple(item.values()) for item in data] |
0 commit comments