Skip to content

Commit

Permalink
remove unneeded unittest tearDown methods
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Jan 26, 2024
1 parent 9a0eb81 commit e9cc87a
Show file tree
Hide file tree
Showing 19 changed files with 85 additions and 112 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Runs the complete test suite incl. many external command line dependencies (like Openbabel)
# as well as the pymatgen.ext package. Coverage is computed based on this workflow.
# as well as the pymatgen.ext package. Coverage used to be computed based on this workflow.
name: Tests

on:
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def _get_reaction(self, x: float) -> Reaction:

reactants = self._get_reactants(x)

product = [Composition(k.name) for k, v in decomp.items()]
product = [Composition(entry.name) for entry in decomp]
reaction = Reaction(reactants, product)

x_original = self._get_original_composition_ratio(reaction)
Expand Down Expand Up @@ -695,7 +695,7 @@ def get_no_mixing_energy(self):
def _get_reactants(self, x: float) -> list[Composition]:
"""Returns a list of relevant reactant compositions given an x coordinate."""
reactants = super()._get_reactants(x)
reactants += [Composition(e.symbol) for e, v in self.pd.chempots.items()]
reactants += [Composition(entry.symbol) for entry in self.pd.chempots]

return reactants

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,7 @@ def get_critical_compositions(self, comp1, comp2):
num_atoms = n1 + (n2 - n1) * x_unnormalized
cs *= num_atoms[:, None]

return [Composition((c, v) for c, v in zip(pd_els, m)) for m in cs]
return [Composition((elem, val) for elem, val in zip(pd_els, m)) for m in cs]

def get_element_profile(self, element, comp, comp_tol=1e-5):
"""
Expand Down
10 changes: 5 additions & 5 deletions pymatgen/analysis/reaction_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,16 +367,16 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): from as_dict().
dct (dict): from as_dict().
Returns:
A Reaction object.
Reaction
"""
reactants = [Composition(sym_amt) for sym_amt in d["reactants"]]
products = [Composition(sym_amt) for sym_amt in d["products"]]
reactants = [*map(Composition, dct["reactants"])]
products = [*map(Composition, dct["products"])]
return cls(reactants, products)


