Skip to content

Commit e927c52

Browse files
mypy / precommit
1 parent 51e749f commit e927c52

20 files changed

Lines changed: 139 additions & 91 deletions

mp_api/_test_utils.py

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,17 @@
2323

2424
NUM_DOCS = 5
2525

26+
2627
def client_search_testing(
2728
search_method: Callable,
2829
excluded_params: list[str],
2930
alt_name_dict: dict[str, str],
3031
custom_field_tests: dict[str, Any],
3132
sub_doc_fields: list[str],
32-
int_bounds : tuple[int,int] = (-100, 100),
33-
float_bounds : tuple[float,float] = (-100.12, 100.12),
33+
int_bounds: tuple[int, int] = (-100, 100),
34+
float_bounds: tuple[float, float] = (-100.12, 100.12),
3435
):
35-
"""
36-
Function to test a client using its search method.
36+
"""Function to test a client using its search method.
3737
Each parameter is used to query for data, which is then checked.
3838
3939
Args:
@@ -43,7 +43,7 @@ def client_search_testing(
4343
custom_field_tests (dict[str, Any]): Custom queries for specific fields.
4444
sub_doc_fields (list[str]): Prefixes for fields to check in resulting data. Useful when data to be tested is nested.
4545
int_bounds (tuple[int,int]) : integer bounds to use in testing int-type query arguments
46-
float_boudns (tuple[float,float]) : float bounds to use in testing float-type query arguments
46+
float_bounds (tuple[float,float]) : float bounds to use in testing float-type query arguments
4747
"""
4848
if search_method is None:
4949
return
@@ -56,7 +56,7 @@ def client_search_testing(
5656

5757
if param not in excluded_params + ["return"]:
5858
param_type = entry[1]
59-
q = {"chunk_size": 1, "num_chunks": 1}
59+
q: dict[str, Any] = {"chunk_size": 1, "num_chunks": 1}
6060

6161
if "tuple[int, int]" in param_type:
6262
q[param] = int_bounds
@@ -84,31 +84,35 @@ def client_search_testing(
8484
assert doc[alt_name_dict.get(param, param)] is not None
8585

8686

87-
def client_pagination(search_method : Callable, id_name : str):
88-
89-
page_1 = search_method(_page=1, chunk_size=NUM_DOCS, fields = [id_name])
90-
page_2 = search_method(_page=2, chunk_size=NUM_DOCS, fields = [id_name])
91-
assert all(
92-
len(results) == NUM_DOCS for results in (page_1, page_2)
93-
)
87+
def client_pagination(search_method: Callable, id_name: str):
88+
page_1 = search_method(_page=1, chunk_size=NUM_DOCS, fields=[id_name])
89+
page_2 = search_method(_page=2, chunk_size=NUM_DOCS, fields=[id_name])
90+
assert all(len(results) == NUM_DOCS for results in (page_1, page_2))
9491
assert {str(getattr(doc, id_name)) for doc in page_1}.intersection(
95-
{str(getattr(doc,id_name)) for doc in page_2}
92+
{str(getattr(doc, id_name)) for doc in page_2}
9693
) == set()
9794

9895

99-
def client_sort(search_method : Callable, sort_fields : str | Sequence[str]):
100-
101-
for sort_field in ([sort_fields] if isinstance(sort_fields,str) else sort_fields):
102-
asc = search_method(_page=1, _sort_fields=sort_field, chunk_size=NUM_DOCS, fields = [sort_field])
103-
desc = search_method(_page=1, _sort_fields=f"-{sort_field}", chunk_size=NUM_DOCS, fields = [sort_field])
96+
def client_sort(search_method: Callable, sort_fields: str | Sequence[str]):
97+
for sort_field in [sort_fields] if isinstance(sort_fields, str) else sort_fields:
98+
asc = search_method(
99+
_page=1, _sort_fields=sort_field, chunk_size=NUM_DOCS, fields=[sort_field]
100+
)
101+
desc = search_method(
102+
_page=1,
103+
_sort_fields=f"-{sort_field}",
104+
chunk_size=NUM_DOCS,
105+
fields=[sort_field],
106+
)
104107

105108
idxs = list(range(NUM_DOCS))
106-
assert sorted(
107-
idxs, key=lambda idx: getattr(asc[idx],sort_field)
108-
) == idxs
109-
110-
assert sorted(
111-
idxs,
112-
key=lambda idx: getattr(desc[idx],sort_field),
113-
reverse=True,
114-
) == idxs
109+
assert sorted(idxs, key=lambda idx: getattr(asc[idx], sort_field)) == idxs
110+
111+
assert (
112+
sorted(
113+
idxs,
114+
key=lambda idx: getattr(desc[idx], sort_field),
115+
reverse=True,
116+
)
117+
== idxs
118+
)

mp_api/client/routes/materials/electrodes.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,18 +88,17 @@ def search(
8888
query_params: dict = defaultdict(dict)
8989

9090
for param, value in locals().items():
91-
if (
92-
param not in {"__class__", "self", "query_params"}
93-
and value is not None
94-
):
95-
96-
if param == "num_elements": # this must come first
91+
if param not in {"__class__", "self", "query_params"} and value is not None:
92+
if param == "num_elements": # this must come first
9793
if isinstance(num_elements, int):
9894
num_elements = (num_elements, num_elements)
9995
query_params.update(
100-
{"nelements_min": num_elements[0], "nelements_max": num_elements[1]}
101-
)
102-
96+
{
97+
"nelements_min": num_elements[0], # type: ignore[index]
98+
"nelements_max": num_elements[1], # type: ignore[index]
99+
}
100+
)
101+
103102
elif isinstance(value, tuple):
104103
query_params.update(
105104
{f"{param}_min": value[0], f"{param}_max": value[1]}
@@ -108,10 +107,15 @@ def search(
108107
query_params[param] = ",".join(validate_ids(value))
109108
elif param == "working_ion":
110109
query_params["working_ion"] = ",".join(
111-
str(ele) for ele in ([value] if isinstance(value, str | Element) else value)
110+
str(ele)
111+
for ele in (
112+
[value] if isinstance(value, str | Element) else value
113+
)
114+
)
115+
elif param in ("formula", "elements", "exclude_elements"):
116+
query_params[param] = ",".join(
117+
[value] if isinstance(value, str) else value
112118
)
113-
elif param in ("formula","elements","exclude_elements"):
114-
query_params[param] = ",".join([value] if isinstance(value,str) else value)
115119
else:
116120
query_params[param] = value
117121

mp_api/client/routes/materials/summary.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -309,10 +309,16 @@ def _csrc(x):
309309

310310
query_params.update({"material_ids": ",".join(validate_ids(material_ids))})
311311

312-
for k in ("formula", "chemsys", "elements", "exclude_elements", "possible_species"):
312+
for k in (
313+
"formula",
314+
"chemsys",
315+
"elements",
316+
"exclude_elements",
317+
"possible_species",
318+
):
313319
if (v := _locals.get(k)) is not None:
314-
query_params[k] = ",".join([v] if isinstance(v,str) else v)
315-
320+
query_params[k] = ",".join([v] if isinstance(v, str) else v)
321+
316322
symm_cardinality = {
317323
"crystal_system": 7,
318324
"spacegroup_number": 230,
@@ -331,7 +337,14 @@ def _csrc(x):
331337
else:
332338
query_params.update({k: symm_vals})
333339

334-
for k in ("deprecated", "is_stable", "is_gap_direct", "is_metal", "has_reconstructed", "theoretical"):
340+
for k in (
341+
"deprecated",
342+
"is_stable",
343+
"is_gap_direct",
344+
"is_metal",
345+
"has_reconstructed",
346+
"theoretical",
347+
):
335348
if (v := _locals.get(k)) is not None:
336349
query_params[k] = v
337350

mp_api/client/routes/materials/xas.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from pymatgen.core.periodic_table import Element
77

88
from mp_api.client.core import BaseRester
9-
from mp_api.client.core.utils import validate_ids
109

1110
if TYPE_CHECKING:
1211
from typing import Any
@@ -62,10 +61,9 @@ def search(
6261
Returns:
6362
([MaterialsDoc]) List of material documents
6463
"""
65-
6664
_locals = locals()
6765
query_params: dict[str, Any] = {
68-
k : _locals[k]
66+
k: _locals[k]
6967
for k in ("edge", "spectrum_type", "formula", "_page", "_sort_fields")
7068
if _locals.get(k) is not None
7169
}
@@ -79,9 +77,8 @@ def search(
7977
}
8078
)
8179
for k in ("chemsys", "elements", "material_ids", "spectrum_ids"):
82-
if (v := _locals.get(k) ) is not None:
83-
query_params[k] = ",".join([v] if isinstance(v,str) else v)
84-
80+
if (v := _locals.get(k)) is not None:
81+
query_params[k] = ",".join([v] if isinstance(v, str) else v)
8582

