Skip to content

Commit

Permalink
test error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Jul 3, 2023
1 parent 56b4936 commit cb213d9
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 65 deletions.
2 changes: 1 addition & 1 deletion pymatgen/analysis/xas/tests/test_spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,5 @@ def test_site_weighted_spectrum(self):
assert weighted_spectrum.y[0] == approx((4 * self.site1_xanes.y[0] + 2 * self.site2_xanes.y[0]) / 6, abs=1e-2)
assert min(weighted_spectrum.x) == max(min(self.site1_xanes.x), min(self.site2_xanes.x))
self.site2_xanes.absorbing_index = self.site1_xanes.absorbing_index
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Need at least two site-wise spectra to perform site-weighting"):
site_weighted_spectrum([self.site1_xanes, self.site2_xanes])
4 changes: 2 additions & 2 deletions pymatgen/command_line/enumlib_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def get_sg_info(ss):
# enumeration. See Cu7Te5.cif test file.
base *= 10

# base = ndisordered # 10 ** int(math.ceil(math.log10(ndisordered)))
# base = n_disordered # 10 ** int(math.ceil(math.log10(n_disordered)))
# To get a reasonable number of structures, we fix concentrations to the
# range expected in the original structure.
total_amounts = sum(index_amounts)
Expand Down Expand Up @@ -298,7 +298,7 @@ def _run_multienum(self):
timer.cancel()

if timed_out:
raise TimeoutError("Enumeration took too long.")
raise TimeoutError("Enumeration took too long")

else:
output = p.communicate()[0].decode("utf-8")
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/command_line/tests/test_enumlib_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,5 +128,5 @@ def test_timeout(self):
SpacegroupAnalyzer(struct, 0.1)
struct["Al3+"] = {"Al3+": 0.5, "Ga3+": 0.5}
adaptor = EnumlibAdaptor(struct, 1, 1, enum_precision_parameter=0.01, timeout=0.0000000000001)
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError, match="Enumeration took too long"):
adaptor._run_multienum()
10 changes: 5 additions & 5 deletions pymatgen/command_line/tests/test_mcsqs_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def test_mcsqs_caller_supercell(self):
sqs = run_mcsqs(struct, {2: 6, 3: 4}, scaling=[2, 1, 1], search_time=0.01, instances=1)

matches = [sqs.bestsqs.matches(s) for s in self.pzt_structs]
assert True in matches
assert any(matches)

assert isinstance(sqs.bestsqs, Structure)

Expand All @@ -52,15 +52,15 @@ def test_mcsqs_caller_total_atoms(self):
sqs = run_mcsqs(struct, {2: 6, 3: 4}, scaling=2, search_time=0.01, instances=1)

matches = [sqs.bestsqs.matches(s) for s in self.pzt_structs2]
assert True in matches
assert any(matches)

def test_mcsqs_caller_total_atoms_auto_instances(self):
struct = self.struct.copy()
struct.replace_species({"Ti": {"Ti": 0.5, "Zr": 0.5}, "Zr": {"Ti": 0.5, "Zr": 0.5}})
sqs = run_mcsqs(struct, {2: 6, 3: 4}, scaling=2, search_time=0.01, instances=None)

matches = [sqs.bestsqs.matches(s) for s in self.pzt_structs2]
assert True in matches
assert any(matches)

def test_mcsqs_caller_parallel(self):
# explicitly test with four instances
Expand All @@ -70,7 +70,7 @@ def test_mcsqs_caller_parallel(self):
sqs = run_mcsqs(struct, {2: 6, 3: 4}, scaling=2, search_time=0.01, instances=4)

matches = [sqs.bestsqs.matches(s) for s in self.pzt_structs2]
assert True in matches
assert any(matches)

def test_mcsqs_perfect_match_error(self):
scale = 32 / self.perfect_match_zzn_rs.num_sites
Expand Down Expand Up @@ -101,5 +101,5 @@ def test_mcsqs_caller_runtime_error(self):
struct.replace_species({"Ti": {"Ti": 0.5, "Zr": 0.5}, "Zr": {"Ti": 0.5, "Zr": 0.5}})
struct.replace_species({"Pb": {"Ti": 0.2, "Pb": 0.8}})
struct.replace_species({"O": {"F": 0.8, "O": 0.2}})
with pytest.raises(RuntimeError):
with pytest.raises(RuntimeError, match="mcsqs exited before timeout reached"):
run_mcsqs(struct, {2: 6, 3: 4}, 10, 0.000001)
6 changes: 5 additions & 1 deletion pymatgen/core/tests/test_periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,8 +545,12 @@ def test_sort(self):

