|
| 1 | +"""Define testing utils that need to imported.""" |
| 2 | + |
| 3 | +# pragma: exclude file |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +try: |
| 8 | + import pytest |
| 9 | +except ImportError as exc: |
| 10 | + raise ImportError( |
| 11 | + "You must `pip install 'mp-api[test]' to use these testing utilities." |
| 12 | + ) from exc |
| 13 | + |
| 14 | +import os |
| 15 | +from typing import TYPE_CHECKING |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from collections.abc import Callable, Sequence |
| 19 | + from typing import Any |
| 20 | + |
| 21 | +requires_api_key = pytest.mark.skipif( |
| 22 | + os.getenv("MP_API_KEY") is None, |
| 23 | + reason="No API key found.", |
| 24 | +) |
| 25 | + |
| 26 | +NUM_DOCS = 5 |
| 27 | + |
| 28 | + |
| 29 | +def client_search_testing( |
| 30 | + search_method: Callable, |
| 31 | + excluded_params: list[str], |
| 32 | + alt_name_dict: dict[str, str], |
| 33 | + custom_field_tests: dict[str, Any], |
| 34 | + sub_doc_fields: list[str], |
| 35 | + int_bounds: tuple[int, int] = (-100, 100), |
| 36 | + float_bounds: tuple[float, float] = (-100.12, 100.12), |
| 37 | +): |
| 38 | + """Function to test a client using its search method. |
| 39 | + Each parameter is used to query for data, which is then checked. |
| 40 | +
|
| 41 | + Args: |
| 42 | + search_method (Callable): Client search method |
| 43 | + excluded_params (list[str]): List of parameters to exclude from testing |
| 44 | + alt_name_dict (dict[str, str]): Alternative names for parameters used in the projection and subsequent data checking |
| 45 | + custom_field_tests (dict[str, Any]): Custom queries for specific fields. |
| 46 | + sub_doc_fields (list[str]): Prefixes for fields to check in resulting data. Useful when data to be tested is nested. |
| 47 | + int_bounds (tuple[int,int]) : integer bounds to use in testing int-type query arguments |
| 48 | + float_bounds (tuple[float,float]) : float bounds to use in testing float-type query arguments |
| 49 | + """ |
| 50 | + if search_method is None: |
| 51 | + return |
| 52 | + # Get list of parameters |
| 53 | + param_tuples = list(search_method.__annotations__.items()) |
| 54 | + |
| 55 | + # Query API for each numeric and boolean parameter and check if returned |
| 56 | + for entry in param_tuples: |
| 57 | + param = entry[0] |
| 58 | + |
| 59 | + if param not in excluded_params + ["return"]: |
| 60 | + param_type = entry[1] |
| 61 | + q: dict[str, Any] = {"chunk_size": 1, "num_chunks": 1} |
| 62 | + |
| 63 | + if "tuple[int, int]" in param_type: |
| 64 | + q[param] = int_bounds |
| 65 | + elif "tuple[float, float]" in param_type: |
| 66 | + q[param] = float_bounds |
| 67 | + elif "bool" in param_type: |
| 68 | + q[param] = False |
| 69 | + elif param in custom_field_tests: |
| 70 | + q[param] = custom_field_tests[param] |
| 71 | + else: |
| 72 | + raise ValueError( |
| 73 | + f"Parameter '{param}' with type '{param_type}' was not " |
| 74 | + "properly identified in the generic search method test." |
| 75 | + ) |
| 76 | + |
| 77 | + if len(docs := search_method(**q)) > 0: |
| 78 | + doc = docs[0].model_dump() |
| 79 | + else: |
| 80 | + raise ValueError("No documents returned") |
| 81 | + |
| 82 | + for sub_field in sub_doc_fields: |
| 83 | + if sub_field in doc: |
| 84 | + doc = doc[sub_field] |
| 85 | + |
| 86 | + assert doc[alt_name_dict.get(param, param)] is not None |
| 87 | + |
| 88 | + |
| 89 | +def client_pagination(search_method: Callable, id_name: str): |
| 90 | + page_1 = search_method(_page=1, chunk_size=NUM_DOCS, fields=[id_name]) |
| 91 | + page_2 = search_method(_page=2, chunk_size=NUM_DOCS, fields=[id_name]) |
| 92 | + assert all(len(results) == NUM_DOCS for results in (page_1, page_2)) |
| 93 | + assert {str(getattr(doc, id_name)) for doc in page_1}.intersection( |
| 94 | + {str(getattr(doc, id_name)) for doc in page_2} |
| 95 | + ) == set() |
| 96 | + |
| 97 | + |
| 98 | +def client_sort(search_method: Callable, sort_fields: str | Sequence[str]): |
| 99 | + for sort_field in [sort_fields] if isinstance(sort_fields, str) else sort_fields: |
| 100 | + asc = search_method( |
| 101 | + _page=1, _sort_fields=sort_field, chunk_size=NUM_DOCS, fields=[sort_field] |
| 102 | + ) |
| 103 | + desc = search_method( |
| 104 | + _page=1, |
| 105 | + _sort_fields=f"-{sort_field}", |
| 106 | + chunk_size=NUM_DOCS, |
| 107 | + fields=[sort_field], |
| 108 | + ) |
| 109 | + |
| 110 | + idxs = list(range(NUM_DOCS)) |
| 111 | + assert sorted(idxs, key=lambda idx: getattr(asc[idx], sort_field)) == idxs |
| 112 | + |
| 113 | + assert ( |
| 114 | + sorted( |
| 115 | + idxs, |
| 116 | + key=lambda idx: getattr(desc[idx], sort_field), |
| 117 | + reverse=True, |
| 118 | + ) |
| 119 | + == idxs |
| 120 | + ) |
0 commit comments