|
| 1 | +from collections.abc import Hashable |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import pandas |
| 5 | +import pytest |
| 6 | +from pytest import FixtureRequest |
| 7 | + |
| 8 | +from pytest_data_loader import load, parametrize, parametrize_dir |
| 9 | +from tests.tests_loader.helper import PATH_CSV_FILE, PATH_CSV_FILE_DIR, get_parametrized_test_idx |
| 10 | + |
| 11 | +pytestmark = pytest.mark.readers |
| 12 | + |
| 13 | + |
| 14 | +DELIMITER = {"comma": ",", "semicolon": ","} |
| 15 | + |
| 16 | + |
| 17 | +@load(("file_path", "df"), PATH_CSV_FILE, file_reader=pandas.read_csv) |
| 18 | +def test_load_csv_file_with_pandas(file_path: Path, df: pandas.DataFrame) -> None: |
| 19 | + """Test @load loader with the CSV reader from pandas""" |
| 20 | + assert isinstance(df, pandas.DataFrame) |
| 21 | + expected_data = get_expected_data(file_path) |
| 22 | + for i, row in df.iterrows(): |
| 23 | + assert isinstance(row, pandas.Series) |
| 24 | + assert DELIMITER[file_path.stem].join(row.to_list()) == expected_data[i + 1] |
| 25 | + |
| 26 | + |
| 27 | +@parametrize( |
| 28 | + ("file_path", "idx_and_row"), PATH_CSV_FILE, file_reader=pandas.read_csv, parametrizer_func=lambda df: df.iterrows() |
| 29 | +) |
| 30 | +def test_parametrize_csv_file_with_pandas( |
| 31 | + request: FixtureRequest, file_path: Path, idx_and_row: tuple[Hashable, pandas.Series] |
| 32 | +) -> None: |
| 33 | + """Test @parametrize loader with the CSV reader from pands""" |
| 34 | + assert isinstance(idx_and_row, tuple) |
| 35 | + i, row = idx_and_row |
| 36 | + expected_data = get_expected_data(file_path) |
| 37 | + assert i == get_parametrized_test_idx(request, arg_name="idx_and_row") |
| 38 | + assert DELIMITER[file_path.stem].join(row.to_list()) == expected_data[i + 1] |
| 39 | + |
| 40 | + |
| 41 | +@parametrize_dir( |
| 42 | + ("file_path", "df"), |
| 43 | + PATH_CSV_FILE_DIR, |
| 44 | + file_reader_func=lambda p: (lambda f: pandas.read_csv(f, delimiter=DELIMITER[p.stem])), |
| 45 | +) |
| 46 | +def test_parametrize_dir_with_pandas(file_path: Path, df: pandas.DataFrame) -> None: |
| 47 | + """Test @parametrize_dir loader with the CSV reader from pands""" |
| 48 | + assert isinstance(df, pandas.DataFrame) |
| 49 | + expected_data = get_expected_data(file_path) |
| 50 | + rows: list[pandas.Series] = [] |
| 51 | + for i, row in df.iterrows(): |
| 52 | + assert DELIMITER[file_path.stem].join(row.to_list()) == expected_data[i + 1] |
| 53 | + rows.append(row) |
| 54 | + assert len(rows) + 1 == len(expected_data) |
| 55 | + |
| 56 | + |
| 57 | +def get_expected_data(file_path: Path) -> list[str]: |
| 58 | + with open(file_path) as f: |
| 59 | + return f.read().splitlines() |
0 commit comments