def test_immutable(self):
sp = Species("Fe", 2, spin=5)
with pytest.raises(AttributeError, match="property 'spin' of 'Species' object has no setter"):
with pytest.raises(AttributeError) as exc:
sp.spin = 6

assert "can't set attribute" in str(exc.value) or "property 'spin' of 'Species' object has no setter" in str(
exc.value
) # 'can't set attribute' on Linux, for some reason different message on Windows and Mac
sp.properties["spin"] = 7
assert sp.spin == 5

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class OrbitalTest(unittest.TestCase):
def test_init(self):
for orb in Orbital:
assert Orbital(orb.value) == orb
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="100 is not a valid Orbital"):
Orbital(100)

def test_cached(self):
Expand Down
8 changes: 6 additions & 2 deletions pymatgen/ext/tests/test_matproj.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,15 @@ def test_get_structure_by_material_id(self):
assert s1.formula == "Cs1"

# requesting via task-id instead of mp-id
with pytest.warns(Warning):
with pytest.warns(
Warning,
match="calculation task mp-698856 is mapped to canonical mp-id mp-1394, so structure for mp-1394 returned",
):
self.rester.get_structure_by_material_id("mp-698856")

# requesting unknown mp-id
with pytest.raises(MPRestError):
# TODO (janosh) this seems like the wrong error message for this case
with pytest.raises(MPRestError, match="'id' is not a valid Element"):
self.rester.get_structure_by_material_id("id-does-not-exist")

def test_get_entry_by_material_id(self):
Expand Down
25 changes: 12 additions & 13 deletions pymatgen/io/babel.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
from pymatgen.core.structure import IMolecule, Molecule

try:
from openbabel import openbabel
from openbabel import pybel as pb
from openbabel import openbabel, pybel
except Exception:
openbabel = None

Expand Down Expand Up @@ -75,7 +74,7 @@ def __init__(self, mol):
self._obmol = ob_mol
elif isinstance(mol, openbabel.OBMol):
self._obmol = mol
elif isinstance(mol, pb.Molecule):
elif isinstance(mol, pybel.Molecule):
self._obmol = mol.OBMol

@property
Expand All @@ -102,9 +101,9 @@ def localopt(self, forcefield="mmff94", steps=500):
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.
"""
pbmol = pb.Molecule(self._obmol)
pbmol.localopt(forcefield=forcefield, steps=steps)
self._obmol = pbmol.OBMol
pybelmol = pybel.Molecule(self._obmol)
pybelmol.localopt(forcefield=forcefield, steps=steps)
self._obmol = pybelmol.OBMol

def make3d(self, forcefield="mmff94", steps=50):
"""
Expand All @@ -125,9 +124,9 @@ def make3d(self, forcefield="mmff94", steps=50):
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 50.
"""
pbmol = pb.Molecule(self._obmol)
pbmol.make3D(forcefield=forcefield, steps=steps)
self._obmol = pbmol.OBMol
pybelmol = pybel.Molecule(self._obmol)
pybelmol.make3D(forcefield=forcefield, steps=steps)
self._obmol = pybelmol.OBMol

def add_hydrogen(self):
"""Add hydrogens (make all hydrogen explicit)."""
Expand Down Expand Up @@ -288,7 +287,7 @@ def confab_conformers(
@property
def pybel_mol(self):
"""Returns Pybel's Molecule object."""
return pb.Molecule(self._obmol)
return pybel.Molecule(self._obmol)

def write_file(self, filename, file_format="xyz"):
"""
Expand All @@ -298,7 +297,7 @@ def write_file(self, filename, file_format="xyz"):
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats.
"""
mol = pb.Molecule(self._obmol)
mol = pybel.Molecule(self._obmol)
return mol.write(file_format, filename, overwrite=True)

@staticmethod
Expand All @@ -316,7 +315,7 @@ def from_file(filename, file_format="xyz", return_all_molecules=False):
Returns:
BabelMolAdaptor object or list thereof
"""
mols = pb.readfile(str(file_format), str(filename))
mols = pybel.readfile(str(file_format), str(filename))
if return_all_molecules:
return [BabelMolAdaptor(mol.OBMol) for mol in mols]

Expand Down Expand Up @@ -348,5 +347,5 @@ def from_string(string_data, file_format="xyz"):
Returns:
BabelMolAdaptor object
"""
mols = pb.readstring(str(file_format), str(string_data))
mols = pybel.readstring(str(file_format), str(string_data))
return BabelMolAdaptor(mols.OBMol)
12 changes: 6 additions & 6 deletions pymatgen/io/lammps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
from pymatgen.util.coord import get_angle

