Skip to content

Commit 2bf633d

Browse files
clean up exceptions defs
1 parent 1ec35e7 commit 2bf633d

10 files changed

Lines changed: 29 additions & 23 deletions

File tree

mp_api/client/core/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from __future__ import annotations
22

3-
from .client import BaseRester, MPRestError, MPRestWarning
3+
from .client import BaseRester
4+
from .exceptions import MPRestError, MPRestWarning
45
from .settings import MAPIClientSettings

mp_api/client/core/client.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from tqdm.auto import tqdm
3131
from urllib3.util.retry import Retry
3232

33+
from mp_api.client.core.exceptions import MPRestError
3334
from mp_api.client.core.settings import MAPIClientSettings
3435
from mp_api.client.core.utils import load_json, validate_ids
3536

@@ -1350,11 +1351,3 @@ def __str__(self): # pragma: no cover
13501351
f"{self.__class__.__name__} connected to {self.endpoint}\n\n"
13511352
f"Available fields: {', '.join(self.available_fields)}\n\n"
13521353
)
1353-
1354-
1355-
class MPRestError(Exception):
1356-
"""Raised when the query has problems, e.g., bad query format."""
1357-
1358-
1359-
class MPRestWarning(Warning):
1360-
"""Raised when a query is malformed but interpretable."""

