Skip to content

Commit

Permalink
added exception testing
Browse files Browse the repository at this point in the history
  • Loading branch information
wolearyc committed Aug 4, 2024
1 parent e12aef3 commit e3bf651
Show file tree
Hide file tree
Showing 9 changed files with 484 additions and 88 deletions.
2 changes: 1 addition & 1 deletion docs/coverage-badge.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/tests-badge.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 3 additions & 4 deletions ramannoodle/polarizability/interpolation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
is_collinear_with_all,
)
from ...symmetry import StructuralSymmetry
from ...exceptions import InvalidDOFException
from ...exceptions import InvalidDOFException, get_type_error

from ... import io
from ...io.io_utils import pathify_as_list
Expand Down Expand Up @@ -233,9 +233,8 @@ def add_dof( # pylint: disable=too-many-locals
) from exc
raise exc
except TypeError as exc:
raise TypeError(
"interpolation_order should be int, not "
f"{type(interpolation_order).__name__}"
raise get_type_error(
"interpolation_order", interpolation_order, "int"
) from exc

self._cartesian_basis_vectors += basis_vectors_to_add
Expand Down
16 changes: 12 additions & 4 deletions test/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
from ramannoodle import io


@pytest.fixture
@pytest.fixture(scope="session")
def outcar_path_fixture(request: FixtureRequest) -> Path:
"""Return an outcar path."""
return Path(request.param)


@pytest.fixture
@pytest.fixture(scope="session")
def outcar_file_fixture(
request: FixtureRequest,
) -> Generator[TextIO, None, None]:
Expand All @@ -29,7 +29,15 @@ def outcar_file_fixture(
file.close()


@pytest.fixture
# HACK: indirect fixtures are unable to be scoped, so manually cache.
symmetry_cache = {}


@pytest.fixture(scope="session")
def outcar_symmetry_fixture(request: FixtureRequest) -> StructuralSymmetry:
"""Return a structural symmetry."""
return io.read_structural_symmetry(request.param, file_format="outcar")
if request.param not in symmetry_cache:
symmetry_cache[request.param] = io.read_structural_symmetry(
request.param, file_format="outcar"
)
return symmetry_cache[request.param]
Binary file added test/data/TiO2/known_gaussian_spectrum.npz
Binary file not shown.
Binary file added test/data/TiO2/known_lorentzian_spectrum.npz
Binary file not shown.
254 changes: 254 additions & 0 deletions test/tests/test_interpolation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
"""Testing for the polarizability."""

from typing import Type

import numpy as np
from numpy.typing import NDArray

import pytest

from ramannoodle.polarizability.polarizability_utils import find_duplicates
from ramannoodle.polarizability.interpolation import InterpolationPolarizabilityModel
from ramannoodle.exceptions import InvalidDOFException
from ramannoodle.symmetry import StructuralSymmetry

# pylint: disable=protected-access
# pylint: disable=too-many-arguments


@pytest.mark.parametrize(
"vectors, known",
[
(np.array([-0.05, 0.05, 0.01, -0.01]), None),
(np.array([-0.05, 0.05, -0.05, -0.01]), -0.05),
],
)
def test_find_duplicates(vectors: NDArray[np.float64], known: bool) -> None:
"""Test for find_duplicates (success)."""
assert find_duplicates(vectors) == known


@pytest.mark.parametrize(
"vectors, exception_type, in_reason",
[
(1, TypeError, "should have type Iterable, not int"),
(["string", TypeError, "not array_like"]),
],
)
def test_find_duplicates_exception(
vectors: NDArray[np.float64], exception_type: Type[Exception], in_reason: str
) -> None:
"""Test for find_duplicates (exception)."""
with pytest.raises(exception_type) as error:
find_duplicates(vectors)
assert in_reason in str(error.value)


@pytest.mark.parametrize(
"outcar_symmetry_fixture,displaced_atom_index, amplitudes, known_dof_added",
[
("test/data/STO_RATTLED_OUTCAR", 0, np.array([-0.05, 0.05, 0.01, -0.01]), 1),
("test/data/TiO2/phonons_OUTCAR", 0, np.array([0.01]), 72),
],
indirect=["outcar_symmetry_fixture"],
)
def test_add_dof(
outcar_symmetry_fixture: StructuralSymmetry,
displaced_atom_index: int,
amplitudes: NDArray[np.float64],
known_dof_added: int,
) -> None:
"""Test add_dof (normal)."""
symmetry = outcar_symmetry_fixture
model = InterpolationPolarizabilityModel(symmetry, np.zeros((3, 3)))
displacement = symmetry._fractional_positions * 0
displacement[displaced_atom_index][0] = 1.0
polarizabilities = np.zeros((len(amplitudes), 3, 3))
model.add_dof(displacement, amplitudes, polarizabilities, 1)
assert len(model._cartesian_basis_vectors) == known_dof_added
assert np.isclose(np.linalg.norm(model._cartesian_basis_vectors[0]), 1)


@pytest.mark.parametrize(
"outcar_symmetry_fixture,displaced_atom_indexes, amplitudes,polarizabilities,"
"interpolation_order,exception_type,in_reason",
[
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
np.zeros((1, 3, 3)),
4,
InvalidDOFException,
"insufficient points",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1, 0.1]),
np.zeros((1, 3, 3)),
1,
ValueError,
"polarizabilities has wrong shape",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
np.zeros((2, 3, 3)),
1,
ValueError,
"polarizabilities has wrong shape",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
np.zeros((2, 3, 3)),
1,
ValueError,
"polarizabilities has wrong shape",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0], [0, 1]],
np.array([0.1]),
np.zeros((1, 3, 3)),
1,
InvalidDOFException,
"not orthogonal",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
[0.1],
np.zeros((1, 3, 3)),
1,
TypeError,
"amplitudes should have type ndarray, not list",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
list(np.zeros((1, 3, 3))),
1,
TypeError,
"polarizabilities should have type ndarray, not list",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
np.zeros((1, 2, 2)),
1,
ValueError,
"polarizabilities has wrong shape: (1,2,2) != (1,3,3)",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1]),
np.zeros((1, 3, 3)),
-1.6,
TypeError,
"interpolation_order should have type int, not float",
),
(
"test/data/STO_RATTLED_OUTCAR",
[[0]],
np.array([0.1, 0.1]),
np.zeros((2, 3, 3)),
-1.6,
InvalidDOFException,
"due to symmetry, amplitude 0.1 should not be specified",
),
],
indirect=["outcar_symmetry_fixture"],
)
def test_add_dof_exception(
outcar_symmetry_fixture: StructuralSymmetry,
displaced_atom_indexes: list[list[int]],
amplitudes: NDArray[np.float64],
polarizabilities: NDArray[np.float64],
interpolation_order: int,
exception_type: Type[Exception],
in_reason: str,
) -> None:
"""Test add_dof (exception)."""
symmetry = outcar_symmetry_fixture
model = InterpolationPolarizabilityModel(symmetry, np.zeros((3, 3)))
with pytest.raises(exception_type) as error:
for atom_indexes in displaced_atom_indexes:
for atom_index in atom_indexes:
displacement = symmetry.get_fractional_positions() * 0
displacement[atom_index] = 1
model.add_dof(
displacement, amplitudes, polarizabilities, interpolation_order
)