try:
from openbabel import pybel as pb
from openbabel import pybel
except ImportError:
pb = None
pybel = None

__author__ = "Kiran Mathew, Brandon Wood, Michael Humbert"
__email__ = "kmathew@lbl.gov"
Expand Down Expand Up @@ -276,7 +276,7 @@ def _write_input(self, input_dir="."):
# all other filetypes
else:
a = BabelMolAdaptor(mol)
pm = pb.Molecule(a.openbabel_mol)
pm = pybel.Molecule(a.openbabel_mol)
pm.write(
self.control_params["filetype"],
filename=filename,
Expand Down Expand Up @@ -330,7 +330,7 @@ def write_pdb(mol, filename, name=None, num=None):
name = name or f"ml{num}"

# bma = BabelMolAdaptor(mol)
pbm = pb.Molecule(bma._obmol)
pbm = pybel.Molecule(bma._obmol)
for x in pbm.residues:
x.OBResidue.SetName(name)
x.OBResidue.SetNum(num)
Expand All @@ -353,7 +353,7 @@ def convert_obatoms_to_molecule(self, atoms, residue_name=None, site_property="f
Args:
atoms ([OBAtom]): list of OBAtom objects
residue_name (str): the key in self.map_residue_to_mol. Usec to
residue_name (str): the key in self.map_residue_to_mol. Used to
restore the site properties in the final packed molecule.
site_property (str): the site property to be restored.
Expand Down Expand Up @@ -407,7 +407,7 @@ def restore_site_properties(self, site_property="ff_map", filename=None):

filename = filename or self.control_params["output"]
bma = BabelMolAdaptor.from_file(filename, "pdb")
pbm = pb.Molecule(bma._obmol)
pbm = pybel.Molecule(bma._obmol)

assert len(pbm.residues) == sum(x["number"] for x in self.param_list)

Expand Down
16 changes: 5 additions & 11 deletions pymatgen/io/tests/test_babel.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from pymatgen.io.xyz import XYZ
from pymatgen.util.testing import PymatgenTest

pytest.importorskip("openbabel")
pybel = pytest.importorskip("openbabel.pybel")


class BabelMolAdaptorTest(unittest.TestCase):
Expand Down Expand Up @@ -81,18 +81,14 @@ def test_localopt(self):
assert site.distance(optmol[0]) == approx(1.09216, abs=1e-1)

def test_make3d(self):
from openbabel import pybel as pb

mol_0d = pb.readstring("smi", "CCCC").OBMol
mol_0d = pybel.readstring("smi", "CCCC").OBMol
adaptor = BabelMolAdaptor(mol_0d)
adaptor.make3d()
assert mol_0d.GetDimension() == 3

def add_hydrogen(self):
from openbabel import pybel as pb

mol_0d = pb.readstring("smi", "CCCC").OBMol
assert len(pb.Molecule(mol_0d).atoms) == 2
mol_0d = pybel.readstring("smi", "CCCC").OBMol
assert len(pybel.Molecule(mol_0d).atoms) == 2
adaptor = BabelMolAdaptor(mol_0d)
adaptor.add_hydrogen()
assert len(adaptor.pymatgen_mol) == 14
Expand Down Expand Up @@ -126,9 +122,7 @@ def test_rotor_search_rrs(self):
assert site.distance(optmol[0]) == approx(1.09216, abs=1e-1)

def test_confab_conformers(self):
from openbabel import pybel as pb

mol = pb.readstring("smi", "CCCC").OBMol
mol = pybel.readstring("smi", "CCCC").OBMol
adaptor = BabelMolAdaptor(mol)
adaptor.make3d()
conformers = adaptor.confab_conformers()
Expand Down
37 changes: 17 additions & 20 deletions pymatgen/io/vasp/tests/test_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import numpy as np
import pytest
from numpy.testing import assert_allclose
from pytest import approx

from pymatgen.core import Element
Expand Down Expand Up @@ -368,7 +369,7 @@ def test_dielectric_vasp608(self):

def test_indirect_vasprun(self):
vasp_run = Vasprun(self.TEST_FILES_DIR / "vasprun.xml.indirect.gz")
(gap, cbm, vbm, direct) = vasp_run.eigenvalue_band_properties
_gap, _cbm, _vbm, direct = vasp_run.eigenvalue_band_properties
assert not direct

def test_optical_vasprun(self):
Expand All @@ -392,16 +393,12 @@ def test_optical_vasprun(self):
def test_force_constants(self):
vasprun_fc = Vasprun(self.TEST_FILES_DIR / "vasprun.xml.dfpt.phonon", parse_potcar_file=False)
assert vasprun_fc.force_constants.shape == (16, 16, 3, 3)
assert np.allclose(
assert_allclose(
vasprun_fc.force_constants[8, 9],
[
[-0.00184451, -0.0, -0.0],
[-0.0, -0.00933824, -0.03021279],
[-0.0, -0.03021279, 0.01202547],
],
[[-0.00184451, 0, 0], [0, -0.00933824, -0.03021279], [0, -0.03021279, 0.01202547]],
)
assert vasprun_fc.normalmode_eigenvals.size == 48
assert np.allclose(
assert_allclose(
vasprun_fc.normalmode_eigenvals[17:29],
[
-0.59067079,
Expand All @@ -419,7 +416,7 @@ def test_force_constants(self):
],
)
assert vasprun_fc.normalmode_eigenvecs.shape == (48, 16, 3)
assert np.allclose(
assert_allclose(
vasprun_fc.normalmode_eigenvecs[33],
[
[0.0884346, -0.08837289, -0.24995639],
Expand Down Expand Up @@ -1168,8 +1165,8 @@ def test_drift(self):
def test_electrostatic_potential(self):
outcar = Outcar(self.TEST_FILES_DIR / "OUTCAR")
assert outcar.ngf == [54, 30, 54]
assert np.allclose(outcar.sampling_radii, [0.9748, 0.9791, 0.7215])
assert np.allclose(
assert_allclose(outcar.sampling_radii, [0.9748, 0.9791, 0.7215])
assert_allclose(
outcar.electrostatic_potential,
[-26.0704, -45.5046, -45.5046, -72.9539, -73.0621, -72.9539, -73.0621],
)
Expand Down Expand Up @@ -1467,7 +1464,7 @@ def test_init(self):

ans = [1.56472768, 3.25985108, 3.49205728, 3.66275028, 3.8045896, 5.10813352]
myans = self.chgcar_fe3o4.get_integrated_diff(0, 3, 6)
assert np.allclose(myans[:, 1], ans)
assert_allclose(myans[:, 1], ans)

def test_write(self):
self.chgcar_spin.write_file("CHGCAR_pmg")
Expand Down Expand Up @@ -1657,11 +1654,11 @@ def test_init(self):
assert d.nspecs == 2
assert d.natoms == 6
assert d.ndisps == 3
assert np.allclose(d.masses, [63.546, 196.966])
assert_allclose(d.masses, [63.546, 196.966])
assert 4 in d.data
assert 2 in d.data[4]
assert np.allclose(d.data[4][2]["dispvec"], [0.0, 0.05, 0.0])
assert np.allclose(d.data[4][2]["dynmat"][3], [0.055046, -0.298080, 0.0])
assert_allclose(d.data[4][2]["dispvec"], [0.0, 0.05, 0.0])
assert_allclose(d.data[4][2]["dynmat"][3], [0.055046, -0.298080, 0.0])
# TODO: test get_phonon_frequencies once cross-checked


Expand Down Expand Up @@ -1698,8 +1695,8 @@ def test_standard(self):
assert w.encut == 25.0
assert w.nb == 9
assert w.nk == 1
assert np.allclose(w.a, a)
assert np.allclose(w.b, b)
assert_allclose(w.a, a)
assert_allclose(w.b, b)
assert w.vol == approx(vol)
assert len(w.kpoints) == w.nk
assert len(w.coeffs) == w.nk
Expand Down Expand Up @@ -1746,8 +1743,8 @@ def test_n2_45210(self):
assert w.encut == 25.0
assert w.nb == 9
assert w.nk == 1
assert np.allclose(w.a, self.a)
assert np.allclose(w.b, self.b)
assert_allclose(w.a, self.a)
assert_allclose(w.b, self.b)
assert w.vol == approx(self.vol)
assert len(w.kpoints) == w.nk
assert len(w.coeffs) == w.nk
Expand Down Expand Up @@ -1912,7 +1909,7 @@ def test_get_parchg(self):
assert "total" in c.data
assert "diff" not in c.data
assert np.prod(c.data["total"].shape) == np.prod(w.ng * 2)
assert np.allclose(c.data["total"], 0.0)
assert_allclose(c.data["total"], 0.0)

def test_write_unks(self):
unk_std = Unk.from_file(self.TEST_FILES_DIR / "UNK.N2.std")
Expand Down
Loading

0 comments on commit cb213d9

Please sign in to comment.