Expand Down
16 changes: 8 additions & 8 deletions pymatgen/io/abinit/abiobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,16 +605,16 @@ def as_dict(self):
return dct

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""Build object from dictionary."""
d = d.copy()
d.pop("@module", None)
d.pop("@class", None)
dct = dct.copy()
dct.pop("@module", None)
dct.pop("@class", None)
dec = MontyDecoder()
d["spin_mode"] = dec.process_decoded(d["spin_mode"])
d["smearing"] = dec.process_decoded(d["smearing"])
d["algorithm"] = dec.process_decoded(d["algorithm"]) if d["algorithm"] else None
return cls(**d)
dct["spin_mode"] = dec.process_decoded(dct["spin_mode"])
dct["smearing"] = dec.process_decoded(dct["smearing"])
dct["algorithm"] = dec.process_decoded(dct["algorithm"]) if dct["algorithm"] else None
return cls(**dct)

def to_abivars(self):
"""Return dictionary with Abinit variables."""
Expand Down
2 changes: 1 addition & 1 deletion tests/analysis/test_interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def test_get_reaction(self):

def test_get_get_elmt_amt_in_rxt(self):
rxt1 = Reaction(
[Composition("Mn"), Composition("O2"), Composition("Li")],
[*map(Composition, ["Mn", "O2", "Li"])],
[Composition("LiMnO2")],
)
test1 = np.isclose(self.irs[2]._get_elem_amt_in_rxn(rxt1), 3)
Expand Down
10 changes: 0 additions & 10 deletions tests/analysis/test_local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,6 @@ def test_filtered(self):
all_nns = nn.get_all_nn_info(bcc * [2, 2, 2])
assert [len(x) for x in all_nns] == [8] * 16

def tearDown(self):
del self.struct
del self.nn


class TestJmolNN(PymatgenTest):
def setUp(self):
Expand Down Expand Up @@ -562,12 +558,6 @@ def test_get_neighbors_of_site_with_index(self):
assert len(get_neighbors_of_site_with_index(self.diamond, 0, approach="min_OKeeffe")) == 4
assert len(get_neighbors_of_site_with_index(self.diamond, 0, approach="min_VIRE")) == 4

def tearDown(self):
del self.silicon
del self.diamond
del self.nacl
del self.cscl


class TestNearNeighbor(PymatgenTest):
def setUp(self):
Expand Down
11 changes: 5 additions & 6 deletions tests/analysis/test_phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ def test_as_from_dict(self):

assert entry.name == "mp-757614"
assert entry.energy_per_atom == 53.0 / 4
gpentry = GrandPotPDEntry.from_dict(gpd)
assert gpentry.name == "mp-757614"
assert gpentry.energy_per_atom == 50.0 / 2
gp_entry = GrandPotPDEntry.from_dict(gpd)
assert gp_entry.name == "mp-757614"
assert gp_entry.energy_per_atom == 50.0 / 2

d_anon = d.copy()
del d_anon["name"]
Expand All @@ -109,12 +109,11 @@ def setUp(self):
comp = Composition("LiFeO2")
entry = PDEntry(comp, 53)

terminal_compositions = ["Li2O", "FeO", "LiO8"]
terminal_compositions = [Composition(c) for c in terminal_compositions]
terminal_compositions = [*map(Composition, ("Li2O", "FeO", "LiO8"))]

sp_mapping = {}
for idx, comp in enumerate(terminal_compositions):
sp_mapping[comp] = DummySpecies("X" + chr(102 + idx))
sp_mapping[comp] = DummySpecies(f"X{chr(102 + idx)}")

self.transformed_entry = TransformedPDEntry(entry, sp_mapping)

Expand Down
6 changes: 3 additions & 3 deletions tests/analysis/test_structure_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,9 +342,9 @@ def test_as_dict_and_from_dict(self):
scale=False,
comparator=FrameworkComparator(),
)
d = sm.as_dict()
sm2 = StructureMatcher.from_dict(d)
assert sm2.as_dict() == d
dct = sm.as_dict()
sm2 = StructureMatcher.from_dict(dct)
assert sm2.as_dict() == dct

def test_no_scaling(self):
sm = StructureMatcher(ltol=0.1, stol=0.1, angle_tol=2, scale=False, comparator=ElementComparator())
Expand Down
16 changes: 8 additions & 8 deletions tests/apps/battery/test_conversion_battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ def test_init(self):

# try to export/import a voltage pair via a dict
pair = c.voltage_pairs[0]
d = pair.as_dict()
pair2 = ConversionVoltagePair.from_dict(d)
dct = pair.as_dict()
pair2 = ConversionVoltagePair.from_dict(dct)
for prop in ["voltage", "mass_charge", "mass_discharge"]:
assert getattr(pair, prop) == getattr(pair2, prop), 2

# try to create an electrode from a dict and test methods
d = c.as_dict()
electrode = ConversionElectrode.from_dict(d)
dct = c.as_dict()
electrode = ConversionElectrode.from_dict(dct)
for k, v in p.items():
assert getattr(electrode, "get_" + k)() == approx(v, abs=1e-2)

Expand All @@ -121,14 +121,14 @@ def test_repr(self):
)

def test_summary(self):
kmap = {"specific_energy": "energy_grav", "energy_density": "energy_vol"}
key_map = {"specific_energy": "energy_grav", "energy_density": "energy_vol"}
for f in self.formulas:
c = self.conversion_electrodes[f]["CE"]
d = c.get_summary_dict()
dct = c.get_summary_dict()
p = self.expected_properties[f]
for k, v in p.items():
summary_key = kmap.get(k, k)
assert d[summary_key] == approx(v, abs=1e-2)
summary_key = key_map.get(k, k)
assert dct[summary_key] == approx(v, abs=1e-2)

def test_composite(self):
# check entries in charged/discharged state
Expand Down
20 changes: 10 additions & 10 deletions tests/apps/battery/test_insertion_battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ def test_get_all_entries(self):
self.ie_LTO.get_all_entries()

def test_as_from_dict(self):
d = self.ie_LTO.as_dict()
ie = InsertionElectrode.from_dict(d)
dct = self.ie_LTO.as_dict()
ie = InsertionElectrode.from_dict(dct)
assert ie.max_voltage == approx(2.78583901)
assert ie.min_voltage == approx(0.89702381)
assert ie.get_average_voltage() == approx(1.84143141)
Expand Down Expand Up @@ -112,14 +112,14 @@ def test_voltage_pair(self):
assert vv.voltage == approx(2.78583901)

def test_get_summary_dict(self):
d = self.ie_CMO.get_summary_dict()
assert d["stability_charge"] == approx(0.2346574583333325)
assert d["stability_discharge"] == approx(0.33379544031249786)
assert d["muO2_data"]["mp-714969"][0]["chempot"] == approx(-4.93552791875)

assert d["adj_pairs"][0]["muO2_data"]["mp-714969"][0]["chempot"] == approx(-4.93552791875)
assert d["framework_formula"] == "MoO2"
assert d["adj_pairs"][1]["framework_formula"] == "MoO2"
dct = self.ie_CMO.get_summary_dict()
assert dct["stability_charge"] == approx(0.2346574583333325)
assert dct["stability_discharge"] == approx(0.33379544031249786)
assert dct["muO2_data"]["mp-714969"][0]["chempot"] == approx(-4.93552791875)

assert dct["adj_pairs"][0]["muO2_data"]["mp-714969"][0]["chempot"] == approx(-4.93552791875)
assert dct["framework_formula"] == "MoO2"
assert dct["adj_pairs"][1]["framework_formula"] == "MoO2"

def test_init_no_structure(self):
def remove_structure(entries):
Expand Down
16 changes: 8 additions & 8 deletions tests/apps/borg/test_hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def test_get_valid_paths(self):

def test_assimilate(self):
entry = self.drone.assimilate(TEST_FILES_DIR)
for p in ["hubbards", "is_hubbard", "potcar_spec", "run_type"]:
assert p in entry.parameters
for param in ("hubbards", "is_hubbard", "potcar_spec", "run_type"):
assert param in entry.parameters
assert entry.data["efermi"] == approx(-6.62148548)
assert entry.composition.reduced_formula == "Xe"
assert entry.energy == approx(0.5559329)
Expand All @@ -39,8 +39,8 @@ def test_assimilate(self):
# assert len(entry.parameters["history"]) == 2

def test_as_from_dict(self):
d = self.structure_drone.as_dict()
drone = VaspToComputedEntryDrone.from_dict(d)
dct = self.structure_drone.as_dict()
drone = VaspToComputedEntryDrone.from_dict(dct)
assert isinstance(drone, VaspToComputedEntryDrone)


Expand All @@ -55,8 +55,8 @@ def test_get_valid_paths(self):
assert len(self.drone.get_valid_paths(path)) > 0

def test_as_from_dict(self):
d = self.structure_drone.as_dict()
drone = SimpleVaspToComputedEntryDrone.from_dict(d)
dct = self.structure_drone.as_dict()
drone = SimpleVaspToComputedEntryDrone.from_dict(dct)
assert isinstance(drone, SimpleVaspToComputedEntryDrone)


Expand Down Expand Up @@ -95,6 +95,6 @@ def test_assimilate(self):
assert p in entry.data

def test_as_from_dict(self):
d = self.structure_drone.as_dict()
drone = GaussianToComputedEntryDrone.from_dict(d)
dct = self.structure_drone.as_dict()
drone = GaussianToComputedEntryDrone.from_dict(dct)
assert isinstance(drone, GaussianToComputedEntryDrone)
6 changes: 3 additions & 3 deletions tests/command_line/test_critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ def test_properties_to_from_dict(self):
# test connectivity
assert self.c2o.edges[3] == {"from_idx": 1, "from_lvec": (0, 0, 0), "to_idx": 0, "to_lvec": (1, 0, 0)}
# test as/from dict
d = self.c2o.as_dict()
assert set(d) == {
dct = self.c2o.as_dict()
assert set(dct) == {
"@module",
"@class",
"@version",
Expand All @@ -128,7 +128,7 @@ def test_properties_to_from_dict(self):
"yt",
"zpsp",
}
self.c2o.from_dict(d)
self.c2o.from_dict(dct)

def test_graph_output(self):
sg = self.c2o.structure_graph()
Expand Down
11 changes: 3 additions & 8 deletions tests/core/test_composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,12 @@ def test_indeterminate_formula(self):
["Co2 O3", "C1 O5"],
["N1 Ca1 Lu1", "U1 Al1 C1 N1"],
["N1 Ca1 Lu1", "U1 Al1 C1 N1"],
[
"Li1 Co1 P2 N1 O10",
"Li1 Co1 Po8 N1 O2",
"Li1 P2 C1 N1 O11",
"Li1 Po8 C1 N1 O3",
],
["Li1 Co1 P2 N1 O10", "Li1 Co1 Po8 N1 O2", "Li1 P2 C1 N1 O11", "Li1 Po8 C1 N1 O3"],
["Co2 P4 O4", "Co2 Po4", "P4 C2 O6", "Po4 C2 O2"],
[],
]
for i, c in enumerate(correct_formulas):
assert [Composition(comp) for comp in c] == self.indeterminate_comp[i]
for idx, formulas in enumerate(correct_formulas):
assert [*map(Composition, formulas)] == self.indeterminate_comp[idx]

def test_alphabetical_formula(self):
correct_formulas = [
Expand Down
14 changes: 7 additions & 7 deletions tests/core/test_ion.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ def test_from_dict(self):
assert Ion.from_dict(sym_dict).reduced_formula == "PO4[-2]", "Creation form sym_amount dictionary failed!"

def test_as_dict(self):
c = Ion.from_dict({"Mn": 1, "O": 4, "charge": -1})
d = c.as_dict()
ion = Ion.from_dict({"Mn": 1, "O": 4, "charge": -1})
dct = ion.as_dict()
correct_dict = {"Mn": 1.0, "O": 4.0, "charge": -1.0}
assert d == correct_dict
assert d["charge"] == correct_dict["charge"]
assert dct == correct_dict
assert dct["charge"] == correct_dict["charge"]
correct_dict = {"Mn": 1.0, "O": 4.0, "charge": -1}
d = c.to_reduced_dict
assert d == correct_dict
assert d["charge"] == correct_dict["charge"]
dct = ion.to_reduced_dict
assert dct == correct_dict
assert dct["charge"] == correct_dict["charge"]

def test_equals(self):
random_z = random.randint(1, 92)
Expand Down
4 changes: 2 additions & 2 deletions tests/core/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ def test_are_symmetrically_related_vectors(self):
assert self.op.are_symmetrically_related_vectors(to_a, from_a, -r_a, from_b, to_b, r_b)[1]

def test_as_from_dict(self):
d = self.op.as_dict()
op = SymmOp.from_dict(d)
dct = self.op.as_dict()
op = SymmOp.from_dict(dct)
point = np.random.rand(3)
new_coord = self.op.operate(point)
assert op.are_symmetrically_related(point, new_coord)
Expand Down
27 changes: 13 additions & 14 deletions tests/core/test_periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ def test_nan_x(self):

def test_dict(self):
fe = Element.Fe
d = fe.as_dict()
assert fe == Element.from_dict(d)
dct = fe.as_dict()
assert fe == Element.from_dict(dct)

def test_block(self):
cases = {
Expand Down Expand Up @@ -238,8 +238,8 @@ def test_attributes(self):
("O", "Te"): "is_chalcogen",
}

for k, v in is_true.items():
for sym in k:
for key, v in is_true.items():
for sym in key:
assert getattr(Element(sym), v), f"{sym=} is false"

keys = [
Expand Down Expand Up @@ -286,16 +286,15 @@ def test_attributes(self):
# Test all elements up to Uranium
for idx in range(1, 104):
el = Element.from_Z(idx)
d = el.data
for k in keys:
k_str = k.capitalize().replace("_", " ")
if k_str in d and (not str(d[k_str]).startswith("no data")):
assert getattr(el, k) is not None
elif k == "long_name":
assert el.long_name == d["Name"]
elif k == "iupac_ordering":
assert "IUPAC ordering" in d
assert getattr(el, k) is not None
for key in keys:
k_str = key.capitalize().replace("_", " ")
if k_str in el.data and (not str(el.data[k_str]).startswith("no data")):
assert getattr(el, key) is not None
elif key == "long_name":
assert el.long_name == el.data["Name"]
elif key == "iupac_ordering":
assert "IUPAC ordering" in el.data
assert getattr(el, key) is not None
el = Element.from_Z(idx)
if len(el.oxidation_states) > 0:
assert max(el.oxidation_states) == el.max_oxidation_state
Expand Down
Loading

0 comments on commit e9cc87a

Please sign in to comment.