assert in_reason in str(error.value)


@pytest.mark.parametrize(
"outcar_symmetry_fixture,outcar_files,interpolation_order,exception_type,in_reason",
[
(
"test/data/STO_RATTLED_OUTCAR",
["test/data/TiO2/Ti5_0.1x_eps_OUTCAR"],
1,
InvalidDOFException,
"incompatible outcar",
),
(
"test/data/TiO2/phonons_OUTCAR",
["test/data/TiO2/Ti5_0.1x_eps_OUTCAR"],
3,
InvalidDOFException,
"insufficient points (3)",
),
(
"test/data/TiO2/phonons_OUTCAR",
[
"test/data/TiO2/Ti5_0.1x_eps_OUTCAR",
"test/data/TiO2/Ti5_0.1x_eps_OUTCAR",
],
1,
InvalidDOFException,
"due to symmetry, amplitude",
),
(
"test/data/TiO2/phonons_OUTCAR",
[
"this_outcar_does_not_exist",
],
1,
FileNotFoundError,
"No such file or directory",
),
(
"test/data/TiO2/phonons_OUTCAR",
[
"test/data/TiO2/Ti5_0.1x_eps_OUTCAR",
"test/data/TiO2/Ti5_0.1y_eps_OUTCAR",
],
1,
InvalidDOFException,
"is not collinear",
),
],
indirect=["outcar_symmetry_fixture"],
)
def test_add_dof_from_files_exception(
outcar_symmetry_fixture: StructuralSymmetry,
outcar_files: list[str],
interpolation_order: int,
exception_type: Type[Exception],
in_reason: str,
) -> None:
"""Test exceptions in add_dof_from_files."""
symmetry = outcar_symmetry_fixture
model = InterpolationPolarizabilityModel(symmetry, np.zeros((3, 3)))
with pytest.raises(exception_type) as error:
model.add_dof_from_files(outcar_files, "outcar", interpolation_order)
assert in_reason in str(error.value)
77 changes: 0 additions & 77 deletions test/tests/test_polarizability.py

This file was deleted.

Loading

0 comments on commit e3bf651

Please sign in to comment.