mp_api/client/core/exceptions.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""Define custom exceptions and warnings for the client."""
2+
from __future__ import annotations
3+
4+
5+
class MPRestError(Exception):
6+
"""Raised when the query has problems, e.g., bad query format."""
7+
8+
9+
class MPRestWarning(Warning):
10+
"""Raised when a query is malformed but interpretable."""

mp_api/client/core/utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from monty.json import MontyDecoder
1010
from packaging.version import parse as parse_version
1111

12+
from mp_api.client.core.exceptions import MPRestError
1213
from mp_api.client.core.settings import MAPIClientSettings
1314

1415
if TYPE_CHECKING:
@@ -62,7 +63,7 @@ def validate_api_key(api_key: str | None = None) -> str:
6263

6364
if not api_key or len(api_key) != 32:
6465
addendum = " Valid API keys are 32 characters." if api_key else ""
65-
raise ValueError(
66+
raise MPRestError(
6667
"Please obtain a valid API key from https://materialsproject.org/api "
6768
f"and export it as an environment variable `MP_API_KEY`.{addendum}"
6869
)
@@ -77,13 +78,13 @@ def validate_ids(id_list: list[str]) -> list[str]:
7778
id_list (List[str]): List of material or task IDs.
7879
7980
Raises:
80-
ValueError: If at least one ID is not formatted correctly.
81+
MPRestError: If at least one ID is not formatted correctly.
8182
8283
Returns:
8384
id_list: Returns original ID list if everything is formatted correctly.
8485
"""
8586
if len(id_list) > MAPIClientSettings().MAX_LIST_LENGTH:
86-
raise ValueError(
87+
raise MPRestError(
8788
"List of material/molecule IDs provided is too long. Consider removing the ID filter to automatically pull"
8889
" data for all IDs and filter locally."
8990
)

mp_api/client/mprester.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,8 +290,6 @@ def __init__(
290290
elif "molecules" in suffix_split:
291291
_sub_rester_suffix_map["molecules"][attr] = cls
292292

293-
# TODO: Enable monty decoding when tasks and SNL schema is normalized
294-
#
295293
# Allow lazy loading of nested resters under materials and molecules using custom __getattr__ methods
296294
def __core_custom_getattr(_self, _attr, _rester_map):
297295
if _attr in _rester_map:

tests/core/test_utils.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from packaging.version import parse as parse_version
44
import pytest
55

6+
from mp_api.client.core.exceptions import MPRestError
7+
68

79
def test_emmet_core_version_checks(monkeypatch: pytest.MonkeyPatch):
810
ref_ver = (1, 2, "3rc5")
@@ -32,7 +34,7 @@ def test_id_validation():
3234

3335
max_num_idxs = MAPIClientSettings().MAX_LIST_LENGTH
3436

35-
with pytest.raises(ValueError, match="too long"):
37+
with pytest.raises(MPRestError, match="too long"):
3638
_ = validate_ids([f"mp-{x}" for x in range(max_num_idxs + 1)])
3739

3840
# For all legacy MPIDs, ensure these validate correctly
@@ -60,10 +62,10 @@ def test_api_key_validation(monkeypatch: pytest.MonkeyPatch):
6062
}
6163
monkeypatch.setattr(pymatgen.core, "SETTINGS", non_api_key_settings)
6264

63-
with pytest.raises(ValueError, match="32 characters"):
65+
with pytest.raises(MPRestError, match="32 characters"):
6466
validate_api_key("invalid_key")
6567

66-
with pytest.raises(ValueError, match="Please obtain a valid"):
68+
with pytest.raises(MPRestError, match="Please obtain a valid"):
6769
validate_api_key()
6870

6971
junk_api_key = "a" * 32
@@ -80,5 +82,6 @@ def test_api_key_validation(monkeypatch: pytest.MonkeyPatch):
8082
# MP API environment variable takes precedence
8183
assert validate_api_key() == junk_api_key
8284

85+
# Check that pymatgen API key is used
8386
monkeypatch.setenv("MP_API_KEY", "")
8487
assert validate_api_key() == other_junk_api_key

tests/materials/test_electronic_structure.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pytest
55
from pymatgen.analysis.magnetism import Ordering
66

7-
from mp_api.client.core.client import MPRestError
7+
from mp_api.client.core.exceptions import MPRestError
88
from mp_api.client.routes.materials.electronic_structure import (
99
BandStructureRester,
1010
DosRester,

tests/materials/test_phonon.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from emmet.core.phonon import PhononBS, PhononDOS
77

8-
from mp_api.client.core import MPRestError
8+
from mp_api.client.core.exceptions import MPRestError
99
from mp_api.client.routes.materials.phonon import PhononRester
1010

1111
from ..conftest import client_search_testing, requires_api_key

tests/materials/test_summary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from pymatgen.analysis.magnetism import Ordering
88

99
from mp_api.client.routes.materials.summary import SummaryRester
10-
from mp_api.client.core.client import MPRestWarning, MPRestError
10+
from mp_api.client.core.exceptions import MPRestWarning, MPRestError
1111

1212
excluded_params = [
1313
"include_gnome",

tests/test_mprester.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from pymatgen.io.vasp import Chgcar
3434

3535
from mp_api.client import MPRester
36-
from mp_api.client.core.client import MPRestError
36+
from mp_api.client.core.exceptions import MPRestError
3737
from mp_api.client.core.settings import MAPIClientSettings
3838

3939
from .conftest import requires_api_key
@@ -391,12 +391,12 @@ def test_get_default_api_key_endpoint(self, monkeypatch: pytest.MonkeyPatch):
391391
monkeypatch.delenv("MP_API_KEY", raising=False)
392392
monkeypatch.delenv("PMG_MAPI_KEY", raising=False)
393393
monkeypatch.setitem(SETTINGS, "PMG_MAPI_KEY", None)
394-
with pytest.raises(MPRestError, match="No API key found in request"):
394+
with pytest.raises(MPRestError, match="Please obtain a valid API key"):
395395
MPRester().get_structure_by_material_id("mp-149")
396396

397397
def test_invalid_api_key(self, monkeypatch):
398398
monkeypatch.setenv("MP_API_KEY", "INVALID")
399-
with pytest.raises(ValueError, match="Keys for the new API are 32 characters"):
399+
with pytest.raises(MPRestError, match="Valid API keys are 32 characters"):
400400
MPRester().get_structure_by_material_id("mp-149")
401401

402402
def test_get_cohesive_energy_per_atom_utility(self):

0 commit comments

Comments
 (0)