From e9cc87a22e61a3e75bd3a68b96bad699fc29a485 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Fri, 26 Jan 2024 12:08:00 +0100 Subject: [PATCH] remove unneeded unittest tearDown methods --- .github/workflows/test.yml | 2 +- pymatgen/analysis/interface_reactions.py | 4 +-- pymatgen/analysis/phase_diagram.py | 2 +- pymatgen/analysis/reaction_calculator.py | 10 +++---- pymatgen/io/abinit/abiobjects.py | 16 +++++------ tests/analysis/test_interface_reactions.py | 2 +- tests/analysis/test_local_env.py | 10 ------- tests/analysis/test_phase_diagram.py | 11 ++++---- tests/analysis/test_structure_matcher.py | 6 ++--- tests/apps/battery/test_conversion_battery.py | 16 +++++------ tests/apps/battery/test_insertion_battery.py | 20 +++++++------- tests/apps/borg/test_hive.py | 16 +++++------ tests/command_line/test_critic2_caller.py | 6 ++--- tests/core/test_composition.py | 11 +++----- tests/core/test_ion.py | 14 +++++----- tests/core/test_operations.py | 4 +-- tests/core/test_periodic_table.py | 27 +++++++++---------- tests/ext/test_matproj.py | 3 --- tests/io/lammps/test_data.py | 17 ++++-------- 19 files changed, 85 insertions(+), 112 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 58b83a114a3..9cb6a17465b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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: diff --git a/pymatgen/analysis/interface_reactions.py b/pymatgen/analysis/interface_reactions.py index 68b21094da3..e0fd752a837 100644 --- a/pymatgen/analysis/interface_reactions.py +++ b/pymatgen/analysis/interface_reactions.py @@ -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) @@ -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 diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 5f349651937..38f6d6719df 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -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): """ diff --git a/pymatgen/analysis/reaction_calculator.py b/pymatgen/analysis/reaction_calculator.py index 7933761feff..ee1ce7dbaec 100644 --- a/pymatgen/analysis/reaction_calculator.py +++ b/pymatgen/analysis/reaction_calculator.py @@ -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) diff --git a/pymatgen/io/abinit/abiobjects.py b/pymatgen/io/abinit/abiobjects.py index 94f2d19829d..7a4f16b5387 100644 --- a/pymatgen/io/abinit/abiobjects.py +++ b/pymatgen/io/abinit/abiobjects.py @@ -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.""" diff --git a/tests/analysis/test_interface_reactions.py b/tests/analysis/test_interface_reactions.py index 73566f7691e..453be3dd6d8 100644 --- a/tests/analysis/test_interface_reactions.py +++ b/tests/analysis/test_interface_reactions.py @@ -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) diff --git a/tests/analysis/test_local_env.py b/tests/analysis/test_local_env.py index 9665d1908ea..5a63631f753 100644 --- a/tests/analysis/test_local_env.py +++ b/tests/analysis/test_local_env.py @@ -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): @@ -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): diff --git a/tests/analysis/test_phase_diagram.py b/tests/analysis/test_phase_diagram.py index beec36a4027..bc65b4b6ddc 100644 --- a/tests/analysis/test_phase_diagram.py +++ b/tests/analysis/test_phase_diagram.py @@ -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"] @@ -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) diff --git a/tests/analysis/test_structure_matcher.py b/tests/analysis/test_structure_matcher.py index d61efe3aea3..07c38d60ffd 100644 --- a/tests/analysis/test_structure_matcher.py +++ b/tests/analysis/test_structure_matcher.py @@ -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()) diff --git a/tests/apps/battery/test_conversion_battery.py b/tests/apps/battery/test_conversion_battery.py index 742087a4724..337af2b1263 100644 --- a/tests/apps/battery/test_conversion_battery.py +++ b/tests/apps/battery/test_conversion_battery.py @@ -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) @@ -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 diff --git a/tests/apps/battery/test_insertion_battery.py b/tests/apps/battery/test_insertion_battery.py index abb277d4593..129cb66159f 100644 --- a/tests/apps/battery/test_insertion_battery.py +++ b/tests/apps/battery/test_insertion_battery.py @@ -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) @@ -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): diff --git a/tests/apps/borg/test_hive.py b/tests/apps/borg/test_hive.py index c7bd4900ff2..fcfb15110ad 100644 --- a/tests/apps/borg/test_hive.py +++ b/tests/apps/borg/test_hive.py @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/tests/command_line/test_critic2_caller.py b/tests/command_line/test_critic2_caller.py index dfe26885b21..48792b03fde 100644 --- a/tests/command_line/test_critic2_caller.py +++ b/tests/command_line/test_critic2_caller.py @@ -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", @@ -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() diff --git a/tests/core/test_composition.py b/tests/core/test_composition.py index 054fcbf5a62..5e53f8d8e6a 100644 --- a/tests/core/test_composition.py +++ b/tests/core/test_composition.py @@ -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 = [ diff --git a/tests/core/test_ion.py b/tests/core/test_ion.py index c8e205c62c0..192e694eb75 100644 --- a/tests/core/test_ion.py +++ b/tests/core/test_ion.py @@ -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) diff --git a/tests/core/test_operations.py b/tests/core/test_operations.py index 2f0fe855d3f..673490f3f7a 100644 --- a/tests/core/test_operations.py +++ b/tests/core/test_operations.py @@ -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) diff --git a/tests/core/test_periodic_table.py b/tests/core/test_periodic_table.py index b3aa9d7e41e..b4885cbe852 100644 --- a/tests/core/test_periodic_table.py +++ b/tests/core/test_periodic_table.py @@ -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 = { @@ -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 = [ @@ -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 diff --git a/tests/ext/test_matproj.py b/tests/ext/test_matproj.py index 875482131ba..db85da9902a 100644 --- a/tests/ext/test_matproj.py +++ b/tests/ext/test_matproj.py @@ -43,9 +43,6 @@ class TestMPResterOld(PymatgenTest): def setUp(self): self.rester = _MPResterLegacy() - def tearDown(self): - self.rester.session.close() - def test_get_all_materials_ids_doc(self): mids = self.rester.get_materials_ids("Al2O3") random.shuffle(mids) diff --git a/tests/io/lammps/test_data.py b/tests/io/lammps/test_data.py index e4ebc0ad607..5001fdbefc4 100644 --- a/tests/io/lammps/test_data.py +++ b/tests/io/lammps/test_data.py @@ -2,7 +2,6 @@ import gzip import json -import os import random import unittest @@ -646,7 +645,7 @@ def test_from_bonding(self): assert "Dihedrals" not in topo_etoh2.topologies -class TestForceField(unittest.TestCase): +class TestForceField(PymatgenTest): @classmethod def setUpClass(cls): mass_info = [ @@ -655,7 +654,7 @@ def setUpClass(cls): ("C", Element("O")), ("D", 1.00794), ] - nonbond_coeffs = [ + non_bond_coeffs = [ [1, 1, 1.1225], [1, 1.175, 1.31894], [1, 1.55, 1.73988], @@ -673,7 +672,7 @@ def setUpClass(cls): {"coeffs": [50, 0.855906], "types": [("B", "C")]}, ] } - cls.virus = ForceField(mass_info=mass_info, nonbond_coeffs=nonbond_coeffs, topo_coeffs=topo_coeffs) + cls.virus = ForceField(mass_info=mass_info, nonbond_coeffs=non_bond_coeffs, topo_coeffs=topo_coeffs) cls.ethane = ForceField.from_file(f"{TEST_DIR}/ff_ethane.yaml") def test_init(self): @@ -728,13 +727,12 @@ def test_init(self): def test_to_file(self): filename = "ff_test.yaml" - v = self.virus - v.to_file(filename=filename) + self.virus.to_file(filename=f"{self.tmp_path}/{filename}") yaml = YAML() with open(filename) as file: dct = yaml.load(file) # assert dct["mass_info"] == [list(m) for m in v.mass_info] - assert dct["nonbond_coeffs"] == v.nonbond_coeffs + assert dct["nonbond_coeffs"] == self.virus.nonbond_coeffs def test_from_file(self): e = self.ethane @@ -759,11 +757,6 @@ def test_from_dict(self): assert decoded.nonbond_coeffs == self.ethane.nonbond_coeffs assert decoded.topo_coeffs == self.ethane.topo_coeffs - @classmethod - def tearDownClass(cls): - if os.path.exists("ff_test.yaml"): - os.remove("ff_test.yaml") - class TestFunc(unittest.TestCase): def test_lattice_2_lmpbox(self):