8683
query_params = {
8784
entry: query_params[entry]

mp_api/client/routes/molecules/jcesr.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def search(
4545
):
4646
"""Query legacy molecule docs using a variety of search criteria.
4747
48-
JCESR = Joint Center for Energy Storage Research
48+
JCESR = Joint Center for Energy Storage Research
4949
5050
Arguments:
5151
task_ids (str, List[str]): A single molecule task ID string or list of strings.
@@ -70,7 +70,7 @@ def search(
7070
([MoleculesDoc]) List of molecule documents
7171
"""
7272
query_params: dict = defaultdict(dict)
73-
73+
7474
if task_ids:
7575
if isinstance(task_ids, str):
7676
task_ids = [task_ids]
@@ -81,14 +81,14 @@ def search(
8181
query_params.update({"elements": ",".join([str(ele) for ele in elements])})
8282

8383
_locals = locals()
84-
for k in ("pointgroup","smiles","_page","_sort_fields"):
84+
for k in ("pointgroup", "smiles", "_page", "_sort_fields"):
8585
if (v := _locals.get(k)) is not None:
8686
query_params[k] = v
8787

88-
for k in ("nelements","EA","IE","charge"):
88+
for k in ("nelements", "EA", "IE", "charge"):
8989
if (vals := _locals.get(k)) is not None:
9090
query_params.update({f"{k}_min": vals[0], f"{k}_max": vals[1]})
91-
91+
9292
query_params = {
9393
entry: query_params[entry]
9494
for entry in query_params

mp_api/client/routes/molecules/summary.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,13 @@ def search(
8585
query_params.update({"molecule_ids": ",".join(molecule_ids)})
8686

8787
_locals = locals()
88-
for k in ("charge","spin_multiplicity","_page","_sort_fields"):
88+
for k in ("charge", "spin_multiplicity", "_page", "_sort_fields"):
8989
if (v := _locals.get(k)) is not None:
9090
query_params[k] = v
9191

92-
for k in ("formula","chemsys","elements","exclude_elements"):
92+
for k in ("formula", "chemsys", "elements", "exclude_elements"):
9393
if (v := _locals.get(k)) is not None:
94-
query_params[k] = ",".join([v] if isinstance(v,str) else v)
94+
query_params[k] = ",".join([v] if isinstance(v, str) else v)
9595

9696
if has_props:
9797
query_params.update({"has_props": ",".join([i.value for i in has_props])})

tests/client/materials/test_absorption.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from mp_api.client.routes.materials.absorption import AbsorptionRester
1111

1212

13-
1413
@requires_api_key
1514
def test_absorption_search():
1615
with AbsorptionRester() as rester:

tests/client/materials/test_alloys.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
try:
32
import pymatgen.analysis.alloys
43
except ImportError:
@@ -15,7 +14,6 @@
1514
from mp_api.client.routes.materials.alloys import AlloysRester
1615

1716

18-
1917
@requires_api_key
2018
def test_alloys_search():
2119
with AlloysRester() as rester:

tests/client/materials/test_doi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
21
from mp_api._test_utils import client_search_testing, requires_api_key
32

43
from mp_api.client.routes.materials.doi import DOIRester
54

5+
66
@requires_api_key
77
def test_doi_search():
88
with DOIRester() as rester:

tests/client/materials/test_electrodes.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@
33
import pytest
44
from pymatgen.core.periodic_table import Element
55

6-
from mp_api._test_utils import client_search_testing, client_pagination, client_sort, requires_api_key
6+
from mp_api._test_utils import (
7+
client_search_testing,
8+
client_pagination,
9+
client_sort,
10+
requires_api_key,
11+
)
712

813
from mp_api.client.routes.materials.electrodes import (
914
ElectrodeRester,
@@ -88,11 +93,14 @@ def test_conversion_client(conversion_rester):
8893
@requires_api_key
8994
def test_pagination():
9095
with ElectrodeRester() as rester:
91-
client_pagination(rester.search,"battery_id")
96+
client_pagination(rester.search, "battery_id")
97+
9298

9399
@pytest.mark.xfail(reason="Sort requires API redeployment", strict=False)
94100
@requires_api_key
95-
@pytest.mark.parametrize("sort_field",["battery_id","stability_charge","average_voltage"])
101+
@pytest.mark.parametrize(
102+
"sort_field", ["battery_id", "stability_charge", "average_voltage"]
103+
)
96104
def test_sort(sort_field):
97105
with ElectrodeRester() as rester:
98-
client_sort(rester.search,sort_field)
106+
client_sort(rester.search, sort_field)

0 commit comments

Comments
 (0)