diff --git a/docs/contributing.md b/docs/contributing.md index 3080cdb14d1..0bc32d675bf 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -13,13 +13,13 @@ the [`pymatgen` GitHub repo](https://github.com/materialsproject/pymatgen). Here 1. Create a free GitHub account (if you don't already have one) and perform the necessary setup (e.g., install SSH keys etc.). -1. Fork the `pymatgen` GitHub repo, i.e., go to the +2. Fork the `pymatgen` GitHub repo, i.e., go to the main [`pymatgen` GitHub repo](https://github.com/materialsproject/pymatgen) and click fork to create a copy of the `pymatgen` code base on your own GitHub account. -1. Install `git` on your local machine (if you don't already have it). +3. Install `git` on your local machine (if you don't already have it). -1. Clone *your forked repo* to your local machine. You will work mostly with your local repo and only publish changes +4. Clone *your forked repo* to your local machine. You will work mostly with your local repo and only publish changes when they are ready to be merged: ```sh @@ -30,33 +30,33 @@ the [`pymatgen` GitHub repo](https://github.com/materialsproject/pymatgen). Here Note that the entire Github repo is fairly large because of the presence of test files, but these are necessary for rigorous testing. -1. Install the [uv package manager](https://github.com/astral-sh/uv): +5. Install the [uv package manager](https://github.com/astral-sh/uv): ```sh pip install uv ``` -1. Create a virtual env for pymatgen. +6. Create a virtual env for pymatgen. ```sh uv create venv # A virtual env will be created in the .venv directory in the repo. source .venv/bin/activate ``` -1. Install pymatgen in editable mode with dev and optional dependencies: +7. Install pymatgen in editable mode with dev and optional dependencies: ```sh uv pip install -e '.[ci,optional]' pre-commit install # Install pre-commit hook for linters. ``` -1. Make a new branch for your contributions +8. Make a new branch for your contributions ```sh git checkout -b my-new-fix-or-feature # should be run from up-to-date master ``` -1. Code (see [Coding Guidelines](#coding-guidelines)). Commit early and commit often. Keep your code up to date. You +9. Code (see [Coding Guidelines](#coding-guidelines)). Commit early and commit often. Keep your code up to date. You need to add the main repository to the list of your remotes. ```sh @@ -79,24 +79,24 @@ the [`pymatgen` GitHub repo](https://github.com/materialsproject/pymatgen). Here Remember, pull is a combination of the commands fetch and merge, so there may be merge conflicts to be manually resolved. -1. Publish your contributions. Assuming that you now have a couple of commits that you would like to contribute to the +10. Publish your contributions. Assuming that you now have a couple of commits that you would like to contribute to the main repository. Please follow the following steps: 1. If your change is based on a relatively old state of the main repository, then you should probably bring your repository up-to-date first to see if the change is not creating any merge conflicts. - 1. Check that everything compiles cleanly and passes all tests. The `pymatgen` repo comes with a complete set of + 2. Check that everything compiles cleanly and passes all tests. The `pymatgen` repo comes with a complete set of tests for all modules. If you have written new modules or methods, you must write tests for the new code as well (see [Coding Guidelines](#coding-guidelines)). Install and run `pytest` in your local repo directory and fix all errors before continuing further. - 1. If everything is ok, publish the commits to your GitHub repository. + 3. If everything is ok, publish the commits to your GitHub repository. ```sh git push origin master ``` -1. Now that your commit is published, it doesn't mean that it has already been merged into the main repository. You +11. Now that your commit is published, it doesn't mean that it has already been merged into the main repository. You should issue a merge request to `pymatgen` maintainers. They will pull your commits and run their own tests before releasing. @@ -111,8 +111,8 @@ guidelines for all contributions to `pymatgen`. The following must be satisfied into `pymatgen`. 1. **Unit tests** are required for all new modules and methods. The only way to minimize code regression is to ensure - that all code is well tested. Untested contributions will not be accepted. -1. **Python PEP 8** [code style](https://python.org/dev/peps/pep-0008). We allow a few exceptions when they are + that all code is well tested. Untested contributions will not be accepted. Please use the modern [`pytest`](https://docs.pytest.org/en/stable/how-to/index.html) framework for tests and avoid the legacy `unittest` style. +2. **Python PEP 8** [code style](https://python.org/dev/peps/pep-0008). We allow a few exceptions when they are well-justified (e.g., Element's atomic number is given a variable name of capital Z, in line with accepted scientific convention), but generally, PEP 8 must be observed. Code style will be automatically checked for all PRs and must pass before any PR is merged. To aid you, you can install and run the same set of formatters and linters that will @@ -125,8 +125,8 @@ into `pymatgen`. pre-commit run --all-files # ensure your entire codebase passes linters ``` -1. **Python 3**. Check the `pyproject.toml` for the supported Python versions. -1. **Documentation** is required for all modules, classes and methods. In particular, the method doc strings should make +3. **Python 3**. Check the `pyproject.toml` for the supported Python versions. +4. **Documentation** is required for all modules, classes and methods. In particular, the method doc strings should make clear the arguments expected and the return values. For complex algorithms (e.g., an Ewald summation), a summary of the algorithm should be provided and preferably with a link to a publication outlining the method in detail. diff --git a/src/pymatgen/util/testing.py b/src/pymatgen/util/testing.py index 4e9bb8bbccf..266490fbaf0 100644 --- a/src/pymatgen/util/testing.py +++ b/src/pymatgen/util/testing.py @@ -1,8 +1,7 @@ """This module implements testing utilities for materials science codes. -While the primary use is within pymatgen, the functionality is meant to -be useful for external materials science codes as well. For instance, obtaining -example crystal structures to perform tests, specialized assert methods for +While the primary use is within pymatgen, the functionality is meant to be useful for external materials science +codes as well. For instance, obtaining example crystal structures to perform tests, specialized assert methods for materials science, etc. """ @@ -16,6 +15,7 @@ from unittest import TestCase import pytest +from monty.dev import deprecated from monty.json import MontyDecoder, MontyEncoder, MSONable from monty.serialization import loadfn @@ -42,12 +42,14 @@ FAKE_POTCAR_DIR: str = f"{VASP_IN_DIR}/fake_potcars" -class PymatgenTest(TestCase): - """Extends unittest.TestCase with several convenient methods for testing: - - assert_msonable: Test if an object is MSONable and return the serialized object. - - assert_str_content_equal: Test if two string are equal (ignore whitespaces). - - get_structure: Load a Structure with its formula. - - serialize_with_pickle: Test if object(s) can be (de)serialized with `pickle`. +class MatSciTest: + """`pytest` based test framework extended to facilitate testing with + the following methods: + - tmp_path (attribute): Temporary directory. + - get_structure: Load a Structure from `util.structures` with its name. + - assert_str_content_equal: Check if two strings are equal (ignore whitespaces). + - serialize_with_pickle: Test whether object(s) can be (de)serialized with pickle. + - assert_msonable: Test if obj is MSONable and return its serialized string. """ # dict of lazily-loaded test structures (initialized to None) @@ -201,7 +203,15 @@ def serialize_with_pickle( if errors: raise ValueError("\n".join(errors)) - # Return list so that client code can perform additional tests + # Return nested list so that client code can perform additional tests. if got_single_object: return [o[0] for o in objects_by_protocol] return objects_by_protocol + + +@deprecated(MatSciTest, deadline=(2026, 1, 1)) +class PymatgenTest(TestCase, MatSciTest): + """Extends unittest.TestCase with several assert methods for array and str comparison. + + Deprecated: please use `MatSciTest` instead (migrate from `unittest` to `pytest`). + """ diff --git a/tests/alchemy/test_filters.py b/tests/alchemy/test_filters.py index 9d023291ba4..a971db73225 100644 --- a/tests/alchemy/test_filters.py +++ b/tests/alchemy/test_filters.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from monty.json import MontyDecoder @@ -14,10 +13,10 @@ from pymatgen.alchemy.transmuters import StandardTransmuter from pymatgen.analysis.structure_matcher import StructureMatcher from pymatgen.core import Lattice, Species, Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestContainsSpecieFilter(PymatgenTest): +class TestContainsSpecieFilter(MatSciTest): def test_filtering(self): coords = [[0, 0, 0], [0.75, 0.75, 0.75], [0.5, 0.5, 0.5], [0.25, 0.25, 0.25]] lattice = Lattice([[3.0, 0.0, 0.0], [1.0, 3.0, 0], [0, -2.0, 3.0]]) @@ -52,7 +51,7 @@ def test_as_from_dict(self): assert isinstance(ContainsSpecieFilter.from_dict(dct), ContainsSpecieFilter) -class TestSpecieProximityFilter(PymatgenTest): +class TestSpecieProximityFilter(MatSciTest): def test_filter(self): struct = self.get_structure("Li10GeP2S12") sf = SpecieProximityFilter({"Li": 1}) @@ -70,8 +69,8 @@ def test_as_from_dict(self): assert isinstance(SpecieProximityFilter.from_dict(dct), SpecieProximityFilter) -class TestRemoveDuplicatesFilter(TestCase): - def setUp(self): +class TestRemoveDuplicatesFilter: + def setup_method(self): with open(f"{TEST_FILES_DIR}/entries/TiO2_entries.json", encoding="utf-8") as file: entries = json.load(file, cls=MontyDecoder) self._struct_list = [entry.structure for entry in entries] @@ -89,8 +88,8 @@ def test_as_from_dict(self): assert isinstance(RemoveDuplicatesFilter().from_dict(dct), RemoveDuplicatesFilter) -class TestRemoveExistingFilter(TestCase): - def setUp(self): +class TestRemoveExistingFilter: + def setup_method(self): with open(f"{TEST_FILES_DIR}/entries/TiO2_entries.json", encoding="utf-8") as file: entries = json.load(file, cls=MontyDecoder) self._struct_list = [entry.structure for entry in entries] diff --git a/tests/alchemy/test_materials.py b/tests/alchemy/test_materials.py index e1b198f008a..0995a53fa13 100644 --- a/tests/alchemy/test_materials.py +++ b/tests/alchemy/test_materials.py @@ -16,14 +16,14 @@ SupercellTransformation, ) from pymatgen.util.provenance import StructureNL -from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/alchemy" -class TestTransformedStructure(PymatgenTest): - def setUp(self): - structure = PymatgenTest.get_structure("LiFePO4") +class TestTransformedStructure(MatSciTest): + def setup_method(self): + structure = MatSciTest.get_structure("LiFePO4") self.structure = structure trafos = [SubstitutionTransformation({"Li": "Na"})] self.trans = TransformedStructure(structure, trafos) diff --git a/tests/alchemy/test_transmuters.py b/tests/alchemy/test_transmuters.py index 653a98c5326..e5697a459f0 100644 --- a/tests/alchemy/test_transmuters.py +++ b/tests/alchemy/test_transmuters.py @@ -8,10 +8,10 @@ RemoveSpeciesTransformation, SubstitutionTransformation, ) -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, MatSciTest -class TestCifTransmuter(PymatgenTest): +class TestCifTransmuter(MatSciTest): def test_init(self): trafos = [SubstitutionTransformation({"Fe": "Mn", "Fe2+": "Mn2+"})] tsc = CifTransmuter.from_filenames([f"{TEST_FILES_DIR}/cif/MultiStructure.cif"], trafos) @@ -22,7 +22,7 @@ def test_init(self): assert expected == els -class TestPoscarTransmuter(PymatgenTest): +class TestPoscarTransmuter(MatSciTest): def test_init(self): trafos = [SubstitutionTransformation({"Fe": "Mn"})] tsc = PoscarTransmuter.from_filenames([f"{VASP_IN_DIR}/POSCAR", f"{VASP_IN_DIR}/POSCAR"], trafos) diff --git a/tests/analysis/chemenv/connectivity/test_connected_components.py b/tests/analysis/chemenv/connectivity/test_connected_components.py index 1abe37bbeac..64ff24aa5a4 100644 --- a/tests/analysis/chemenv/connectivity/test_connected_components.py +++ b/tests/analysis/chemenv/connectivity/test_connected_components.py @@ -20,12 +20,12 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.sites import PeriodicSite from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" -class TestConnectedComponent(PymatgenTest): +class TestConnectedComponent(MatSciTest): def test_init(self): # Generic connected component not using EnvironmentNodes # (as_dict won't work on such a ConnectedComponent instance) diff --git a/tests/analysis/chemenv/connectivity/test_environment_nodes.py b/tests/analysis/chemenv/connectivity/test_environment_nodes.py index 60af01acff7..e9a8e07bea0 100644 --- a/tests/analysis/chemenv/connectivity/test_environment_nodes.py +++ b/tests/analysis/chemenv/connectivity/test_environment_nodes.py @@ -3,7 +3,7 @@ import json from pymatgen.analysis.chemenv.connectivity.environment_nodes import EnvironmentNode -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest try: import bson @@ -13,7 +13,7 @@ __author__ = "waroquiers" -class TestEnvironmentNodes(PymatgenTest): +class TestEnvironmentNodes(MatSciTest): def test_equal(self): struct = self.get_structure("SiO2") en = EnvironmentNode(central_site=struct[0], i_central_site=0, ce_symbol="T:4") diff --git a/tests/analysis/chemenv/connectivity/test_structure_connectivity.py b/tests/analysis/chemenv/connectivity/test_structure_connectivity.py index bb1ddffdc39..dbebbe8a6e2 100644 --- a/tests/analysis/chemenv/connectivity/test_structure_connectivity.py +++ b/tests/analysis/chemenv/connectivity/test_structure_connectivity.py @@ -9,12 +9,12 @@ LightStructureEnvironments, StructureEnvironments, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" -class TestStructureConnectivity(PymatgenTest): +class TestStructureConnectivity(MatSciTest): def test_serialization(self): BaTiO3_se_fpath = f"{TEST_FILES_DIR}/analysis/chemenv/structure_environments/se_mp-5020.json" with open(BaTiO3_se_fpath, encoding="utf-8") as file: diff --git a/tests/analysis/chemenv/coordination_environments/test_chemenv_strategies.py b/tests/analysis/chemenv/coordination_environments/test_chemenv_strategies.py index 64516b22c41..2c7903385fb 100644 --- a/tests/analysis/chemenv/coordination_environments/test_chemenv_strategies.py +++ b/tests/analysis/chemenv/coordination_environments/test_chemenv_strategies.py @@ -10,12 +10,12 @@ DistanceCutoffFloat, SimplestChemenvStrategy, ) -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "waroquiers" -class TestStrategyOptions(PymatgenTest): +class TestStrategyOptions(MatSciTest): def test_options(self): # DistanceCutoffFloat with pytest.raises(ValueError, match=r"Distance cutoff should be between 1 and \+infinity"): diff --git a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py index 18fc1675835..b64d1406a16 100644 --- a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py +++ b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py @@ -11,7 +11,7 @@ ExplicitPermutationsAlgorithm, SeparationPlane, ) -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "waroquiers" @@ -23,7 +23,7 @@ def __init__(self, coords): self.coords = coords -class TestCoordinationGeometries(PymatgenTest): +class TestCoordinationGeometries(MatSciTest): def test_algorithms(self): expl_algo = ExplicitPermutationsAlgorithm(permutations=[[0, 1, 2], [1, 2, 3]]) expl_algo2 = ExplicitPermutationsAlgorithm.from_dict(expl_algo.as_dict()) diff --git a/tests/analysis/chemenv/coordination_environments/test_coordination_geometry_finder.py b/tests/analysis/chemenv/coordination_environments/test_coordination_geometry_finder.py index 41b0783159e..77496ff99e8 100644 --- a/tests/analysis/chemenv/coordination_environments/test_coordination_geometry_finder.py +++ b/tests/analysis/chemenv/coordination_environments/test_coordination_geometry_finder.py @@ -19,15 +19,15 @@ symmetry_measure, ) from pymatgen.core.structure import Lattice, Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" json_dir = f"{TEST_FILES_DIR}/analysis/chemenv/json" -class TestCoordinationGeometryFinder(PymatgenTest): - def setUp(self): +class TestCoordinationGeometryFinder(MatSciTest): + def setup_method(self): self.lgf = LocalGeometryFinder() self.lgf.setup_parameters( centering_type="standard", diff --git a/tests/analysis/chemenv/coordination_environments/test_read_write.py b/tests/analysis/chemenv/coordination_environments/test_read_write.py index 20dcdcdd31c..e57a2480fdc 100644 --- a/tests/analysis/chemenv/coordination_environments/test_read_write.py +++ b/tests/analysis/chemenv/coordination_environments/test_read_write.py @@ -22,7 +22,7 @@ ) from pymatgen.analysis.chemenv.coordination_environments.voronoi import DetailedVoronoiContainer from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" @@ -30,9 +30,9 @@ struct_env_dir = f"{TEST_FILES_DIR}/analysis/chemenv/structure_environments" -class TestReadWriteChemenv(PymatgenTest): +class TestReadWriteChemenv(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.lgf = LocalGeometryFinder() cls.lgf.setup_parameters(centering_type="standard") diff --git a/tests/analysis/chemenv/coordination_environments/test_structure_environments.py b/tests/analysis/chemenv/coordination_environments/test_structure_environments.py index 1aa09656c6f..64ba8cca9f7 100644 --- a/tests/analysis/chemenv/coordination_environments/test_structure_environments.py +++ b/tests/analysis/chemenv/coordination_environments/test_structure_environments.py @@ -17,14 +17,14 @@ StructureEnvironments, ) from pymatgen.core import Species, Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" TEST_DIR = f"{TEST_FILES_DIR}/analysis/chemenv/structure_environments" -class TestStructureEnvironments(PymatgenTest): +class TestStructureEnvironments(MatSciTest): def test_structure_environments(self): with open(f"{TEST_DIR}/se_mp-7000.json", encoding="utf-8") as file: dct = json.load(file) diff --git a/tests/analysis/chemenv/coordination_environments/test_voronoi.py b/tests/analysis/chemenv/coordination_environments/test_voronoi.py index 492cc00df36..ad65dacf081 100644 --- a/tests/analysis/chemenv/coordination_environments/test_voronoi.py +++ b/tests/analysis/chemenv/coordination_environments/test_voronoi.py @@ -5,14 +5,14 @@ from pymatgen.analysis.chemenv.coordination_environments.voronoi import DetailedVoronoiContainer from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" img_files_dir = f"{TEST_FILES_DIR}/analysis/chemenv/images" -class TestVoronoiContainer(PymatgenTest): +class TestVoronoiContainer(MatSciTest): def test_voronoi(self): # Define a cubic lattice and a list of species (to be used for the fake structures) cubic_lattice = Lattice.cubic(10) diff --git a/tests/analysis/chemenv/coordination_environments/test_weights.py b/tests/analysis/chemenv/coordination_environments/test_weights.py index a645c90fce8..d5a2e2bcccd 100644 --- a/tests/analysis/chemenv/coordination_environments/test_weights.py +++ b/tests/analysis/chemenv/coordination_environments/test_weights.py @@ -16,7 +16,7 @@ SelfCSMNbSetWeight, ) from pymatgen.analysis.chemenv.coordination_environments.structure_environments import StructureEnvironments -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" @@ -39,7 +39,7 @@ class DummyVoronoiContainer: pass -class StrategyWeights(PymatgenTest): +class StrategyWeights(MatSciTest): def test_angle_weight(self): fake_nb_set = FakeNbSet() dummy_se = DummyStructureEnvironments() diff --git a/tests/analysis/chemenv/utils/test_chemenv_config.py b/tests/analysis/chemenv/utils/test_chemenv_config.py index bea8a66770f..3fa00994682 100644 --- a/tests/analysis/chemenv/utils/test_chemenv_config.py +++ b/tests/analysis/chemenv/utils/test_chemenv_config.py @@ -2,14 +2,14 @@ from pymatgen.analysis.chemenv.utils.chemenv_config import ChemEnvConfig from pymatgen.core import SETTINGS -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "waroquiers" config_file_dir = f"{TEST_FILES_DIR}/analysis/chemenv/config" -class TestChemenvConfig(PymatgenTest): +class TestChemenvConfig(MatSciTest): def test_chemenv_config(self): config = ChemEnvConfig() diff --git a/tests/analysis/chemenv/utils/test_coordination_geometry_utils.py b/tests/analysis/chemenv/utils/test_coordination_geometry_utils.py index d7cbc5b7f19..03db878145c 100644 --- a/tests/analysis/chemenv/utils/test_coordination_geometry_utils.py +++ b/tests/analysis/chemenv/utils/test_coordination_geometry_utils.py @@ -7,13 +7,13 @@ from pytest import approx from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "David Waroquiers" -class TestPlanesUtils(PymatgenTest): - def setUp(self): +class TestPlanesUtils(MatSciTest): + def setup_method(self): # Test of plane 4x + 2y - 4z + 3 = 0 (used in most test cases) self.expected_coefficients = np.array([4, 2, -4, 3], float) self.p1 = np.array([0, 0, 0.75]) diff --git a/tests/analysis/chemenv/utils/test_graph_utils.py b/tests/analysis/chemenv/utils/test_graph_utils.py index b5f32fe7e94..e086b862d8c 100644 --- a/tests/analysis/chemenv/utils/test_graph_utils.py +++ b/tests/analysis/chemenv/utils/test_graph_utils.py @@ -5,7 +5,7 @@ from pymatgen.analysis.chemenv.connectivity.environment_nodes import EnvironmentNode from pymatgen.analysis.chemenv.utils.graph_utils import MultiGraphCycle, SimpleGraphCycle, get_delta -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "waroquiers" @@ -68,7 +68,7 @@ def __lt__(self, other): return self.isite % 2 < other.isite % 2 -class TestGraphUtils(PymatgenTest): +class TestGraphUtils(MatSciTest): def test_get_delta(self): n1 = FakeNode(3) n2 = FakeNode(7) @@ -664,7 +664,7 @@ def test_multigraph_cycle(self): assert mgc.edge_indices == edges_ref, f"Edges not equal for inodes = ({str_nodes})" -class TestEnvironmentNodesGraphUtils(PymatgenTest): +class TestEnvironmentNodesGraphUtils(MatSciTest): def test_cycle(self): e1 = EnvironmentNode(central_site="Si", i_central_site=0, ce_symbol="T:4") e2 = EnvironmentNode(central_site="Si", i_central_site=3, ce_symbol="T:4") diff --git a/tests/analysis/chemenv/utils/test_math_utils.py b/tests/analysis/chemenv/utils/test_math_utils.py index d3583a24851..889a836e8e0 100644 --- a/tests/analysis/chemenv/utils/test_math_utils.py +++ b/tests/analysis/chemenv/utils/test_math_utils.py @@ -16,12 +16,12 @@ smootherstep, smoothstep, ) -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "waroquiers" -class TestMathUtils(PymatgenTest): +class TestMathUtils(MatSciTest): def test_list_cartesian_product(self): list_of_lists = [[0, 1], [2, 5, 4], [5]] assert _cartesian_product(lists=list_of_lists) == [ diff --git a/tests/analysis/diffraction/test_neutron.py b/tests/analysis/diffraction/test_neutron.py index 4de897d85d6..16a137c8301 100644 --- a/tests/analysis/diffraction/test_neutron.py +++ b/tests/analysis/diffraction/test_neutron.py @@ -6,7 +6,7 @@ from pymatgen.analysis.diffraction.neutron import NDCalculator from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest """ These calculated values were verified with VESTA and FullProf. @@ -20,7 +20,7 @@ __date__ = "4/19/18" -class TestNDCalculator(PymatgenTest): +class TestNDCalculator(MatSciTest): def test_get_pattern(self): struct = self.get_structure("CsCl") c = NDCalculator(wavelength=1.54184) # CuKa radiation diff --git a/tests/analysis/diffraction/test_tem.py b/tests/analysis/diffraction/test_tem.py index c8cfee3b1d5..bf28f0b4bb1 100644 --- a/tests/analysis/diffraction/test_tem.py +++ b/tests/analysis/diffraction/test_tem.py @@ -11,7 +11,7 @@ from pymatgen.analysis.diffraction.tem import TEMCalculator from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "Frank Wan, Jason Liang" __copyright__ = "Copyright 2019, The Materials Project" @@ -21,7 +21,7 @@ __date__ = "2/20/20" -class TestTEMCalculator(PymatgenTest): +class TestTEMCalculator(MatSciTest): def test_wavelength_rel(self): # Test that the relativistic wavelength formula (for 200 kV electron beam) is correct tem_calc = TEMCalculator() diff --git a/tests/analysis/diffraction/test_xrd.py b/tests/analysis/diffraction/test_xrd.py index 997c43de42b..b3b5f180f7d 100644 --- a/tests/analysis/diffraction/test_xrd.py +++ b/tests/analysis/diffraction/test_xrd.py @@ -6,7 +6,7 @@ from pymatgen.analysis.diffraction.xrd import XRDCalculator from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" @@ -16,7 +16,7 @@ __date__ = "5/22/14" -class TestXRDCalculator(PymatgenTest): +class TestXRDCalculator(MatSciTest): def test_type_wavelength(self): """Test TypeError is raised if wavelength is unaccepted type.""" wavelength = [1.78, 2.78] # just a list diff --git a/tests/analysis/elasticity/test_elastic.py b/tests/analysis/elasticity/test_elastic.py index 32ac9eedea7..335453fd7c6 100644 --- a/tests/analysis/elasticity/test_elastic.py +++ b/tests/analysis/elasticity/test_elastic.py @@ -27,13 +27,13 @@ from pymatgen.core.structure import Structure from pymatgen.core.tensors import Tensor from pymatgen.core.units import FloatWithUnit -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/elasticity" -class TestElasticTensor(PymatgenTest): - def setUp(self): +class TestElasticTensor(MatSciTest): + def setup_method(self): self.voigt_1 = [ [59.33, 28.08, 28.08, 0, 0, 0], [28.08, 59.31, 28.07, 0, 0, 0], @@ -263,8 +263,8 @@ def test_energy_density(self): ) -class TestElasticTensorExpansion(PymatgenTest): - def setUp(self): +class TestElasticTensorExpansion(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/test_toec_data.json", encoding="utf-8") as file: self.data_dict = json.load(file) self.strains = [Strain(sm) for sm in self.data_dict["strains"]] @@ -364,8 +364,8 @@ def test_get_yield_stress(self): self.exp_cu_4.get_yield_stress([1, 0, 0]) -class TestNthOrderElasticTensor(PymatgenTest): - def setUp(self): +class TestNthOrderElasticTensor(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/test_toec_data.json", encoding="utf-8") as file: self.data_dict = json.load(file) self.strains = [Strain(sm) for sm in self.data_dict["strains"]] @@ -401,10 +401,10 @@ def test_energy_density(self): self.c3.energy_density(self.strains[0]) -class TestDiffFit(PymatgenTest): +class TestDiffFit(MatSciTest): """Test various functions related to diff fitting.""" - def setUp(self): + def setup_method(self): with open(f"{TEST_DIR}/test_toec_data.json", encoding="utf-8") as file: self.data_dict = json.load(file) self.strains = [Strain(sm) for sm in self.data_dict["strains"]] diff --git a/tests/analysis/elasticity/test_strain.py b/tests/analysis/elasticity/test_strain.py index 9679fb367cd..0ff2d2ed590 100644 --- a/tests/analysis/elasticity/test_strain.py +++ b/tests/analysis/elasticity/test_strain.py @@ -7,11 +7,11 @@ from pymatgen.analysis.elasticity.strain import Deformation, DeformedStructureSet, Strain, convert_strain_to_deformation from pymatgen.core.structure import Structure from pymatgen.core.tensors import Tensor -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestDeformation(PymatgenTest): - def setUp(self): +class TestDeformation(MatSciTest): + def setup_method(self): self.norm_defo = Deformation.from_index_amount((0, 0), 0.02) self.ind_defo = Deformation.from_index_amount((0, 1), 0.02) self.non_ind_defo = Deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) @@ -81,8 +81,8 @@ def test_apply_to_structure(self): assert_allclose(new_coord, defo_coord) -class TestStrain(PymatgenTest): - def setUp(self): +class TestStrain(MatSciTest): + def setup_method(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) @@ -142,8 +142,8 @@ def test_convert_strain_to_deformation(self): assert_allclose(defo.green_lagrange_strain, strain) -class TestDeformedStructureSet(PymatgenTest): - def setUp(self): +class TestDeformedStructureSet(MatSciTest): + def setup_method(self): self.structure = self.get_structure("Sn") self.default_dss = DeformedStructureSet(self.structure) diff --git a/tests/analysis/elasticity/test_stress.py b/tests/analysis/elasticity/test_stress.py index 9d1dc98ad33..100604b9700 100644 --- a/tests/analysis/elasticity/test_stress.py +++ b/tests/analysis/elasticity/test_stress.py @@ -7,11 +7,11 @@ from pymatgen.analysis.elasticity.strain import Deformation from pymatgen.analysis.elasticity.stress import Stress -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestStress(PymatgenTest): - def setUp(self): +class TestStress(MatSciTest): + def setup_method(self): self.rand_stress = Stress(np.random.default_rng().standard_normal((3, 3))) self.symm_stress = Stress([[0.51, 2.29, 2.42], [2.29, 5.14, 5.07], [2.42, 5.07, 5.33]]) self.non_symm = Stress([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.2, 0.5, 0.5]]) diff --git a/tests/analysis/ferroelectricity/test_polarization.py b/tests/analysis/ferroelectricity/test_polarization.py index 57236ff98c4..7a68b1a805e 100644 --- a/tests/analysis/ferroelectricity/test_polarization.py +++ b/tests/analysis/ferroelectricity/test_polarization.py @@ -13,7 +13,7 @@ from pymatgen.core.structure import Structure from pymatgen.io.vasp.inputs import Potcar from pymatgen.io.vasp.outputs import Outcar -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/vasp/fixtures/BTO_221_99_polarization" bto_folders = ["nonpolar_polarization"] @@ -38,8 +38,8 @@ ) -class TestUtils(PymatgenTest): - def setUp(self): +class TestUtils(MatSciTest): + def setup_method(self): self.potcar = Potcar.from_file(f"{TEST_DIR}/POTCAR") self.zval_dict = {"Ba": 10, "Ti": 10, "O": 6} self.ions = ions @@ -54,8 +54,8 @@ def test_get_total_ionic_dipole(self): assert_allclose(p_ion, self.ions[-1].ravel().tolist()) -class TestPolarization(PymatgenTest): - def setUp(self): +class TestPolarization(MatSciTest): + def setup_method(self): self.p_ions = ions self.p_ions_outcar = np.array( [ @@ -258,8 +258,8 @@ def test_smoothness(self): assert_allclose(self.smoothness_all_in_polar, smoothness) -class TestEnergyTrend(PymatgenTest): - def setUp(self): +class TestEnergyTrend(MatSciTest): + def setup_method(self): self.energies = [ -7.97738049, -7.988621176, diff --git a/tests/analysis/interfaces/test_coherent_interface.py b/tests/analysis/interfaces/test_coherent_interface.py index e2a19a73915..9f578f30c32 100644 --- a/tests/analysis/interfaces/test_coherent_interface.py +++ b/tests/analysis/interfaces/test_coherent_interface.py @@ -1,7 +1,5 @@ from __future__ import annotations -import unittest - from numpy.testing import assert_allclose from pymatgen.analysis.interfaces.coherent_interfaces import ( @@ -14,12 +12,12 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestInterfaceBuilder(PymatgenTest): +class TestInterfaceBuilder(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): si_struct = cls.get_structure("Si") sio2_struct = cls.get_structure("SiO2") cls.si_conventional = SpacegroupAnalyzer(si_struct).get_conventional_standard_structure() @@ -51,8 +49,8 @@ def test_coherent_interface_builder(self): assert len(list(builder.get_interfaces(termination=("O2_Pmmm_1", "Si_R-3m_1")))) >= 6 -class TestCoherentInterfaceBuilder(unittest.TestCase): - def setUp(self): +class TestCoherentInterfaceBuilder: + def setup_method(self): # build substrate & film structure basis = [[0, 0, 0], [0.25, 0.25, 0.25]] self.substrate = Structure(Lattice.cubic(a=5.431), ["Si", "Si"], basis) diff --git a/tests/analysis/interfaces/test_substrate_analyzer.py b/tests/analysis/interfaces/test_substrate_analyzer.py index 06f6ddba240..29002cbfff8 100644 --- a/tests/analysis/interfaces/test_substrate_analyzer.py +++ b/tests/analysis/interfaces/test_substrate_analyzer.py @@ -5,10 +5,10 @@ from pymatgen.analysis.elasticity.elastic import ElasticTensor from pymatgen.analysis.interfaces.substrate_analyzer import SubstrateAnalyzer from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -VO2 = PymatgenTest.get_structure("VO2") -TiO2 = PymatgenTest.get_structure("TiO2") +VO2 = MatSciTest.get_structure("VO2") +TiO2 = MatSciTest.get_structure("TiO2") # Film VO2 film = SpacegroupAnalyzer(VO2, symprec=0.1).get_conventional_standard_structure() diff --git a/tests/analysis/interfaces/test_zsl.py b/tests/analysis/interfaces/test_zsl.py index 25ab77950e1..f38892b8753 100644 --- a/tests/analysis/interfaces/test_zsl.py +++ b/tests/analysis/interfaces/test_zsl.py @@ -13,7 +13,7 @@ vec_area, ) from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "Shyam Dwaraknath" __copyright__ = "Copyright 2016, The Materials Project" @@ -23,8 +23,8 @@ __date__ = "2/5/16" -class TestZSLGen(PymatgenTest): - def setUp(self): +class TestZSLGen(MatSciTest): + def setup_method(self): # Film VO2 self.film = SpacegroupAnalyzer(self.get_structure("VO2"), symprec=0.1).get_conventional_standard_structure() diff --git a/tests/analysis/magnetism/test_analyzer.py b/tests/analysis/magnetism/test_analyzer.py index 3286409d05f..dfbac279ef4 100644 --- a/tests/analysis/magnetism/test_analyzer.py +++ b/tests/analysis/magnetism/test_analyzer.py @@ -1,7 +1,6 @@ from __future__ import annotations from shutil import which -from unittest import TestCase import pytest from monty.serialization import loadfn @@ -24,8 +23,8 @@ enumlib_present = enum_cmd and makestr_cmd -class TestCollinearMagneticStructureAnalyzer(TestCase): - def setUp(self): +class TestCollinearMagneticStructureAnalyzer: + def setup_method(self): self.Fe = Structure.from_file(f"{TEST_FILES_DIR}/cif/Fe.cif", primitive=True) self.LiFePO4 = Structure.from_file(f"{TEST_FILES_DIR}/cif/LiFePO4.cif", primitive=True) diff --git a/tests/analysis/magnetism/test_heisenberg.py b/tests/analysis/magnetism/test_heisenberg.py index 248bb559227..d6ce648ea87 100644 --- a/tests/analysis/magnetism/test_heisenberg.py +++ b/tests/analysis/magnetism/test_heisenberg.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pandas as pd from pymatgen.analysis.magnetism.heisenberg import HeisenbergMapper @@ -11,9 +9,9 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/magnetic_orderings" -class TestHeisenbergMapper(TestCase): +class TestHeisenbergMapper: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.df = pd.read_json(f"{TEST_DIR}/mag_orderings_test_cases.json") # Good tests diff --git a/tests/analysis/magnetism/test_jahnteller.py b/tests/analysis/magnetism/test_jahnteller.py index ac3555cce47..11f81b9686b 100644 --- a/tests/analysis/magnetism/test_jahnteller.py +++ b/tests/analysis/magnetism/test_jahnteller.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np from pytest import approx @@ -10,8 +8,8 @@ from pymatgen.util.testing import TEST_FILES_DIR -class TestJahnTeller(TestCase): - def setUp(self): +class TestJahnTeller: + def setup_method(self): self.jt = JahnTellerAnalyzer() def test_jahn_teller_species_analysis(self): diff --git a/tests/analysis/solar/test_slme.py b/tests/analysis/solar/test_slme.py index 3ccf3256d11..3bcfd828495 100644 --- a/tests/analysis/solar/test_slme.py +++ b/tests/analysis/solar/test_slme.py @@ -3,12 +3,12 @@ from pytest import approx from pymatgen.analysis.solar.slme import optics, slme -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/solar" -class TestSolar(PymatgenTest): +class TestSolar(MatSciTest): def test_slme_from_vasprun(self): en, abz, dir_gap, indir_gap = optics(f"{TEST_DIR}/vasprun.xml") abz *= 100.0 diff --git a/tests/analysis/structure_prediction/test_dopant_predictor.py b/tests/analysis/structure_prediction/test_dopant_predictor.py index f19d032624d..7f4d8aaf6c5 100644 --- a/tests/analysis/structure_prediction/test_dopant_predictor.py +++ b/tests/analysis/structure_prediction/test_dopant_predictor.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - from pytest import approx from pymatgen.analysis.local_env import CrystalNN @@ -12,8 +10,8 @@ from pymatgen.core import Species, Structure -class TestDopantPrediction(TestCase): - def setUp(self): +class TestDopantPrediction: + def setup_method(self): self.tin_dioxide = Structure( [3.24, 0, 0, 0, 4.83, 0, 0, 0, 4.84], ["O", "O", "O", "O", "Sn", "Sn"], diff --git a/tests/analysis/structure_prediction/test_substitution_probability.py b/tests/analysis/structure_prediction/test_substitution_probability.py index bd0fce0c386..e8695fac167 100644 --- a/tests/analysis/structure_prediction/test_substitution_probability.py +++ b/tests/analysis/structure_prediction/test_substitution_probability.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from pytest import approx @@ -26,7 +25,7 @@ def get_table(): return json.load(file) -class TestSubstitutionProbability(TestCase): +class TestSubstitutionProbability: def test_full_lambda_table(self): """Check specific values in the data folder. If the JSON is updated, these tests will have to be as well. @@ -57,7 +56,7 @@ def test_mini_lambda_table(self): assert prob == approx(0.00102673915742, abs=1e-5), "probability isn't correct" -class TestSubstitutionPredictor(TestCase): +class TestSubstitutionPredictor: def test_prediction(self): sp = SubstitutionPredictor(threshold=8e-3) result = sp.list_prediction(["Na+", "Cl-"], to_this_composition=True)[5] diff --git a/tests/analysis/structure_prediction/test_substitutor.py b/tests/analysis/structure_prediction/test_substitutor.py index 62690d436bd..b46256b7081 100644 --- a/tests/analysis/structure_prediction/test_substitutor.py +++ b/tests/analysis/structure_prediction/test_substitutor.py @@ -4,7 +4,7 @@ from pymatgen.analysis.structure_prediction.substitutor import Substitutor from pymatgen.core import Composition, Species -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/struct_predictor" @@ -20,8 +20,8 @@ def get_table(): return json.load(file) -class TestSubstitutor(PymatgenTest): - def setUp(self): +class TestSubstitutor(MatSciTest): + def setup_method(self): self.substitutor = Substitutor(threshold=1e-3, lambda_table=get_table(), alpha=-5.0) def test_substitutor(self): @@ -32,7 +32,7 @@ def test_substitutor(self): subs = self.substitutor.pred_from_comp(comp) assert len(subs) == 4, "incorrect number of substitutions" - structures = [{"structure": PymatgenTest.get_structure("Li2O"), "id": "pmgtest"}] + structures = [{"structure": MatSciTest.get_structure("Li2O"), "id": "pmgtest"}] subs = self.substitutor.pred_from_structures(["Na+", "O2-"], structures) assert subs[0].formula == "Na2 O1" diff --git a/tests/analysis/structure_prediction/test_volume_predictor.py b/tests/analysis/structure_prediction/test_volume_predictor.py index 20ecf2bd24b..da96904a990 100644 --- a/tests/analysis/structure_prediction/test_volume_predictor.py +++ b/tests/analysis/structure_prediction/test_volume_predictor.py @@ -5,38 +5,38 @@ from pymatgen.analysis.structure_prediction.volume_predictor import DLSVolumePredictor, RLSVolumePredictor from pymatgen.core import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/structure_prediction" -class TestRLSVolumePredictor(PymatgenTest): +class TestRLSVolumePredictor(MatSciTest): def test_predict(self): - struct = PymatgenTest.get_structure("CsCl") - nacl = PymatgenTest.get_structure("CsCl") + struct = MatSciTest.get_structure("CsCl") + nacl = MatSciTest.get_structure("CsCl") nacl.replace_species({"Cs": "Na"}) nacl.scale_lattice(184.384551033) predictor = RLSVolumePredictor(radii_type="ionic") assert predictor.predict(struct, nacl) == approx(342.84905395082535) predictor = RLSVolumePredictor(radii_type="atomic") assert predictor.predict(struct, nacl) == approx(391.884366481) - lif = PymatgenTest.get_structure("CsCl") + lif = MatSciTest.get_structure("CsCl") lif.replace_species({"Cs": "Li", "Cl": "F"}) predictor = RLSVolumePredictor(radii_type="ionic") assert predictor.predict(lif, nacl) == approx(74.268402413690467) predictor = RLSVolumePredictor(radii_type="atomic") assert predictor.predict(lif, nacl) == approx(62.2808125839) - lfpo = PymatgenTest.get_structure("LiFePO4") - lmpo = PymatgenTest.get_structure("LiFePO4") + lfpo = MatSciTest.get_structure("LiFePO4") + lmpo = MatSciTest.get_structure("LiFePO4") lmpo.replace_species({"Fe": "Mn"}) predictor = RLSVolumePredictor(radii_type="ionic") assert predictor.predict(lmpo, lfpo) == approx(310.08253254420134) predictor = RLSVolumePredictor(radii_type="atomic") assert predictor.predict(lmpo, lfpo) == approx(299.607967711) - sto = PymatgenTest.get_structure("SrTiO3") - scoo = PymatgenTest.get_structure("SrTiO3") + sto = MatSciTest.get_structure("SrTiO3") + scoo = MatSciTest.get_structure("SrTiO3") scoo.replace_species({"Ti4+": "Co4+"}) predictor = RLSVolumePredictor(radii_type="ionic") assert predictor.predict(scoo, sto) == approx(56.162534974936463) @@ -61,8 +61,8 @@ def test_predict(self): assert predictor.predict(apo, aps) == approx(1196.31384276) def test_modes(self): - cs_cl = PymatgenTest.get_structure("CsCl") - na_cl = PymatgenTest.get_structure("CsCl") + cs_cl = MatSciTest.get_structure("CsCl") + na_cl = MatSciTest.get_structure("CsCl") na_cl.replace_species({"Cs": "Na"}) na_cl.scale_lattice(184.384551033) vol_pred = RLSVolumePredictor(radii_type="ionic", use_bv=False) @@ -77,7 +77,7 @@ def test_modes(self): assert vol_pred.predict(cs_cl, na_cl) == approx(342.84905395082535) -class TestDLSVolumePredictor(PymatgenTest): +class TestDLSVolumePredictor(MatSciTest): def test_predict(self): vol_pred = DLSVolumePredictor() p_fast = DLSVolumePredictor(cutoff=0.0) # for speed on compressed cells @@ -94,7 +94,7 @@ def test_predict(self): assert vol_pred.predict(fen) == approx(fen.volume * 1.5) assert p_fast.predict(fen) == approx(fen.volume * 1.5) - lfpo = PymatgenTest.get_structure("LiFePO4") + lfpo = MatSciTest.get_structure("LiFePO4") lfpo.scale_lattice(lfpo.volume * 3.0) assert p_nolimit.predict(lfpo) == approx(291.62094410192924) @@ -104,6 +104,6 @@ def test_predict(self): assert vol_pred.predict(lfpo) == approx(lfpo.volume * 1.5) assert p_fast.predict(lfpo) == approx(lfpo.volume * 1.5) - lmpo = PymatgenTest.get_structure("LiFePO4") + lmpo = MatSciTest.get_structure("LiFePO4") lmpo.replace_species({"Fe": "Mn"}) assert vol_pred.predict(lmpo) == approx(290.795329052) diff --git a/tests/analysis/test_adsorption.py b/tests/analysis/test_adsorption.py index ced3948a366..e3b9d0070fe 100644 --- a/tests/analysis/test_adsorption.py +++ b/tests/analysis/test_adsorption.py @@ -8,11 +8,11 @@ from pymatgen.core.structure import Molecule, Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.util.coord import in_coord_list -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestAdsorbateSiteFinder(PymatgenTest): - def setUp(self): +class TestAdsorbateSiteFinder(MatSciTest): + def setup_method(self): self.structure = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.5), ["Ni"], [[0, 0, 0]]) lattice = Lattice.cubic(3.010) frac_coords = [ diff --git a/tests/analysis/test_bond_dissociation.py b/tests/analysis/test_bond_dissociation.py index 01cb71aaea6..9ac3a059a8a 100644 --- a/tests/analysis/test_bond_dissociation.py +++ b/tests/analysis/test_bond_dissociation.py @@ -1,7 +1,6 @@ from __future__ import annotations import platform -from unittest import TestCase import pytest from monty.serialization import loadfn @@ -12,8 +11,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/bond_dissociation" -class TestBondDissociation(TestCase): - def setUp(self): +class TestBondDissociation: + def setup_method(self): pytest.importorskip("openbabel") self.PC_65_principle = loadfn(f"{TEST_DIR}/PC_65_principle.json") self.PC_65_principle["initial_molecule"] = self.PC_65_principle["initial_molecule"].as_dict() diff --git a/tests/analysis/test_bond_valence.py b/tests/analysis/test_bond_valence.py index a2e0db2ce0c..dbc68adf22d 100644 --- a/tests/analysis/test_bond_valence.py +++ b/tests/analysis/test_bond_valence.py @@ -5,13 +5,13 @@ from pymatgen.analysis.bond_valence import BVAnalyzer, calculate_bv_sum, calculate_bv_sum_unordered from pymatgen.core import Composition, Species, Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/bond_valence" -class TestBVAnalyzer(PymatgenTest): - def setUp(self): +class TestBVAnalyzer(MatSciTest): + def setup_method(self): self.analyzer = BVAnalyzer() def test_get_valences(self): @@ -44,7 +44,7 @@ def test_get_oxi_state_structure(self): assert Species("Mn4+") in oxi_struct.composition.elements -class TestBondValenceSum(PymatgenTest): +class TestBondValenceSum(MatSciTest): def test_calculate_bv_sum(self): struct = Structure.from_file(f"{TEST_DIR}/LiMn2O4.json") neighbors = struct.get_neighbors(struct[0], 3.0) diff --git a/tests/analysis/test_chempot_diagram.py b/tests/analysis/test_chempot_diagram.py index 43dfd957b0d..24efd0e5317 100644 --- a/tests/analysis/test_chempot_diagram.py +++ b/tests/analysis/test_chempot_diagram.py @@ -12,13 +12,13 @@ ) from pymatgen.core.composition import Element from pymatgen.entries.entry_tools import EntrySet -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis" -class TestChemicalPotentialDiagram(PymatgenTest): - def setUp(self): +class TestChemicalPotentialDiagram(MatSciTest): + def setup_method(self): self.entries = EntrySet.from_csv(f"{TEST_DIR}/pd_entries_test.csv") self.cpd_ternary, self.cpd_ternary_formal = ( ChemicalPotentialDiagram(entries=self.entries, default_min_limit=-25, formal_chempots=formal) diff --git a/tests/analysis/test_cost.py b/tests/analysis/test_cost.py index c20bed2fd54..074a98cd9c7 100644 --- a/tests/analysis/test_cost.py +++ b/tests/analysis/test_cost.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - from pytest import approx from pymatgen.analysis.cost import CostAnalyzer, CostDBCSV, CostDBElements @@ -10,8 +8,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/cost" -class TestCostAnalyzer(TestCase): - def setUp(self): +class TestCostAnalyzer: + def setup_method(self): self.ca1 = CostAnalyzer(CostDBCSV(f"{TEST_DIR}/costdb_1.csv")) self.ca2 = CostAnalyzer(CostDBCSV(f"{TEST_DIR}/costdb_2.csv")) @@ -31,7 +29,7 @@ def test_sanity(self): assert self.ca1.get_cost_per_kg("Ag") == self.ca2.get_cost_per_kg("Ag") -class TestCostDB(TestCase): +class TestCostDB: def test_sanity(self): ca = CostAnalyzer(CostDBElements()) assert ca.get_cost_per_kg("PtO") > ca.get_cost_per_kg("MgO") diff --git a/tests/analysis/test_dimensionality.py b/tests/analysis/test_dimensionality.py index 8b99c6fd5e2..ced0094926b 100644 --- a/tests/analysis/test_dimensionality.py +++ b/tests/analysis/test_dimensionality.py @@ -15,11 +15,11 @@ from pymatgen.analysis.graphs import StructureGraph from pymatgen.analysis.local_env import CrystalNN from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestLarsenDimensionality(PymatgenTest): - def setUp(self): +class TestLarsenDimensionality(MatSciTest): + def setup_method(self): cnn = CrystalNN() self.lifepo = cnn.get_bonded_structure(self.get_structure("LiFePO4")) self.graphite = cnn.get_bonded_structure(self.get_structure("Graphite")) @@ -114,7 +114,7 @@ def test_zero_d_to_molecule_graph(self): assert len(mol_graph.molecule) == 12 -class TestCheonDimensionality(PymatgenTest): +class TestCheonDimensionality(MatSciTest): def test_get_dimensionality(self): struct = self.get_structure("LiFePO4") assert get_dimensionality_cheon(struct) == "intercalated ion" @@ -152,7 +152,7 @@ def test_tricky_structure(self): assert get_dimensionality_cheon(tricky_structure, larger_cell=True) == "3D" -class TestGoraiDimensionality(PymatgenTest): +class TestGoraiDimensionality(MatSciTest): def test_get_dimensionality(self): struct = self.get_structure("LiFePO4") assert get_dimensionality_gorai(struct) == 3 diff --git a/tests/analysis/test_disorder.py b/tests/analysis/test_disorder.py index f1fbd2f58d5..c6d449eccf5 100644 --- a/tests/analysis/test_disorder.py +++ b/tests/analysis/test_disorder.py @@ -4,10 +4,10 @@ from pymatgen.analysis.disorder import get_warren_cowley_parameters from pymatgen.core import Element, Structure -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestOrderParameter(PymatgenTest): +class TestOrderParameter(MatSciTest): def test_compute_warren_cowley_parameters(self): struct = Structure.from_prototype("CsCl", ["Mo", "W"], a=4) aij = get_warren_cowley_parameters(struct, r=3.4, dr=0.3) diff --git a/tests/analysis/test_eos.py b/tests/analysis/test_eos.py index 9a839f8279b..874c476ce3b 100644 --- a/tests/analysis/test_eos.py +++ b/tests/analysis/test_eos.py @@ -5,11 +5,11 @@ from pytest import approx from pymatgen.analysis.eos import EOS, NumericalEOS -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestEOS(PymatgenTest): - def setUp(self): +class TestEOS(MatSciTest): + def setup_method(self): # Si data from Cormac self.volumes = [ 25.987454833, diff --git a/tests/analysis/test_ewald.py b/tests/analysis/test_ewald.py index 285152bb8fd..6e5ea7e5a0b 100644 --- a/tests/analysis/test_ewald.py +++ b/tests/analysis/test_ewald.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest from pytest import approx @@ -11,8 +9,8 @@ from pymatgen.util.testing import VASP_IN_DIR -class TestEwaldSummation(TestCase): - def setUp(self): +class TestEwaldSummation: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.original_struct = Structure.from_file(filepath) self.struct = self.original_struct.copy() @@ -80,7 +78,7 @@ def test_as_dict(self): assert ham.as_dict() == EwaldSummation.from_dict(dct).as_dict() -class TestEwaldMinimizer(TestCase): +class TestEwaldMinimizer: def test_init(self): matrix = np.array( [ diff --git a/tests/analysis/test_fragmenter.py b/tests/analysis/test_fragmenter.py index 211d7e3b7d1..05af88a8edf 100644 --- a/tests/analysis/test_fragmenter.py +++ b/tests/analysis/test_fragmenter.py @@ -8,7 +8,7 @@ from pymatgen.analysis.graphs import MoleculeGraph from pymatgen.analysis.local_env import OpenBabelNN from pymatgen.core.structure import Molecule -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Samuel Blau" __email__ = "samblau1@gmail.com" @@ -17,9 +17,9 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/local_env/fragmenter_files" -class TestFragmentMolecule(PymatgenTest): +class TestFragmentMolecule(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.pc = Molecule.from_file(f"{TEST_DIR}/PC.xyz") cls.ec = Molecule.from_file(f"{TEST_DIR}/EC.xyz") cls.pos_pc = Molecule.from_file(f"{TEST_DIR}/PC.xyz") diff --git a/tests/analysis/test_functional_groups.py b/tests/analysis/test_functional_groups.py index a5fcb316e38..5b04e8290c2 100644 --- a/tests/analysis/test_functional_groups.py +++ b/tests/analysis/test_functional_groups.py @@ -1,7 +1,6 @@ from __future__ import annotations import platform -from unittest import TestCase import pytest @@ -25,8 +24,8 @@ __credit__ = "Peiyuan Yu" -class TestFunctionalGroupExtractor(TestCase): - def setUp(self): +class TestFunctionalGroupExtractor: + def setup_method(self): self.file = f"{TEST_DIR}/func_group_test.mol" self.mol = Molecule.from_file(self.file) self.strategy = OpenBabelNN() diff --git a/tests/analysis/test_graphs.py b/tests/analysis/test_graphs.py index fa7a8739ba4..779236067ce 100644 --- a/tests/analysis/test_graphs.py +++ b/tests/analysis/test_graphs.py @@ -5,7 +5,6 @@ import warnings from glob import glob from shutil import which -from unittest import TestCase import networkx as nx import networkx.algorithms.isomorphism as iso @@ -25,7 +24,7 @@ from pymatgen.command_line.critic2_caller import Critic2Analysis from pymatgen.core import Lattice, Molecule, Site, Structure from pymatgen.core.structure import FunctionalGroups -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from openbabel import openbabel @@ -47,8 +46,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/graphs" -class TestStructureGraph(PymatgenTest): - def setUp(self): +class TestStructureGraph(MatSciTest): + def setup_method(self): # trivial example, simple square lattice for testing structure = Structure(Lattice.tetragonal(5, 50), ["H"], [[0, 0, 0]]) self.square_sg = StructureGraph.from_empty_graph(structure, edge_weight_name="", edge_weight_units="") @@ -508,8 +507,8 @@ def test_sort(self): assert list(sg.graph.edges)[-2:] == [(1, 3, 0), (1, 2, 0)] -class TestMoleculeGraph(TestCase): - def setUp(self): +class TestMoleculeGraph: + def setup_method(self): cyclohexene_xyz = f"{TEST_DIR}/cyclohexene.xyz" cyclohexene = Molecule.from_file(cyclohexene_xyz) self.cyclohexene = MoleculeGraph.from_empty_graph( diff --git a/tests/analysis/test_interface_reactions.py b/tests/analysis/test_interface_reactions.py index f768d58bee3..a9dc2bb3ec9 100644 --- a/tests/analysis/test_interface_reactions.py +++ b/tests/analysis/test_interface_reactions.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest from matplotlib.figure import Figure as MplFigure @@ -17,8 +15,8 @@ from pymatgen.entries.computed_entries import ComputedEntry -class TestInterfaceReaction(TestCase): - def setUp(self): +class TestInterfaceReaction: + def setup_method(self): self.entries = [ ComputedEntry(Composition("Li"), 0), ComputedEntry(Composition("Mn"), 0), diff --git a/tests/analysis/test_local_env.py b/tests/analysis/test_local_env.py index ac2ab8b099d..f9478dfa605 100644 --- a/tests/analysis/test_local_env.py +++ b/tests/analysis/test_local_env.py @@ -40,7 +40,7 @@ solid_angle, ) from pymatgen.core import Element, Lattice, Molecule, Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/local_env/fragmenter_files" @@ -54,8 +54,8 @@ def test_opt_params(): assert cn_opt_params == CN_OPT_PARAMS -class TestValenceIonicRadiusEvaluator(PymatgenTest): - def setUp(self): +class TestValenceIonicRadiusEvaluator(MatSciTest): + def setup_method(self): """Setup MgO rocksalt structure for testing Vacancy.""" mgo_latt = np.eye(3) * 4.212 mgo_specie = ["Mg"] * 4 + ["O"] * 4 @@ -89,8 +89,8 @@ def test_radii_ionic_structure(self): assert rad in {0.86, 1.26} -class TestVoronoiNN(PymatgenTest): - def setUp(self): +class TestVoronoiNN(MatSciTest): + def setup_method(self): self.struct = self.get_structure("LiFePO4") self.nn = VoronoiNN(targets=[Element("O")]) self.s_sic = self.get_structure("Si") @@ -260,8 +260,8 @@ def test_filtered(self): assert [len(x) for x in all_nns] == [8] * 16 -class TestJmolNN(PymatgenTest): - def setUp(self): +class TestJmolNN(MatSciTest): + def setup_method(self): self.jmol = JmolNN() self.jmol_update = JmolNN(el_radius_updates={"Li": 1}) @@ -290,7 +290,7 @@ def test_get_nn(self): assert len(self.jmol_update.get_nn(struct, 0)) == 2 -class TestIsayevNN(PymatgenTest): +class TestIsayevNN(MatSciTest): def test_get_nn(self): inn = IsayevNN() struct = self.get_structure("LiFePO4") @@ -301,8 +301,8 @@ def test_get_nn(self): assert len(inn.get_nn(struct, 0)) == 2 -class TestOpenBabelNN(PymatgenTest): - def setUp(self): +class TestOpenBabelNN(MatSciTest): + def setup_method(self): pytest.importorskip("openbabel") self.benzene = Molecule.from_file(f"{TEST_DIR}/../benzene.xyz") self.acetylene = Molecule.from_file(f"{TEST_FILES_DIR}/io/xyz/acetylene.xyz") @@ -333,8 +333,8 @@ def test_nn_length(self): assert strategy.get_nn_info(self.acetylene, 0)[0]["weight"] == approx(1.19, abs=1e-2) -class TestCovalentBondNN(PymatgenTest): - def setUp(self): +class TestCovalentBondNN(MatSciTest): + def setup_method(self): self.benzene = Molecule.from_file(f"{TEST_DIR}/../benzene.xyz") self.acetylene = Molecule.from_file(f"{TEST_FILES_DIR}/io/xyz/acetylene.xyz") @@ -372,8 +372,8 @@ def test_bonded_structure(self): assert len(acetylene.graph.nodes) == 4 -class TestMiniDistNN(PymatgenTest): - def setUp(self): +class TestMiniDistNN(MatSciTest): + def setup_method(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C0+", "C0+"], @@ -485,8 +485,8 @@ def test_get_local_order_params(self): assert ops["octahedral"] == approx(0.9999995266669) -class TestMotifIdentification(PymatgenTest): - def setUp(self): +class TestMotifIdentification(MatSciTest): + def setup_method(self): self.silicon = Structure( Lattice.cubic(5.47), ["Si", "Si", "Si", "Si", "Si", "Si", "Si", "Si"], @@ -583,8 +583,8 @@ def test_get_neighbors_of_site_with_index(self): assert len(get_neighbors_of_site_with_index(self.diamond, 0, approach="min_VIRE")) == 4 -class TestNearNeighbor(PymatgenTest): - def setUp(self): +class TestNearNeighbor(MatSciTest): + def setup_method(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C0+", "C0+"], @@ -617,8 +617,8 @@ def test_on_disorder_options(self): ) -class TestLocalStructOrderParams(PymatgenTest): - def setUp(self): +class TestLocalStructOrderParams(MatSciTest): + def setup_method(self): self.single_bond = Structure( Lattice.cubic(10), ["H", "H", "H"], @@ -1182,8 +1182,8 @@ def test_get_order_parameters(self): ops_101.get_order_parameters(self.bcc, 0, indices_neighs=[2]) -class TestCrystalNN(PymatgenTest): - def setUp(self): +class TestCrystalNN(MatSciTest): + def setup_method(self): self.lifepo4 = self.get_structure("LiFePO4") self.lifepo4.add_oxidation_state_by_guess() self.he_bcc = self.get_structure("He_BCC") @@ -1329,8 +1329,8 @@ def test_get_bonded_structure(self): cnn.get_bonded_structure(self.disordered_struct, 0, on_disorder="error") -class TestCutOffDictNN(PymatgenTest): - def setUp(self): +class TestCutOffDictNN(MatSciTest): + def setup_method(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C", "C"], @@ -1355,8 +1355,8 @@ def test_from_preset(self): @pytest.mark.skipif(not which("critic2"), reason="critic2 executable not present") -class TestCritic2NN(PymatgenTest): - def setUp(self): +class TestCritic2NN(MatSciTest): + def setup_method(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C", "C"], @@ -1369,8 +1369,8 @@ def test_cn(self): # assert nn.get_cn(self.diamond, 0) == 4 -class TestMetalEdgeExtender(PymatgenTest): - def setUp(self): +class TestMetalEdgeExtender(MatSciTest): + def setup_method(self): self.LiEC = Molecule.from_file(f"{TEST_DIR}/LiEC.xyz") self.phsh = Molecule.from_file(f"{TEST_DIR}/phsh.xyz") self.phsh_graph = MoleculeGraph.from_edges( diff --git a/tests/analysis/test_molecule_matcher.py b/tests/analysis/test_molecule_matcher.py index 3a7f433e1be..b811b4240de 100644 --- a/tests/analysis/test_molecule_matcher.py +++ b/tests/analysis/test_molecule_matcher.py @@ -1,7 +1,6 @@ from __future__ import annotations import platform -from unittest import TestCase import numpy as np import pytest @@ -556,9 +555,9 @@ def test_fit(self): assert rmsd == approx(0, abs=6) -class TestKabschMatcherSi(TestCase): +class TestKabschMatcherSi: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si_cluster.xyz") cls.mol_matcher = KabschMatcher(cls.mol1) @@ -593,9 +592,9 @@ def test_permuted_atoms_order(self): assert rmsd == approx(2.7962454578966454, abs=1e-6) -class TestBruteForceOrderMatcherSi(TestCase): +class TestBruteForceOrderMatcherSi: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si_cluster.xyz") cls.mol_matcher = BruteForceOrderMatcher(cls.mol1) @@ -614,9 +613,9 @@ def test_random_match(self): self.mol_matcher.fit(mol2) -class TestHungarianOrderMatcherSi(TestCase): +class TestHungarianOrderMatcherSi: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si_cluster.xyz") cls.mol_matcher = HungarianOrderMatcher(cls.mol1) @@ -653,9 +652,9 @@ def test_random_match(self): assert rmsd == approx(1.0177241485450828, abs=1e-6) -class TestGeneticOrderMatcherSi(TestCase): +class TestGeneticOrderMatcherSi: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si_cluster.xyz") cls.mol_matcher = GeneticOrderMatcher(cls.mol1, threshold=0.3) @@ -690,9 +689,9 @@ def test_random_match(self): assert res[0][-1] == approx(0.22163169511782, abs=1e-6) -class TestKabschMatcherSi2O(TestCase): +class TestKabschMatcherSi2O: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si2O_cluster.xyz") cls.mol_matcher = KabschMatcher(cls.mol1) @@ -725,9 +724,9 @@ def test_permuted_atoms_order(self): self.mol_matcher.fit(mol2) -class TestBruteForceOrderMatcherSi2O(TestCase): +class TestBruteForceOrderMatcherSi2O: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si2O_cluster.xyz") cls.mol_matcher = BruteForceOrderMatcher(cls.mol1) @@ -757,9 +756,9 @@ def test_random_match(self): assert rmsd == approx(0.23051587697194997, abs=1e-6) -class TestHungarianOrderMatcherSi2O(TestCase): +class TestHungarianOrderMatcherSi2O: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si2O_cluster.xyz") cls.mol_matcher = HungarianOrderMatcher(cls.mol1) @@ -789,9 +788,9 @@ def test_random_match(self): assert rmsd == approx(0.23231038877573124, abs=1e-6) -class TestGeneticOrderMatcherSi2O(TestCase): +class TestGeneticOrderMatcherSi2O: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.mol1 = Molecule.from_file(f"{TEST_DIR}/Si2O_cluster.xyz") cls.mol_matcher = GeneticOrderMatcher(cls.mol1, threshold=0.3) diff --git a/tests/analysis/test_molecule_structure_comparator.py b/tests/analysis/test_molecule_structure_comparator.py index 3875ffb44ec..b212b593e17 100644 --- a/tests/analysis/test_molecule_structure_comparator.py +++ b/tests/analysis/test_molecule_structure_comparator.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pytest from pymatgen.analysis.molecule_structure_comparator import MoleculeStructureComparator @@ -15,7 +13,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/structural_change" -class TestMoleculeStructureComparator(TestCase): +class TestMoleculeStructureComparator: def test_are_equal(self): msc1 = MoleculeStructureComparator() mol1 = Molecule.from_file(f"{TEST_DIR}/t1.xyz") diff --git a/tests/analysis/test_nmr.py b/tests/analysis/test_nmr.py index 14490ec7a0c..b0ca34759b3 100644 --- a/tests/analysis/test_nmr.py +++ b/tests/analysis/test_nmr.py @@ -5,10 +5,10 @@ from pytest import approx from pymatgen.analysis.nmr import ChemicalShielding, ElectricFieldGradient -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestChemicalShieldingNotation(PymatgenTest): +class TestChemicalShieldingNotation(MatSciTest): def test_construction(self): cs = ChemicalShielding(np.arange(9).reshape((3, 3))) assert cs.shape == (3, 3) @@ -46,7 +46,7 @@ def test_notations(self): assert mary1.kappa == approx(0.8337, abs=1e-5) -class TestElectricFieldGradient(PymatgenTest): +class TestElectricFieldGradient(MatSciTest): def test_construction(self): efg = ElectricFieldGradient(np.arange(9).reshape((3, 3))) assert efg.shape == (3, 3) diff --git a/tests/analysis/test_phase_diagram.py b/tests/analysis/test_phase_diagram.py index ef1bc12e840..7ac972d54ba 100644 --- a/tests/analysis/test_phase_diagram.py +++ b/tests/analysis/test_phase_diagram.py @@ -1,11 +1,9 @@ from __future__ import annotations import collections -import unittest -import unittest.mock from itertools import combinations from numbers import Number -from unittest import TestCase +from unittest.mock import patch import matplotlib.pyplot as plt import numpy as np @@ -32,13 +30,13 @@ from pymatgen.core import Composition, DummySpecies, Element from pymatgen.entries.computed_entries import ComputedEntry from pymatgen.entries.entry_tools import EntrySet -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis" -class TestPDEntry(TestCase): - def setUp(self): +class TestPDEntry: + def setup_method(self): comp = Composition("LiFeO2") self.entry = PDEntry(comp, 53, name="mp-757614") self.gp_entry = GrandPotPDEntry(self.entry, {Element("O"): 1.5}) @@ -113,8 +111,8 @@ def test_read_csv(self): assert len(entries) == 490, "Wrong number of entries!" -class TestTransformedPDEntry(TestCase): - def setUp(self): +class TestTransformedPDEntry: + def setup_method(self): comp = Composition("LiFeO2") entry = PDEntry(comp, 53) @@ -179,8 +177,8 @@ def test_normalize(self): assert norm_entry.composition == expected_comp -class TestPhaseDiagram(PymatgenTest): - def setUp(self): +class TestPhaseDiagram(MatSciTest): + def setup_method(self): self.entries = EntrySet.from_csv(f"{TEST_DIR}/pd_entries_test.csv") self.pd = PhaseDiagram(self.entries) @@ -667,8 +665,8 @@ def test_val_err_on_no_entries(self): PhaseDiagram(entries=entries) -class TestGrandPotentialPhaseDiagram(TestCase): - def setUp(self): +class TestGrandPotentialPhaseDiagram: + def setup_method(self): self.entries = EntrySet.from_csv(f"{TEST_DIR}/pd_entries_test.csv") self.pd = GrandPotentialPhaseDiagram(self.entries, {Element("O"): -5}) self.pd6 = GrandPotentialPhaseDiagram(self.entries, {Element("O"): -6}) @@ -703,8 +701,8 @@ def test_str(self): ) -class TestCompoundPhaseDiagram(TestCase): - def setUp(self): +class TestCompoundPhaseDiagram: + def setup_method(self): self.entries = EntrySet.from_csv(f"{TEST_DIR}/pd_entries_test.csv") self.pd = CompoundPhaseDiagram(self.entries, [Composition("Li2O"), Composition("Fe2O3")]) @@ -741,8 +739,8 @@ def test_num2str(self): assert len(ret) == num -class TestPatchedPhaseDiagram(TestCase): - def setUp(self): +class TestPatchedPhaseDiagram: + def setup_method(self): self.entries = EntrySet.from_csv(f"{TEST_DIR}/phase_diagram/reaction_entries_test.csv") # NOTE add He to test for correct behavior despite no patches involving He self.no_patch_entry = he_entry = PDEntry("He", -1.23) @@ -891,8 +889,8 @@ def test_remove_redundant_spaces(self): assert len(self.ppd.remove_redundant_spaces(test)) == 30 -class TestReactionDiagram(TestCase): - def setUp(self): +class TestReactionDiagram: + def setup_method(self): self.entries = list(EntrySet.from_csv(f"{TEST_DIR}/phase_diagram/reaction_entries_test.csv").entries) for entry in self.entries: if entry.reduced_formula == "VPO5": @@ -931,8 +929,8 @@ def test_formula(self): # assert formula in formed_formula, f"{formed_formula=} not in {expected_formula=}" -class TestPDPlotter(TestCase): - def setUp(self): +class TestPDPlotter: + def setup_method(self): entries = list(EntrySet.from_csv(f"{TEST_DIR}/pd_entries_test.csv")) elemental_entries = [entry for entry in entries if entry.elements == [Element("Li")]] @@ -1009,7 +1007,7 @@ def test_plotly_plots(self): # test show() # suppress default plotly behavior of opening figure in browser by patching plotly.io.show to noop - with unittest.mock.patch("plotly.io.show") as mock_show: + with patch("plotly.io.show") as mock_show: assert self.plotter_ternary_plotly_2d.show() is None mock_show.assert_called_once() diff --git a/tests/analysis/test_piezo.py b/tests/analysis/test_piezo.py index bf3eb7534c2..06f89320b12 100644 --- a/tests/analysis/test_piezo.py +++ b/tests/analysis/test_piezo.py @@ -7,7 +7,7 @@ from numpy.testing import assert_allclose, assert_array_equal from pymatgen.analysis.piezo import PiezoTensor -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "Shyam Dwaraknath" __version__ = "0.1" @@ -17,8 +17,8 @@ __date__ = "4/1/16" -class TestPiezo(PymatgenTest): - def setUp(self): +class TestPiezo(MatSciTest): + def setup_method(self): self.piezo_struct = self.get_structure("BaNiO3") self.voigt_matrix = np.array( [ diff --git a/tests/analysis/test_piezo_sensitivity.py b/tests/analysis/test_piezo_sensitivity.py index 757215a30e4..7e2d3045487 100644 --- a/tests/analysis/test_piezo_sensitivity.py +++ b/tests/analysis/test_piezo_sensitivity.py @@ -17,7 +17,7 @@ rand_piezo, ) from pymatgen.io.phonopy import get_phonopy_structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from phonopy import Phonopy @@ -34,8 +34,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/piezo_sensitivity" -class TestPiezoSensitivity(PymatgenTest): - def setUp(self): +class TestPiezoSensitivity(MatSciTest): + def setup_method(self): self.piezo_struct = self.get_structure("Pb2TiZrO6") self.IST = np.load(f"{TEST_DIR}/pztist.npy", allow_pickle=True) self.BEC = np.load(f"{TEST_DIR}/pztborn.npy", allow_pickle=True) diff --git a/tests/analysis/test_pourbaix_diagram.py b/tests/analysis/test_pourbaix_diagram.py index f5cf13681a3..d43751a3325 100644 --- a/tests/analysis/test_pourbaix_diagram.py +++ b/tests/analysis/test_pourbaix_diagram.py @@ -1,7 +1,6 @@ from __future__ import annotations import multiprocessing -from unittest import TestCase import matplotlib.pyplot as plt import numpy as np @@ -19,15 +18,15 @@ from pymatgen.core.composition import Composition from pymatgen.core.ion import Ion from pymatgen.entries.computed_entries import ComputedEntry -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/pourbaix_diagram" -class TestPourbaixEntry(PymatgenTest): +class TestPourbaixEntry(MatSciTest): """Test all functions using a fictitious entry""" - def setUp(self): + def setup_method(self): # comp = Composition("Mn2O3") self.sol_entry = ComputedEntry("Mn2O3", 49) ion = Ion.from_formula("MnO4-") @@ -104,9 +103,9 @@ def test_get_elt_fraction(self): assert pb_entry.get_element_fraction("Mn") == approx(0.4) -class TestPourbaixDiagram(TestCase): +class TestPourbaixDiagram: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.test_data = loadfn(f"{TEST_DIR}/pourbaix_test_data.json") cls.pbx = PourbaixDiagram(cls.test_data["Zn"], filter_solids=True) cls.pbx_no_filter = PourbaixDiagram(cls.test_data["Zn"], filter_solids=False) @@ -300,8 +299,8 @@ def test_serialization(self): assert len(pd_binary.stable_entries) == len(new_binary.stable_entries) -class TestPourbaixPlotter(TestCase): - def setUp(self): +class TestPourbaixPlotter: + def setup_method(self): self.test_data = loadfn(f"{TEST_DIR}/pourbaix_test_data.json") self.pd = PourbaixDiagram(self.test_data["Zn"]) self.plotter = PourbaixPlotter(self.pd) diff --git a/tests/analysis/test_prototypes.py b/tests/analysis/test_prototypes.py index d2a16258d03..887b5d598d4 100644 --- a/tests/analysis/test_prototypes.py +++ b/tests/analysis/test_prototypes.py @@ -1,10 +1,10 @@ from __future__ import annotations from pymatgen.analysis.prototypes import AflowPrototypeMatcher -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestAflowPrototypeMatcher(PymatgenTest): +class TestAflowPrototypeMatcher(MatSciTest): def test_prototype_matching(self): af = AflowPrototypeMatcher() diff --git a/tests/analysis/test_quasi_harmonic_debye_approx.py b/tests/analysis/test_quasi_harmonic_debye_approx.py index 6c0c5816d2d..c9481f73513 100644 --- a/tests/analysis/test_quasi_harmonic_debye_approx.py +++ b/tests/analysis/test_quasi_harmonic_debye_approx.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np from numpy.testing import assert_allclose @@ -12,8 +10,8 @@ __author__ = "Kiran Mathew" -class TestQuasiHarmonicDebyeApprox(TestCase): - def setUp(self): +class TestQuasiHarmonicDebyeApprox: + def setup_method(self): struct = Structure.from_dict( { "lattice": { @@ -137,8 +135,8 @@ def test_vibrational_free_energy(self): assert_allclose(A, 0.494687, atol=1e-3) -class TestAnharmonicQuasiHarmonicDebyeApprox(TestCase): - def setUp(self): +class TestAnharmonicQuasiHarmonicDebyeApprox: + def setup_method(self): struct = Structure.from_str( """FCC Al 1.0 diff --git a/tests/analysis/test_quasirrho.py b/tests/analysis/test_quasirrho.py index 1db102b0516..ce33ac6e302 100644 --- a/tests/analysis/test_quasirrho.py +++ b/tests/analysis/test_quasirrho.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pytest from pymatgen.analysis.quasirrho import QuasiRRHO, get_avg_mom_inertia @@ -12,10 +10,10 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/quasirrho" -class TestQuasiRRHO(TestCase): +class TestQuasiRRHO: """Test class for QuasiRRHO""" - def setUp(self): + def setup_method(self): self.gout = GaussianOutput(f"{TEST_DIR}/quasirrho_gaufreq.log") self.linear_gout = GaussianOutput(f"{TEST_DIR}/co2.log.gz") self.qout = QCOutput(f"{TEST_DIR}/Frequency_no_equal.qout") diff --git a/tests/analysis/test_reaction_calculator.py b/tests/analysis/test_reaction_calculator.py index 82fc1e03bea..cb6363a0114 100644 --- a/tests/analysis/test_reaction_calculator.py +++ b/tests/analysis/test_reaction_calculator.py @@ -2,7 +2,6 @@ import math from collections import defaultdict -from unittest import TestCase import numpy as np import pytest @@ -287,8 +286,8 @@ def test_underdetermined_reactants(self): assert str(rxn) == "LiMnCl3 + 3 LiCl + MnCl2 -> 2 Li2MnCl4" -class TestBalancedReaction(TestCase): - def setUp(self) -> None: +class TestBalancedReaction: + def setup_method(self) -> None: rct = {"K2SO4": 3, "Na2S": 1, "Li": 24} prod = {"KNaS": 2, "K2S": 2, "Li2O": 12} self.rxn = BalancedReaction(rct, prod) @@ -334,8 +333,8 @@ def test_hash(self): assert hash(self.rxn) == 4774511606373046513 -class TestComputedReaction(TestCase): - def setUp(self): +class TestComputedReaction: + def setup_method(self): dct = [ { "correction": 0, diff --git a/tests/analysis/test_structure_analyzer.py b/tests/analysis/test_structure_analyzer.py index 5c99c0a263d..8112b23699f 100644 --- a/tests/analysis/test_structure_analyzer.py +++ b/tests/analysis/test_structure_analyzer.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np from numpy.testing import assert_allclose from pytest import approx @@ -18,11 +16,11 @@ ) from pymatgen.core import Element, Lattice, Structure from pymatgen.io.vasp.outputs import Xdatcar -from pymatgen.util.testing import VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import VASP_IN_DIR, VASP_OUT_DIR, MatSciTest -class TestVoronoiAnalyzer(PymatgenTest): - def setUp(self): +class TestVoronoiAnalyzer(MatSciTest): + def setup_method(self): self.structs = Xdatcar(f"{VASP_OUT_DIR}/XDATCAR.MD").structures self.struct = self.structs[1] self.va = VoronoiAnalyzer(cutoff=4) @@ -40,8 +38,8 @@ def test_analyze(self): ) in ensemble, "Cannot find the right polyhedron in ensemble." -class TestRelaxationAnalyzer(TestCase): - def setUp(self): +class TestRelaxationAnalyzer: + def setup_method(self): s1 = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_Li2O") s2 = Structure.from_file(f"{VASP_OUT_DIR}/CONTCAR_Li2O") self.analyzer = RelaxationAnalyzer(s1, s2) @@ -62,7 +60,7 @@ def test_get_percentage_bond_dist_changes(self): assert approx(v2) == -0.009204092115527862 -class TestVoronoiConnectivity(PymatgenTest): +class TestVoronoiConnectivity(MatSciTest): def test_connectivity_array(self): vc = VoronoiConnectivity(self.get_structure("LiFePO4")) ca = vc.connectivity_array @@ -78,7 +76,7 @@ def test_connectivity_array(self): assert_allclose(site.frac_coords, expected) -class TestMiscFunction(PymatgenTest): +class TestMiscFunction(MatSciTest): def test_average_coordination_number(self): xdatcar = Xdatcar(f"{VASP_OUT_DIR}/XDATCAR.MD") coordination_numbers = average_coordination_number(xdatcar.structures, freq=1) diff --git a/tests/analysis/test_structure_matcher.py b/tests/analysis/test_structure_matcher.py index 8850edede70..345518d5d0d 100644 --- a/tests/analysis/test_structure_matcher.py +++ b/tests/analysis/test_structure_matcher.py @@ -17,13 +17,13 @@ ) from pymatgen.core import Element, Lattice, Structure, SymmOp from pymatgen.util.coord import find_in_coord_list_pbc -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/structure_matcher" -class TestStructureMatcher(PymatgenTest): - def setUp(self): +class TestStructureMatcher(MatSciTest): + def setup_method(self): with open(f"{TEST_FILES_DIR}/entries/TiO2_entries.json", encoding="utf-8") as file: entries = json.load(file, cls=MontyDecoder) self.struct_list = [ent.structure for ent in entries] diff --git a/tests/analysis/test_surface_analysis.py b/tests/analysis/test_surface_analysis.py index 42a102b74ca..d987a91b504 100644 --- a/tests/analysis/test_surface_analysis.py +++ b/tests/analysis/test_surface_analysis.py @@ -9,7 +9,7 @@ from pymatgen.analysis.surface_analysis import NanoscaleStability, SlabEntry, SurfaceEnergyPlotter, WorkFunctionAnalyzer from pymatgen.entries.computed_entries import ComputedStructureEntry -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Richard Tran" __copyright__ = "Copyright 2012, The Materials Project" @@ -22,8 +22,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/surfaces" -class TestSlabEntry(PymatgenTest): - def setUp(self): +class TestSlabEntry(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/ucell_entries.txt", encoding="utf-8") as file: ucell_entries = json.loads(file.read()) self.ucell_entries = ucell_entries @@ -118,8 +118,8 @@ def test_cleaned_up_slab(self): assert slab_clean.composition.reduced_composition == clean.composition.reduced_composition -class TestSurfaceEnergyPlotter(PymatgenTest): - def setUp(self): +class TestSurfaceEnergyPlotter(MatSciTest): + def setup_method(self): entry_dict = get_entry_dict(f"{TEST_DIR}/Cu_entries.txt") self.Cu_entry_dict = entry_dict with open(f"{TEST_DIR}/ucell_entries.txt", encoding="utf-8") as file: @@ -292,8 +292,8 @@ def test_surface_chempot_range_map(self): analyzer.chempot_vs_gamma_facet(hkl) -class TestWorkFunctionAnalyzer(PymatgenTest): - def setUp(self): +class TestWorkFunctionAnalyzer(MatSciTest): + def setup_method(self): self.kwargs = { "poscar_filename": f"{TEST_DIR}/CONTCAR.relax1.gz", "locpot_filename": f"{TEST_DIR}/LOCPOT.gz", @@ -309,8 +309,8 @@ def test_is_converged(self): assert self.wf_analyzer.is_converged() -class TestNanoscaleStability(PymatgenTest): - def setUp(self): +class TestNanoscaleStability(MatSciTest): + def setup_method(self): # Load all entries La_hcp_entry_dict = get_entry_dict(f"{TEST_DIR}/La_hcp_entries.txt") La_fcc_entry_dict = get_entry_dict(f"{TEST_DIR}/La_fcc_entries.txt") diff --git a/tests/analysis/test_transition_state.py b/tests/analysis/test_transition_state.py index 9e03e7a988c..4ae68e4bba4 100644 --- a/tests/analysis/test_transition_state.py +++ b/tests/analysis/test_transition_state.py @@ -6,7 +6,7 @@ from numpy.testing import assert_allclose from pymatgen.analysis.transition_state import NEBAnalysis, combine_neb_plots -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest """ TODO: Modify unittest doc. @@ -23,7 +23,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/vasp/fixtures/neb_analysis" -class TestNEBAnalysis(PymatgenTest): +class TestNEBAnalysis(MatSciTest): def test_run(self): neb_analysis1 = NEBAnalysis.from_dir(f"{TEST_DIR}/neb1/neb") neb_analysis1_from_dict = NEBAnalysis.from_dict(neb_analysis1.as_dict()) diff --git a/tests/analysis/test_wulff.py b/tests/analysis/test_wulff.py index 0579d09f72a..48c72ec7d99 100644 --- a/tests/analysis/test_wulff.py +++ b/tests/analysis/test_wulff.py @@ -9,7 +9,7 @@ from pymatgen.core.structure import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.util.coord import in_coord_list -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Zihan Xu, Richard Tran, Balachandran Radhakrishnan" __copyright__ = "Copyright 2013, The Materials Virtual Lab" @@ -21,8 +21,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/analysis/wulff" -class TestWulffShape(PymatgenTest): - def setUp(self): +class TestWulffShape(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/surface_samples.json", encoding="utf-8") as data_file: surface_properties = json.load(data_file) diff --git a/tests/analysis/test_xps.py b/tests/analysis/test_xps.py index 45b250e3100..e21381fcaee 100644 --- a/tests/analysis/test_xps.py +++ b/tests/analysis/test_xps.py @@ -2,10 +2,10 @@ from pymatgen.analysis.xps import XPS from pymatgen.io.vasp import Vasprun -from pymatgen.util.testing import VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import VASP_OUT_DIR, MatSciTest -class TestXPS(PymatgenTest): +class TestXPS(MatSciTest): def test_from_dos(self): vasp_run = Vasprun(f"{VASP_OUT_DIR}/vasprun.LiF.xml.gz") dos = vasp_run.complete_dos diff --git a/tests/analysis/topological/test_spillage.py b/tests/analysis/topological/test_spillage.py index 39224cdfc52..ae1953d2b93 100644 --- a/tests/analysis/topological/test_spillage.py +++ b/tests/analysis/topological/test_spillage.py @@ -3,12 +3,12 @@ from pytest import approx from pymatgen.analysis.topological.spillage import SOCSpillage -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/topological" -class TestSolar(PymatgenTest): +class TestSolar(MatSciTest): def test_spillage_from_vasprun(self): wf_noso = f"{TEST_DIR}/WAVECAR-NonSOC" wf_so = f"{TEST_DIR}/WAVECAR-SOC" diff --git a/tests/analysis/xas/test_spectrum.py b/tests/analysis/xas/test_spectrum.py index f6c258a5f30..79265d83e01 100644 --- a/tests/analysis/xas/test_spectrum.py +++ b/tests/analysis/xas/test_spectrum.py @@ -10,7 +10,7 @@ from pymatgen.analysis.xas.spectrum import XAS, site_weighted_spectrum from pymatgen.core import Element -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/spectrum_test" @@ -28,8 +28,8 @@ site2_xanes_dict = json.load(file, cls=MontyDecoder) -class TestXAS(PymatgenTest): - def setUp(self): +class TestXAS(MatSciTest): + def setup_method(self): self.k_xanes = XAS.from_dict(k_xanes_dict) self.k_exafs = XAS.from_dict(k_exafs_dict) self.l2_xanes = XAS.from_dict(l2_xanes_dict) diff --git a/tests/apps/battery/test_analyzer.py b/tests/apps/battery/test_analyzer.py index eea99df2ecb..41e1b6b4f2c 100644 --- a/tests/apps/battery/test_analyzer.py +++ b/tests/apps/battery/test_analyzer.py @@ -5,10 +5,10 @@ from pymatgen.apps.battery.analyzer import BatteryAnalyzer from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestBatteryAnalyzer(PymatgenTest): +class TestBatteryAnalyzer(MatSciTest): def load_from_cif(self, filename, oxidations, working_ion="Li"): struct = Structure.from_file(f"{TEST_FILES_DIR}/cif/{filename}") struct.add_oxidation_state_by_element(oxidations) @@ -19,7 +19,7 @@ def load_from_internal(self, name, oxidations, working_ion="Li"): struct.add_oxidation_state_by_element(oxidations) return BatteryAnalyzer(struct, working_ion) - def setUp(self): + def setup_method(self): self.li_fe_p_o4 = self.load_from_internal("LiFePO4", {"Li": 1, "Fe": 2, "P": 5, "O": -2}) self.na_fe_p_o4 = self.load_from_internal("NaFePO4", {"Na": 1, "Fe": 2, "P": 5, "O": -2}, working_ion="Na") self.la2coo4f = self.load_from_internal("La2CoO4F", {"La": 3, "Co": 3, "O": -2, "F": -1}, working_ion="F") diff --git a/tests/apps/battery/test_conversion_battery.py b/tests/apps/battery/test_conversion_battery.py index c63fe76f08e..3a428be7e0f 100644 --- a/tests/apps/battery/test_conversion_battery.py +++ b/tests/apps/battery/test_conversion_battery.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from monty.json import MontyDecoder from pytest import approx @@ -13,8 +12,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/apps/battery" -class TestConversionElectrode(TestCase): - def setUp(self): +class TestConversionElectrode: + def setup_method(self): self.formulas = ["LiCoO2", "FeF3", "MnO2"] self.conversion_electrodes = {} for formula in self.formulas: diff --git a/tests/apps/battery/test_insertion_battery.py b/tests/apps/battery/test_insertion_battery.py index c1537b1f740..4b4670137c8 100644 --- a/tests/apps/battery/test_insertion_battery.py +++ b/tests/apps/battery/test_insertion_battery.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from monty.json import MontyDecoder, MontyEncoder from pytest import approx @@ -13,8 +12,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/apps/battery" -class TestInsertionElectrode(TestCase): - def setUp(self): +class TestInsertionElectrode: + def setup_method(self): self.entry_Li = ComputedEntry("Li", -1.90753119) self.entry_Ca = ComputedEntry("Ca", -1.99689568) diff --git a/tests/apps/battery/test_plotter.py b/tests/apps/battery/test_plotter.py index a154f2dfa03..69819b18693 100644 --- a/tests/apps/battery/test_plotter.py +++ b/tests/apps/battery/test_plotter.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from monty.json import MontyDecoder @@ -15,8 +14,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/apps/battery" -class TestVoltageProfilePlotter(TestCase): - def setUp(self): +class TestVoltageProfilePlotter: + def setup_method(self): entry_Li = ComputedEntry("Li", -1.90753119) with open(f"{TEST_DIR}/LiTiO2_batt.json", encoding="utf-8") as file: diff --git a/tests/apps/borg/test_hive.py b/tests/apps/borg/test_hive.py index 6005eaf3f2c..84a2782553c 100644 --- a/tests/apps/borg/test_hive.py +++ b/tests/apps/borg/test_hive.py @@ -1,7 +1,6 @@ from __future__ import annotations import os -from unittest import TestCase import pytest from monty.tempfile import ScratchDir @@ -20,8 +19,8 @@ MOL_TEST_DIR = f"{TEST_FILES_DIR}/io/gaussian" -class TestVaspToComputedEntryDrone(TestCase): - def setUp(self): +class TestVaspToComputedEntryDrone: + def setup_method(self): self.drone = VaspToComputedEntryDrone(data=["efermi"]) self.structure_drone = VaspToComputedEntryDrone(inc_structure=True) @@ -53,8 +52,8 @@ def test_as_from_dict(self): assert isinstance(drone, VaspToComputedEntryDrone) -class TestSimpleVaspToComputedEntryDrone(TestCase): - def setUp(self): +class TestSimpleVaspToComputedEntryDrone: + def setup_method(self): self.drone = SimpleVaspToComputedEntryDrone() self.structure_drone = SimpleVaspToComputedEntryDrone(inc_structure=True) @@ -73,8 +72,8 @@ def test_as_from_dict(self): assert isinstance(drone, SimpleVaspToComputedEntryDrone) -class TestGaussianToComputedEntryDrone(TestCase): - def setUp(self): +class TestGaussianToComputedEntryDrone: + def setup_method(self): self.drone = GaussianToComputedEntryDrone(data=["corrections"]) self.structure_drone = GaussianToComputedEntryDrone(inc_structure=True) diff --git a/tests/command_line/test_bader_caller.py b/tests/command_line/test_bader_caller.py index ad39f8c6b61..86f3bd5d3a4 100644 --- a/tests/command_line/test_bader_caller.py +++ b/tests/command_line/test_bader_caller.py @@ -10,14 +10,14 @@ from pytest import approx from pymatgen.command_line.bader_caller import BaderAnalysis, bader_analysis_from_path -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/command_line/bader" @pytest.mark.skipif(not which("bader"), reason="bader executable not present") -class TestBaderAnalysis(PymatgenTest): - def setUp(self): +class TestBaderAnalysis(MatSciTest): + def setup_method(self): warnings.catch_warnings() def test_init(self): diff --git a/tests/command_line/test_critic2_caller.py b/tests/command_line/test_critic2_caller.py index 2f7a955e16a..5d70812ff3b 100644 --- a/tests/command_line/test_critic2_caller.py +++ b/tests/command_line/test_critic2_caller.py @@ -1,7 +1,6 @@ from __future__ import annotations from shutil import which -from unittest import TestCase import pytest from pytest import approx @@ -75,8 +74,8 @@ def test_from_structure(self): assert "ERROR : load int.CHGCAR id chg_int zpsp Mo 6 S 6" in c2c._input_script -class TestCritic2Analysis(TestCase): - def setUp(self): +class TestCritic2Analysis: + def setup_method(self): stdout_file = f"{TEST_DIR}/MoS2_critic2_stdout.txt" stdout_file_new_format = f"{TEST_DIR}/MoS2_critic2_stdout_new_format.txt" with open(stdout_file, encoding="utf-8") as file: diff --git a/tests/command_line/test_enumlib_caller.py b/tests/command_line/test_enumlib_caller.py index 010bb0bd1b8..2e538207603 100644 --- a/tests/command_line/test_enumlib_caller.py +++ b/tests/command_line/test_enumlib_caller.py @@ -1,6 +1,5 @@ from __future__ import annotations -import unittest from shutil import which import numpy as np @@ -12,15 +11,14 @@ from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.transformations.site_transformations import RemoveSitesTransformation from pymatgen.transformations.standard_transformations import SubstitutionTransformation -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -enum_cmd = which("enum.x") or which("multienum.x") -makestr_cmd = which("makestr.x") or which("makeStr.x") or which("makeStr.py") -enumlib_present = enum_cmd and makestr_cmd +ENUM_CMD = which("enum.x") or which("multienum.x") +MAKESTR_CMD = which("makestr.x") or which("makeStr.x") or which("makeStr.py") -@pytest.mark.skipif(not enumlib_present, reason="enum_lib not present.") -class TestEnumlibAdaptor(PymatgenTest): +@pytest.mark.skipif(not (ENUM_CMD and MAKESTR_CMD), reason="enumlib not present.") +class TestEnumlibAdaptor(MatSciTest): def test_init(self): struct = self.get_structure("LiFePO4") sub_trans = SubstitutionTransformation({"Li": {"Li": 0.5}}) @@ -119,7 +117,7 @@ def test_partial_disorder(self): for struct in structures: assert struct.formula == "Ca12 Al8 Si4 Ge8 O48" - @unittest.skip("Fails seemingly at random.") + @pytest.mark.skip("Fails seemingly at random.") def test_timeout(self): struct = Structure.from_file(filename=f"{TEST_FILES_DIR}/cif/garnet.cif") SpacegroupAnalyzer(struct, 0.1) diff --git a/tests/command_line/test_gulp_caller.py b/tests/command_line/test_gulp_caller.py index 2710fd0d4b3..a09e85fb4c4 100644 --- a/tests/command_line/test_gulp_caller.py +++ b/tests/command_line/test_gulp_caller.py @@ -8,9 +8,7 @@ import os import sys -import unittest from shutil import which -from unittest import TestCase import numpy as np import pytest @@ -30,13 +28,15 @@ TEST_DIR = f"{TEST_FILES_DIR}/command_line/gulp" -gulp_present = which("gulp") and os.getenv("GULP_LIB") and ("win" not in sys.platform) -# disable gulp tests for now. Right now, it is compiled against libgfortran3, which is no longer supported in the new -# Ubuntu 20.04. -gulp_present = False +GULP_PRESENT = which("gulp") and os.getenv("GULP_LIB") and ("win" not in sys.platform) +# Disable GULP tests for now: it is compiled against `libgfortran3``, +# which is no longer supported in Ubuntu 20.04 and onwards. +GULP_PRESENT = False + +if not GULP_PRESENT: + pytest.skip(reason="GULP not available", allow_module_level=True) -@pytest.mark.skipif(not gulp_present, reason="gulp not present.") class TestGulpCaller: def test_run(self): mgo_lattice = np.eye(3) * 4.212 @@ -105,9 +105,8 @@ def test_decimal(self): caller.run(buckingham_input) -@pytest.mark.skipif(not gulp_present, reason="gulp not present.") -class TestGulpIO(TestCase): - def setUp(self): +class TestGulpIO: + def setup_method(self): self.structure = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_Al12O18") self.gio = GulpIO() @@ -132,15 +131,6 @@ def test_structure_lines_no_frac_coords(self): assert "cell" not in inp_str assert "cart" in inp_str - @unittest.skip("Not Implemented yet") - def test_specie_potential(self): - pass - - @unittest.expectedFailure - def test_library_line_explicit_path(self): - gin = self.gio.library_line("/Users/mbkumar/Research/Defects/GulpExe/Libraries/catlow.lib") - assert "lib" in gin - def test_library_line_wrong_file(self): with pytest.raises(GulpError, match="GULP library not found"): self.gio.library_line("temp_to_fail.lib") @@ -280,14 +270,13 @@ def test_get_relaxed_structure(self): assert struct.lattice.a == 4.212 assert struct.lattice.alpha == 90 - @unittest.skip("Test later") + @pytest.mark.skip("Test later") def test_tersoff_input(self): self.gio.tersoff_input(self.structure) -@pytest.mark.skipif(not gulp_present, reason="gulp not present.") -class TestGlobalFunctions(TestCase): - def setUp(self): +class TestGlobalFunctions: + def setup_method(self): mgo_latt = np.eye(3) * 4.212 mgo_specie = ["Mg", "O"] * 4 mgo_frac_cord = [ @@ -337,9 +326,8 @@ def test_get_energy_relax_structure_buckingham(self): assert site_len == len(self.mgo_uc) -@pytest.mark.skipif(not gulp_present, reason="gulp not present.") -class TestBuckinghamPotentialLewis(TestCase): - def setUp(self): +class TestBuckinghamPotentialLewis: + def setup_method(self): self.bpl = BuckinghamPotential("lewis") def test_existing_element(self): @@ -365,9 +353,8 @@ def test_spring(self): assert self.bpl.spring_dict["O"] != "" -@pytest.mark.skipif(not gulp_present, reason="gulp not present.") -class TestBuckinghamPotentialBush(TestCase): - def setUp(self): +class TestBuckinghamPotentialBush: + def setup_method(self): self.bpb = BuckinghamPotential("bush") def test_existing_element(self): diff --git a/tests/command_line/test_mcsqs_caller.py b/tests/command_line/test_mcsqs_caller.py index ca9f8a018d6..d7b56ce64ab 100644 --- a/tests/command_line/test_mcsqs_caller.py +++ b/tests/command_line/test_mcsqs_caller.py @@ -7,7 +7,7 @@ from pymatgen.command_line.mcsqs_caller import run_mcsqs from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Handong Ling, Rachel Woods-Robinson" __maintainer__ = "Handong Ling, Rachel Woods-Robinson" @@ -18,8 +18,8 @@ @pytest.mark.skipif(not (which("mcsqs") and which("str2cif")), reason="mcsqs executable not present") -class TestMcsqsCaller(PymatgenTest): - def setUp(self): +class TestMcsqsCaller(MatSciTest): + def setup_method(self): self.pzt_structs = loadfn(f"{TEST_DIR}/pzt-structs.json") self.pzt_structs2 = loadfn(f"{TEST_DIR}/pzt-structs-2.json") self.struct = self.get_structure("Pb2TiZrO6") diff --git a/tests/command_line/test_vampire_caller.py b/tests/command_line/test_vampire_caller.py index e2e55a18486..b2246508682 100644 --- a/tests/command_line/test_vampire_caller.py +++ b/tests/command_line/test_vampire_caller.py @@ -8,15 +8,15 @@ from pymatgen.command_line.vampire_caller import VampireCaller from pymatgen.core.structure import Structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/analysis/magnetic_orderings" @pytest.mark.skipif(not which("vampire-serial"), reason="vampire executable not present") -class TestVampireCaller(PymatgenTest): +class TestVampireCaller(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.Mn3Al = pd.read_json(f"{TEST_DIR}/Mn3Al.json") cls.compounds = [cls.Mn3Al] diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index 6c83b348172..00000000000 --- a/tests/conftest.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Test fixes for pymatgen.""" - -from __future__ import annotations - -from pathlib import Path - -TEST_DIR = Path(__file__).absolute().parent diff --git a/tests/core/test_composition.py b/tests/core/test_composition.py index 59ddd9836e1..dbb9f827ba6 100644 --- a/tests/core/test_composition.py +++ b/tests/core/test_composition.py @@ -13,11 +13,11 @@ from pymatgen.core import Composition, DummySpecies, Element, Species from pymatgen.core.composition import ChemicalPotential -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestComposition(PymatgenTest): - def setUp(self): +class TestComposition(MatSciTest): + def setup_method(self): self.comps = [ Composition("Li3Fe2(PO4)3"), Composition("Li3Fe(PO4)O"), diff --git a/tests/core/test_interface.py b/tests/core/test_interface.py index c2563cd2a7a..41bb16ec56d 100644 --- a/tests/core/test_interface.py +++ b/tests/core/test_interface.py @@ -8,13 +8,13 @@ from pymatgen.core.structure import Structure from pymatgen.core.surface import SlabGenerator from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/core/grain_boundary" -class TestGrainBoundary(PymatgenTest): - def setUp(self): +class TestGrainBoundary(MatSciTest): + def setup_method(self): self.Cu_conv = Structure.from_file(f"{TEST_DIR}/Cu_mp-30_conventional_standard.cif") GB_Cu_conv = GrainBoundaryGenerator(self.Cu_conv) self.Cu_GB1 = GB_Cu_conv.gb_from_parameters( @@ -104,9 +104,9 @@ def test_as_dict_and_from_dict(self): assert_allclose(Cu_GB2_new.lattice.matrix, self.Cu_GB2.lattice.matrix) -class TestGrainBoundaryGenerator(PymatgenTest): +class TestGrainBoundaryGenerator(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.Cu_prim = Structure.from_file(f"{TEST_DIR}/Cu_mp-30_primitive.cif") cls.GB_Cu_prim = GrainBoundaryGenerator(cls.Cu_prim) cls.Cu_conv = Structure.from_file(f"{TEST_DIR}/Cu_mp-30_conventional_standard.cif") @@ -331,8 +331,8 @@ def test_get_rotation_angle_from_sigma(self): assert_allclose(close_angle, angle) -class TestInterface(PymatgenTest): - def setUp(self): +class TestInterface(MatSciTest): + def setup_method(self): self.interface: Interface = self.get_structure("Si_SiO2_Interface") def test_basic_props(self): diff --git a/tests/core/test_ion.py b/tests/core/test_ion.py index 061f00a6de0..4e1779951eb 100644 --- a/tests/core/test_ion.py +++ b/tests/core/test_ion.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest @@ -9,8 +7,8 @@ from pymatgen.core.ion import Ion -class TestIon(TestCase): - def setUp(self): +class TestIon: + def setup_method(self): self.comp = [] self.comp.append(Ion.from_formula("Li+")) self.comp.append(Ion.from_formula("MnO4-")) diff --git a/tests/core/test_lattice.py b/tests/core/test_lattice.py index 89a79e6330c..32a42a62e16 100644 --- a/tests/core/test_lattice.py +++ b/tests/core/test_lattice.py @@ -9,11 +9,11 @@ from pymatgen.core.lattice import Lattice, get_points_in_spheres from pymatgen.core.operations import SymmOp -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestLattice(PymatgenTest): - def setUp(self): +class TestLattice(MatSciTest): + def setup_method(self): self.lattice = Lattice.cubic(10.0) self.cubic = self.lattice self.tetragonal = Lattice.tetragonal(10, 20) diff --git a/tests/core/test_libxcfunc.py b/tests/core/test_libxcfunc.py index 435b71c389e..1436f08e42e 100644 --- a/tests/core/test_libxcfunc.py +++ b/tests/core/test_libxcfunc.py @@ -1,10 +1,10 @@ from __future__ import annotations from pymatgen.core.libxcfunc import LibxcFunc -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestLibxcFunc(PymatgenTest): +class TestLibxcFunc(MatSciTest): def test_libxcfunc_api(self): """Testing libxcfunc_api.""" # LDA correlation: Hedin & Lundqvist diff --git a/tests/core/test_molecular_orbitals.py b/tests/core/test_molecular_orbitals.py index 4476c856d17..c2275268a33 100644 --- a/tests/core/test_molecular_orbitals.py +++ b/tests/core/test_molecular_orbitals.py @@ -3,12 +3,12 @@ import pytest from pymatgen.core.molecular_orbitals import MolecularOrbitals -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest test_case = MolecularOrbitals("NaCl") -class TestMolecularOrbital(PymatgenTest): +class TestMolecularOrbital(MatSciTest): def test_max_electronegativity(self): test_elec_neg = 2.23 assert test_elec_neg == test_case.max_electronegativity() diff --git a/tests/core/test_operations.py b/tests/core/test_operations.py index 1d775b09b92..370b8bc1d2f 100644 --- a/tests/core/test_operations.py +++ b/tests/core/test_operations.py @@ -1,15 +1,16 @@ from __future__ import annotations import numpy as np +import pytest from numpy.testing import assert_allclose from pymatgen.core.operations import MagSymmOp, SymmOp from pymatgen.electronic_structure.core import Magmom -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestSymmOp(PymatgenTest): - def setUp(self): +class TestSymmOp(MatSciTest): + def setup_method(self): self.op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, translation_vec=[0, 0, 1]) def test_properties(self): @@ -228,7 +229,8 @@ def test_xyz(self): assert op4 == op5 assert op3 == op5 - self.assertWarns(UserWarning, self.op.as_xyz_str) + with pytest.warns(UserWarning, match="Rotation matrix should be integer"): + self.op.as_xyz_str() symm_op = SymmOp.from_xyz_str("0.5+x, 0.25+y, 0.75+z") assert_allclose(symm_op.translation_vector, [0.5, 0.25, 0.75]) @@ -236,7 +238,7 @@ def test_xyz(self): assert_allclose(symm_op.translation_vector, [0.5, 0.25, 0.75]) -class TestMagSymmOp(PymatgenTest): +class TestMagSymmOp(MatSciTest): def test_xyzt_string(self): xyzt_strings = ["x, y, z, +1", "x, y, z, -1", "-y+1/2, x+1/2, x+1/2, +1"] diff --git a/tests/core/test_periodic_table.py b/tests/core/test_periodic_table.py index 84b6fcca159..88ad2c0854d 100644 --- a/tests/core/test_periodic_table.py +++ b/tests/core/test_periodic_table.py @@ -14,10 +14,10 @@ from pymatgen.core.periodic_table import ElementBase, ElementType from pymatgen.core.units import Ha_to_eV from pymatgen.io.core import ParseError -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestElement(PymatgenTest): +class TestElement(MatSciTest): def test_init(self): assert Element("Fe").symbol == "Fe" @@ -413,8 +413,8 @@ def test_isotope(self): assert Element.named_isotopes == (Element.D, Element.T) -class TestSpecies(PymatgenTest): - def setUp(self): +class TestSpecies(MatSciTest): + def setup_method(self): self.specie1 = Species.from_str("Fe2+") self.specie2 = Species("Fe", 3) self.specie3 = Species("Fe", 2) diff --git a/tests/core/test_sites.py b/tests/core/test_sites.py index c941eb587f0..8d682c4505a 100644 --- a/tests/core/test_sites.py +++ b/tests/core/test_sites.py @@ -9,11 +9,11 @@ from pymatgen.core import Composition, Element, Lattice, PeriodicSite, Site, Species from pymatgen.electronic_structure.core import Magmom -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestSite(PymatgenTest): - def setUp(self): +class TestSite(MatSciTest): + def setup_method(self): self.ordered_site = Site("Fe", [0.25, 0.35, 0.45]) self.disordered_site = Site({"Fe": 0.5, "Mn": 0.5}, [0.25, 0.35, 0.45]) self.propertied_site = Site("Fe2+", [0.25, 0.35, 0.45], {"magmom": 5.1, "charge": 4.2}) @@ -79,8 +79,8 @@ def test_setters(self): self.disordered_site.species = {"Cu": 0.5, "Gd": 0.6} -class TestPeriodicSite(PymatgenTest): - def setUp(self): +class TestPeriodicSite(MatSciTest): + def setup_method(self): self.lattice = Lattice.cubic(10.0) self.si = Element("Si") self.site = PeriodicSite("Fe", [0.25, 0.35, 0.45], self.lattice) diff --git a/tests/core/test_spectrum.py b/tests/core/test_spectrum.py index 2f8f208c175..32d7760a992 100644 --- a/tests/core/test_spectrum.py +++ b/tests/core/test_spectrum.py @@ -6,11 +6,11 @@ from scipy import stats from pymatgen.core.spectrum import Spectrum -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestSpectrum(PymatgenTest): - def setUp(self): +class TestSpectrum(MatSciTest): + def setup_method(self): rng = np.random.default_rng() self.spec1 = Spectrum(np.arange(0, 10, 0.1), rng.standard_normal(100)) self.spec2 = Spectrum(np.arange(0, 10, 0.1), rng.standard_normal(100)) diff --git a/tests/core/test_structure.py b/tests/core/test_structure.py index 1a1e8397903..ba8b2bd3fb7 100644 --- a/tests/core/test_structure.py +++ b/tests/core/test_structure.py @@ -31,7 +31,7 @@ from pymatgen.io.cif import CifParser from pymatgen.io.vasp.inputs import Poscar from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, MatSciTest try: from ase.atoms import Atoms @@ -47,7 +47,7 @@ class TestNeighbor: def test_msonable(self): - struct = PymatgenTest.get_structure("Li2O") + struct = MatSciTest.get_structure("Li2O") nn = struct.get_neighbors(struct[0], r=3) assert isinstance(nn[0], PeriodicNeighbor) str_ = json.dumps(nn, cls=MontyEncoder) @@ -64,8 +64,8 @@ def test_neighbor_labels(self): assert p_neighbor.label == label if label is not None else "C" -class TestIStructure(PymatgenTest): - def setUp(self): +class TestIStructure(MatSciTest): + def setup_method(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] self.lattice = Lattice( [ @@ -966,8 +966,8 @@ def test_sites_setter(self): assert struct.sites == new_sites -class TestStructure(PymatgenTest): - def setUp(self): +class TestStructure(MatSciTest): + def setup_method(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = Lattice( [ @@ -1025,7 +1025,7 @@ def test_mutable_sequence_methods(self): assert struct.formula == "Mn1" # Test slice replacement. - struct = PymatgenTest.get_structure("Li2O") + struct = MatSciTest.get_structure("Li2O") struct[:2] = "S" assert struct.formula == "Li1 S2" @@ -1268,7 +1268,7 @@ def test_remove_oxidation_states(self): assert struct_elem == struct_specie, "Oxidation state remover failed" def test_add_oxidation_state_by_guess(self): - struct = PymatgenTest.get_structure("Li2O") + struct = MatSciTest.get_structure("Li2O") returned = struct.add_oxidation_state_by_guess() assert returned is struct expected = [Species("Li", 1), Species("O", -2)] @@ -2073,8 +2073,8 @@ def test_struct_with_isotope(self): assert "Deuterium" not in [el.long_name for el in struct.composition.elements] -class TestIMolecule(PymatgenTest): - def setUp(self): +class TestIMolecule(MatSciTest): + def setup_method(self): coords = [ [0, 0, 0], [0, 0, 1.089], @@ -2368,8 +2368,8 @@ def test_to_file_alias(self): assert os.path.isfile(out_path) -class TestMolecule(PymatgenTest): - def setUp(self): +class TestMolecule(MatSciTest): + def setup_method(self): coords = [ [0, 0, 0], [0, 0, 1.089000], diff --git a/tests/core/test_surface.py b/tests/core/test_surface.py index ae192ef982d..b6ca0f8768e 100644 --- a/tests/core/test_surface.py +++ b/tests/core/test_surface.py @@ -2,9 +2,9 @@ import json import os -import unittest import numpy as np +import pytest from numpy.testing import assert_allclose from pytest import approx @@ -24,13 +24,13 @@ ) from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.symmetry.groups import SpaceGroup -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest PMG_CORE_DIR = os.path.dirname(pymatgen.core.__file__) -class TestSlab(PymatgenTest): - def setUp(self): +class TestSlab(MatSciTest): + def setup_method(self): zno1 = Structure.from_file(f"{TEST_FILES_DIR}/surfaces/ZnO-wz.cif", primitive=False) zno55 = SlabGenerator(zno1, [1, 0, 0], 5, 5, lll_reduce=False, center_slab=False).get_slab() @@ -346,8 +346,8 @@ def test_as_dict(self): assert slab == Slab.from_dict(d) -class TestSlabGenerator(PymatgenTest): - def setUp(self): +class TestSlabGenerator(MatSciTest): + def setup_method(self): lattice = Lattice.cubic(3.010) frac_coords = [ [0.00000, 0.00000, 0.00000], @@ -634,8 +634,8 @@ def test_bonds_broken(self): assert slabs[1].energy, 6.0 -class ReconstructionGeneratorTests(PymatgenTest): - def setUp(self): +class ReconstructionGeneratorTests(MatSciTest): + def setup_method(self): lattice = Lattice.cubic(3.51) species = ["Ni"] coords = [[0, 0, 0]] @@ -697,7 +697,7 @@ def test_get_d(self): s2 = recon2.get_unreconstructed_slabs()[0] assert get_d(s1) == approx(get_d(s2)) - @unittest.skip("This test relies on neighbor orders and is hard coded. Disable temporarily") + @pytest.mark.skip("This test relies on neighbor orders and is hard coded. Disable temporarily") def test_previous_reconstructions(self): # Test to see if we generated all reconstruction types correctly and nothing changes @@ -723,8 +723,8 @@ def test_previous_reconstructions(self): assert any(len(match.group_structures([struct, slab])) == 1 for slab in slabs) -class TestMillerIndexFinder(PymatgenTest): - def setUp(self): +class TestMillerIndexFinder(MatSciTest): + def setup_method(self): self.cscl = Structure.from_spacegroup("Pm-3m", Lattice.cubic(4.2), ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) self.Fe = Structure.from_spacegroup("Im-3m", Lattice.cubic(2.82), ["Fe"], [[0, 0, 0]]) mg_lattice = Lattice.from_parameters(3.2, 3.2, 5.13, 90, 90, 120) diff --git a/tests/core/test_tensors.py b/tests/core/test_tensors.py index 1c840dcfa2b..ea015d29c32 100644 --- a/tests/core/test_tensors.py +++ b/tests/core/test_tensors.py @@ -11,11 +11,11 @@ from pymatgen.core.operations import SymmOp from pymatgen.core.tensors import SquareTensor, Tensor, TensorCollection, TensorMapping, itertools, symmetry_reduce from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestTensor(PymatgenTest): - def setUp(self): +class TestTensor(MatSciTest): + def setup_method(self): rng = np.random.default_rng() self.vec = Tensor([1.0, 0.0, 0.0]) @@ -379,8 +379,8 @@ def test_round(self): assert isinstance(rounded, Tensor) -class TestTensorCollection(PymatgenTest): - def setUp(self): +class TestTensorCollection(MatSciTest): + def setup_method(self): self.seq_tc = list(np.arange(4 * 3**3).reshape((4, 3, 3, 3))) self.seq_tc = TensorCollection(self.seq_tc) self.rand_tc = TensorCollection(list(np.random.default_rng().random((4, 3, 3)))) @@ -472,8 +472,8 @@ def test_serialization(self): assert_allclose(t, t_new) -class TestSquareTensor(PymatgenTest): - def setUp(self): +class TestSquareTensor(MatSciTest): + def setup_method(self): self.rand_sqtensor = SquareTensor(np.random.default_rng().standard_normal((3, 3))) self.symm_sqtensor = SquareTensor([[0.1, 0.3, 0.4], [0.3, 0.5, 0.2], [0.4, 0.2, 0.6]]) self.non_invertible = SquareTensor([[0.1, 0, 0], [0.2, 0, 0], [0, 0, 0]]) diff --git a/tests/core/test_trajectory.py b/tests/core/test_trajectory.py index 3914747aa35..7c2fa2c4d9b 100644 --- a/tests/core/test_trajectory.py +++ b/tests/core/test_trajectory.py @@ -12,13 +12,13 @@ from pymatgen.core.trajectory import Trajectory from pymatgen.io.qchem.outputs import QCOutput from pymatgen.io.vasp.outputs import Xdatcar -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/core/trajectory" -class TestTrajectory(PymatgenTest): - def setUp(self): +class TestTrajectory(MatSciTest): + def setup_method(self): xdatcar = Xdatcar(f"{VASP_OUT_DIR}/XDATCAR_traj") self.traj = Trajectory.from_file(f"{VASP_OUT_DIR}/XDATCAR_traj") self.structures = xdatcar.structures diff --git a/tests/core/test_units.py b/tests/core/test_units.py index 88e06d92517..83b583154b8 100644 --- a/tests/core/test_units.py +++ b/tests/core/test_units.py @@ -26,7 +26,7 @@ eV_to_Ha, unitized, ) -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest def test_unit_conversions(): @@ -37,7 +37,7 @@ def test_unit_conversions(): assert amu_to_kg == approx(1.66053906660e-27) -class TestUnit(PymatgenTest): +class TestUnit(MatSciTest): def test_init(self): u1 = Unit((("m", 1), ("s", -1))) assert str(u1) == "m s^-1" @@ -53,7 +53,7 @@ def test_init(self): assert str(newton * Unit("m")) == "N m" -class TestFloatWithUnit(PymatgenTest): +class TestFloatWithUnit(MatSciTest): def test_energy(self): a = Energy(1.1, "eV") b = a.to("Ha") @@ -185,7 +185,7 @@ def test_neg(self): assert FloatWithUnit(-5, "MPa") == -x -class TestArrayWithUnit(PymatgenTest): +class TestArrayWithUnit(MatSciTest): def test_energy(self): """Similar to TestFloatWithUnit.test_energy. Check whether EnergyArray and FloatWithUnit have same behavior. @@ -202,7 +202,6 @@ def test_energy(self): assert e_in_ha == approx(0.0404242579378) e_in_j = EnergyArray(3.14, "J") assert (e_in_j.to("eV")) == approx(1.9598338493806797e19) - # self.assertRaises(ValueError, Energy, 1, "m") e2_in_ha = EnergyArray(1, "Ha") assert (e_in_ev + e2_in_ha) == approx(28.311386245987997) @@ -293,7 +292,7 @@ def test_as_base_units(self): assert_array_equal(ArrayWithUnit([5000000, 10000000], "Pa"), pressure_arr.as_base_units) -class TestDataPersistence(PymatgenTest): +class TestDataPersistence(MatSciTest): def test_pickle(self): """Test whether FloatWithUnit and ArrayWithUnit support pickle.""" for cls in [FloatWithUnit, ArrayWithUnit]: diff --git a/tests/core/test_xcfunc.py b/tests/core/test_xcfunc.py index 94627874bab..bafedc17902 100644 --- a/tests/core/test_xcfunc.py +++ b/tests/core/test_xcfunc.py @@ -3,11 +3,11 @@ import pytest from pymatgen.core.xcfunc import XcFunc -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestLibxcFunc(PymatgenTest): - def setUp(self) -> None: +class TestLibxcFunc(MatSciTest): + def setup_method(self) -> None: self.ixc_11 = XcFunc.from_abinit_ixc(11) def test_aliases(self): diff --git a/tests/electronic_structure/test_bandstructure.py b/tests/electronic_structure/test_bandstructure.py index 01cba9b7e51..ac2db63dbb5 100644 --- a/tests/electronic_structure/test_bandstructure.py +++ b/tests/electronic_structure/test_bandstructure.py @@ -2,7 +2,6 @@ import copy import json -from unittest import TestCase import numpy as np import pytest @@ -20,13 +19,13 @@ from pymatgen.electronic_structure.core import Orbital, Spin from pymatgen.electronic_structure.plotter import BSPlotterProjected from pymatgen.io.vasp import BSVasprun -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/bandstructure" -class TestKpoint(TestCase): - def setUp(self): +class TestKpoint: + def setup_method(self): self.lattice = Lattice.cubic(10.0) self.kpoint = Kpoint([0.1, 0.4, -0.5], self.lattice, label="X") @@ -68,8 +67,8 @@ def test_from_dict(self): assert kpoint.label == "X" -class TestBandStructureSymmLine(PymatgenTest): - def setUp(self): +class TestBandStructureSymmLine(MatSciTest): + def setup_method(self): self.bs: BandStructureSymmLine = loadfn(f"{TEST_DIR}/Cu2O_361_bandstructure.json") self.bs2: BandStructureSymmLine = loadfn(f"{TEST_DIR}/CaO_2605_bandstructure.json") self.bs_spin: BandStructureSymmLine = loadfn(f"{TEST_DIR}/NiO_19009_bandstructure.json") @@ -258,8 +257,8 @@ def test_apply_scissor_spin_polarized(self): assert bs_scissored.efermi != approx(orig_efermi) -class TestReconstructBandStructure(PymatgenTest): - def setUp(self): +class TestReconstructBandStructure(MatSciTest): + def setup_method(self): self.bs_cu: BandStructureSymmLine = loadfn(f"{TEST_DIR}/Cu_30_bandstructure.json") self.bs_cu2: BandStructureSymmLine = loadfn(f"{TEST_DIR}/Cu_30_bandstructure.json") @@ -277,8 +276,8 @@ def test_vasprun_bs(self): bs.get_projection_on_elements() -class TestLobsterBandStructureSymmLine(PymatgenTest): - def setUp(self): +class TestLobsterBandStructureSymmLine(MatSciTest): + def setup_method(self): with open( f"{TEST_FILES_DIR}/electronic_structure/cohp/Fatband_SiO2/Test_p/lobster_band_structure_spin.json", encoding="utf-8", diff --git a/tests/electronic_structure/test_boltztrap.py b/tests/electronic_structure/test_boltztrap.py index 646f7ca7981..bfda09913d3 100644 --- a/tests/electronic_structure/test_boltztrap.py +++ b/tests/electronic_structure/test_boltztrap.py @@ -2,7 +2,6 @@ import json from shutil import which -from unittest import TestCase import pytest from monty.serialization import loadfn @@ -24,9 +23,9 @@ @pytest.mark.skipif(not which("x_trans"), reason="No x_trans.") -class TestBoltztrapAnalyzer(TestCase): +class TestBoltztrapAnalyzer: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.bz = BoltztrapAnalyzer.from_files(f"{TEST_DIR}/transp/") cls.bz_bands = BoltztrapAnalyzer.from_files(f"{TEST_DIR}/bands/") cls.bz_up = BoltztrapAnalyzer.from_files(f"{TEST_DIR}/dos_up/", dos_spin=1) diff --git a/tests/electronic_structure/test_boltztrap2.py b/tests/electronic_structure/test_boltztrap2.py index b68c94e1cc4..47c4f3f06d0 100644 --- a/tests/electronic_structure/test_boltztrap2.py +++ b/tests/electronic_structure/test_boltztrap2.py @@ -1,7 +1,6 @@ from __future__ import annotations import shutil -from unittest import TestCase import numpy as np import pytest @@ -41,8 +40,8 @@ BZT_TRANSP_FN = f"{TEST_DIR}/bztTranspProps.json.gz" -class TestVasprunBSLoader(TestCase): - def setUp(self): +class TestVasprunBSLoader: + def setup_method(self): self.loader = VasprunBSLoader(VASP_RUN) assert self.loader is not None self.loader = VasprunBSLoader(BAND_STRUCT, VASP_RUN.final_structure) @@ -81,8 +80,8 @@ def test_get_volume(self): @pytest.mark.filterwarnings("ignore:BandstructureLoader is deprecated:DeprecationWarning") -class TestBandstructureLoader(TestCase): - def setUp(self): +class TestBandstructureLoader: + def setup_method(self): self.loader = BandstructureLoader(BAND_STRUCT, VASP_RUN.structures[-1]) assert self.loader is not None @@ -109,8 +108,8 @@ def test_set_upper_lower_bands(self): @pytest.mark.filterwarnings("ignore:VasprunLoader is deprecated:DeprecationWarning") -class TestVasprunLoader(TestCase): - def setUp(self): +class TestVasprunLoader: + def setup_method(self): self.loader = VasprunLoader(VASP_RUN) assert self.loader.proj.shape == (120, 20, 2, 9) assert self.loader is not None @@ -128,8 +127,8 @@ def test_from_file(self): assert self.loader is not None -class TestBztInterpolator(TestCase): - def setUp(self): +class TestBztInterpolator: + def setup_method(self): with ScratchDir("."): shutil.copy(BZT_INTERP_FN, ".") @@ -207,8 +206,8 @@ def test_tot_proj_dos(self): assert pdos == approx(272.194174, abs=1e-5) -class TestBztTransportProperties(TestCase): - def setUp(self): +class TestBztTransportProperties: + def setup_method(self): with ScratchDir("."): shutil.copy(BZT_TRANSP_FN, ".") diff --git a/tests/electronic_structure/test_cohp.py b/tests/electronic_structure/test_cohp.py index 92d3c46facf..3e26c207860 100644 --- a/tests/electronic_structure/test_cohp.py +++ b/tests/electronic_structure/test_cohp.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase import pytest from numpy.testing import assert_allclose, assert_array_equal @@ -15,13 +14,13 @@ get_integrated_cohp_in_energy_range, ) from pymatgen.electronic_structure.core import Orbital, Spin -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/cohp" -class TestCohp(TestCase): - def setUp(self): +class TestCohp: + def setup_method(self): with open(f"{TEST_DIR}/cohp.json", encoding="utf-8") as file: self.cohp = Cohp.from_dict(json.load(file)) self.cohp_only = Cohp(self.cohp.efermi, self.cohp.energies, self.cohp.cohp) @@ -90,8 +89,8 @@ def test_antibnd_states_below_efermi(self): assert self.cohp.has_antibnd_states_below_efermi(spin=Spin.up, limit=0.5) == {Spin.up: False} -class TestIcohpValue(TestCase): - def setUp(self): +class TestIcohpValue: + def setup_method(self): # without spin polarization label = "1" atom1 = "K1" @@ -168,8 +167,8 @@ def test_str(self): assert str(self.icohpvalue_sp) == expected -class TestCombinedIcohp(TestCase): - def setUp(self): +class TestCombinedIcohp: + def setup_method(self): # without spin polarization: are_coops = are_cobis = is_spin_polarized = False list_atom2 = ["K2", "K2", "K2", "K2", "K2", "K2"] @@ -797,8 +796,8 @@ def test_extremum_icohpvalue(self): assert self.icoopcollection_Fe.extremum_icohpvalue(summed_spin_channels=False, spin=Spin.down) == -0.05756 -class TestCompleteCohp(PymatgenTest): - def setUp(self): +class TestCompleteCohp(MatSciTest): + def setup_method(self): filepath = f"{TEST_DIR}/complete_cohp_lobster.json" with open(filepath, encoding="utf-8") as file: self.cohp_lobster_dict = CompleteCohp.from_dict(json.load(file)) @@ -1262,8 +1261,8 @@ def test_orbital_resolved_cohp_summed_spin_channels(self): ).are_coops -class TestMethod(TestCase): - def setUp(self): +class TestMethod: + def setup_method(self): filepath = f"{TEST_DIR}/COHPCAR.lobster.gz" structure = f"{TEST_DIR}/POSCAR" self.cohp_lobster = CompleteCohp.from_file("lobster", filename=filepath, structure_file=structure) diff --git a/tests/electronic_structure/test_dos.py b/tests/electronic_structure/test_dos.py index db1224adcb5..f39722d21b8 100644 --- a/tests/electronic_structure/test_dos.py +++ b/tests/electronic_structure/test_dos.py @@ -2,7 +2,6 @@ import json import re -from unittest import TestCase import numpy as np import pytest @@ -14,13 +13,13 @@ from pymatgen.core import Element, Structure from pymatgen.electronic_structure.core import Orbital, OrbitalType, Spin from pymatgen.electronic_structure.dos import DOS, CompleteDos, FermiDos, LobsterCompleteDos -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/dos" -class TestDos(TestCase): - def setUp(self): +class TestDos: + def setup_method(self): with open(f"{TEST_DIR}/complete_dos.json", encoding="utf-8") as file: self.dos = CompleteDos.from_dict(json.load(file)) @@ -57,8 +56,8 @@ def test_as_dict(self): assert not isinstance(dos_dict["densities"]["1"][0], np.float64) -class TestFermiDos(TestCase): - def setUp(self): +class TestFermiDos: + def setup_method(self): with open(f"{TEST_DIR}/complete_dos.json", encoding="utf-8") as file: self.dos = CompleteDos.from_dict(json.load(file)) self.dos = FermiDos(self.dos) @@ -104,8 +103,8 @@ def test_as_dict(self): assert not isinstance(dos_dict["densities"]["1"][0], np.float64) -class TestCompleteDos(TestCase): - def setUp(self): +class TestCompleteDos: + def setup_method(self): with open(f"{TEST_DIR}/complete_dos.json", encoding="utf-8") as file: self.dos = CompleteDos.from_dict(json.load(file)) with zopen(f"{TEST_DIR}/pdag3_complete_dos.json.gz", mode="rt", encoding="utf-8") as file: @@ -323,8 +322,8 @@ def test_dos_fp_exceptions(self): self.dos.get_dos_fp_similarity(dos_fp, dos_fp2, col=1, metric=metric, normalize=False) -class TestDOS(PymatgenTest): - def setUp(self): +class TestDOS(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/complete_dos.json", encoding="utf-8") as file: dct = json.load(file) ys = list(zip(dct["densities"]["1"], dct["densities"]["-1"], strict=True)) @@ -351,15 +350,15 @@ def test_get_gap(self): assert_allclose(self.dos.get_cbm_vbm(spin=Spin.down), (4.645, 1.8140000000000001)) -class TestSpinPolarization(TestCase): +class TestSpinPolarization: def test_spin_polarization(self): dos_path = f"{TEST_DIR}/dos_spin_polarization_mp-865805.json" dos = loadfn(dos_path) assert dos.spin_polarization == approx(0.6460514663341762) -class TestLobsterCompleteDos(TestCase): - def setUp(self): +class TestLobsterCompleteDos: + def setup_method(self): with open(f"{TEST_DIR}/LobsterCompleteDos_spin.json", encoding="utf-8") as file: data_spin = json.load(file) self.LobsterCompleteDOS_spin = LobsterCompleteDos.from_dict(data_spin) diff --git a/tests/electronic_structure/test_plotter.py b/tests/electronic_structure/test_plotter.py index 7c9ea58ce37..121e5ce0467 100644 --- a/tests/electronic_structure/test_plotter.py +++ b/tests/electronic_structure/test_plotter.py @@ -3,7 +3,6 @@ import json import os from shutil import which -from unittest import TestCase import matplotlib.pyplot as plt import numpy as np @@ -30,15 +29,15 @@ plot_ellipsoid, ) from pymatgen.io.vasp import Vasprun -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest BAND_TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/bandstructure" rc("text", usetex=False) # Disabling latex is needed for this test to work. -class TestDosPlotter(PymatgenTest): - def setUp(self): +class TestDosPlotter(MatSciTest): + def setup_method(self): with open(f"{BAND_TEST_DIR}/../dos/complete_dos.json", encoding="utf-8") as file: self.dos = CompleteDos.from_dict(json.load(file)) self.plotter = DosPlotter(sigma=0.2, stack=True) @@ -91,8 +90,8 @@ def get_plot_attributes(ax: plt.Axes): } -class TestBSPlotter(PymatgenTest): - def setUp(self): +class TestBSPlotter(MatSciTest): + def setup_method(self): with open(f"{BAND_TEST_DIR}/CaO_2605_bandstructure.json", encoding="utf-8") as file: dct = json.loads(file.read()) self.bs = BandStructureSymmLine.from_dict(dct) @@ -184,8 +183,8 @@ def test_get_plot(self): plt.close("all") -class TestBSPlotterProjected(TestCase): - def setUp(self): +class TestBSPlotterProjected: + def setup_method(self): with open(f"{BAND_TEST_DIR}/Cu2O_361_bandstructure.json", encoding="utf-8") as file: self.bs_Cu2O = BandStructureSymmLine.from_dict(json.load(file)) self.plotter_Cu2O = BSPlotterProjected(self.bs_Cu2O) @@ -259,8 +258,8 @@ def test_methods(self): assert isinstance(ax, plt.Axes) -class TestPlotBZ(TestCase): - def setUp(self): +class TestPlotBZ: + def setup_method(self): self.rec_latt = Structure.from_file(f"{TEST_FILES_DIR}/io/cssr/Si.cssr").lattice.reciprocal_lattice self.kpath = [[[0.0, 0.0, 0.0], [0.5, 0.0, 0.5], [0.5, 0.25, 0.75], [0.375, 0.375, 0.75]]] self.labels = { @@ -305,8 +304,8 @@ def test_fold_point(self): @pytest.mark.skip("TODO: need someone to fix this") @pytest.mark.skipif(not which("x_trans"), reason="No x_trans executable found") -class TestBoltztrapPlotter(TestCase): - def setUp(self): +class TestBoltztrapPlotter: + def setup_method(self): bz = BoltztrapAnalyzer.from_files(f"{TEST_FILES_DIR}/boltztrap/transp/") self.plotter = BoltztrapPlotter(bz) @@ -446,8 +445,8 @@ def test_plot_zt_temp(self): plt.close() -class TestCohpPlotter(PymatgenTest): - def setUp(self): +class TestCohpPlotter(MatSciTest): + def setup_method(self): path = f"{TEST_FILES_DIR}/electronic_structure/cohp/complete_cohp_lobster.json" with open(path, encoding="utf-8") as file: self.cohp = CompleteCohp.from_dict(json.load(file)) diff --git a/tests/entries/test_compatibility.py b/tests/entries/test_compatibility.py index 528453e3056..a5ef87b9154 100644 --- a/tests/entries/test_compatibility.py +++ b/tests/entries/test_compatibility.py @@ -7,7 +7,6 @@ from collections import defaultdict from pathlib import Path from typing import TYPE_CHECKING -from unittest import TestCase import pytest from monty.json import MontyDecoder @@ -43,10 +42,10 @@ @pytest.mark.filterwarnings("ignore:MaterialsProjectCompatibility is deprecated") -class TestCorrectionSpecificity(TestCase): +class TestCorrectionSpecificity: """Make sure corrections are only applied to GGA or GGA+U entries.""" - def setUp(self): + def setup_method(self): self.entry1 = ComputedEntry( "Fe2O3", -1, @@ -204,8 +203,8 @@ def test_overlapping_adjustments(): @pytest.mark.filterwarnings("ignore:MaterialsProjectCompatibility is deprecated") -class TestMaterialsProjectCompatibility(TestCase): - def setUp(self): +class TestMaterialsProjectCompatibility: + def setup_method(self): self.entry1 = ComputedEntry( "Fe2O3", -1, @@ -621,8 +620,8 @@ def test_msonable(self): assert isinstance(temp_compat, MaterialsProjectCompatibility) -class TestMaterialsProjectCompatibility2020(TestCase): - def setUp(self): +class TestMaterialsProjectCompatibility2020: + def setup_method(self): self.entry1 = ComputedEntry( "Fe2O3", -1, @@ -1315,8 +1314,8 @@ def test_many_anions(self): assert processed_entry.energy == -1 -class TestMITCompatibility(TestCase): - def setUp(self): +class TestMITCompatibility: + def setup_method(self): self.compat = MITCompatibility(check_potcar_hash=True) self.gga_compat = MITCompatibility("GGA", check_potcar_hash=True) self.entry_O = ComputedEntry( @@ -1655,8 +1654,8 @@ def test_msonable(self): assert isinstance(temp_compat, MITCompatibility) -class TestOxideTypeCorrection(TestCase): - def setUp(self): +class TestOxideTypeCorrection: + def setup_method(self): self.compat = MITCompatibility(check_potcar_hash=True) def test_no_struct_compat(self): @@ -1826,8 +1825,8 @@ def test_process_entry_oxide(self): assert li2o_entry_corrected.energy == approx(-3.0 - 0.66975) -class TestSulfideTypeCorrection2020(TestCase): - def setUp(self): +class TestSulfideTypeCorrection2020: + def setup_method(self): self.compat = MaterialsProject2020Compatibility(check_potcar_hash=False) def test_struct_no_struct(self): @@ -1986,8 +1985,8 @@ def test_struct_no_struct(self): assert struct_corrected.correction == approx(nostruct_corrected.correction) -class TestOxideTypeCorrectionNoPeroxideCorr(TestCase): - def setUp(self): +class TestOxideTypeCorrectionNoPeroxideCorr: + def setup_method(self): self.compat = MITCompatibility(correct_peroxide=False) def test_oxide_energy_corr(self): @@ -2254,8 +2253,8 @@ def test_parallel_process_entries(self): assert len(entries) == 2 -class TestAqueousCorrection(TestCase): - def setUp(self): +class TestAqueousCorrection: + def setup_method(self): fp = f"{PMG_ENTRIES_DIR}/MITCompatibility.yaml" self.corr = AqueousCorrection(fp) @@ -2281,8 +2280,8 @@ def test_compound_energy(self): assert entry.energy == approx(-24.344373) -class TestMITAqueousCompatibility(TestCase): - def setUp(self): +class TestMITAqueousCompatibility: + def setup_method(self): self.compat = MITCompatibility(check_potcar_hash=True) self.aqcompat = MITAqueousCompatibility(check_potcar_hash=True) fp = f"{PMG_ENTRIES_DIR}/MITCompatibility.yaml" @@ -2392,8 +2391,8 @@ def test_dont_error_on_weird_elements(self): assert self.compat.process_entry(entry) is None -class TestCorrectionErrors2020Compatibility(TestCase): - def setUp(self): +class TestCorrectionErrors2020Compatibility: + def setup_method(self): self.compat = MaterialsProject2020Compatibility() params = { diff --git a/tests/entries/test_computed_entries.py b/tests/entries/test_computed_entries.py index 9894f886c4c..f8bf03a95f5 100644 --- a/tests/entries/test_computed_entries.py +++ b/tests/entries/test_computed_entries.py @@ -3,7 +3,6 @@ import copy import json from collections import defaultdict -from unittest import TestCase import pytest from monty.json import MontyDecoder @@ -95,8 +94,8 @@ def test_temp_energy_adjustment(): assert str(ea_dct) == str(ea2.as_dict()) -class TestComputedEntry(TestCase): - def setUp(self): +class TestComputedEntry: + def setup_method(self): self.entry = ComputedEntry( vasp_run.final_structure.composition, vasp_run.final_energy, @@ -256,8 +255,8 @@ def test_from_dict_null_fields(self): assert getattr(new_ce, k, None) is not None -class TestComputedStructureEntry(TestCase): - def setUp(self): +class TestComputedStructureEntry: + def setup_method(self): self.entry = ComputedStructureEntry(vasp_run.final_structure, vasp_run.final_energy, parameters=vasp_run.incar) def test_energy(self): @@ -453,8 +452,8 @@ def test_eq(self): assert copy3 != copy1 -class TestGibbsComputedStructureEntry(TestCase): - def setUp(self): +class TestGibbsComputedStructureEntry: + def setup_method(self): self.temps = [300, 600, 900, 1200, 1500, 1800] self.struct = vasp_run.final_structure self.num_atoms = self.struct.composition.num_atoms diff --git a/tests/entries/test_correction_calculator.py b/tests/entries/test_correction_calculator.py index 209f781be41..d0dfa81e039 100644 --- a/tests/entries/test_correction_calculator.py +++ b/tests/entries/test_correction_calculator.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pytest from pymatgen.entries.correction_calculator import CorrectionCalculator @@ -10,8 +8,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/entries/correction_calculator" -class TestCorrectionCalculator(TestCase): - def setUp(self): +class TestCorrectionCalculator: + def setup_method(self): self.exclude_polyanions = [ "SO4", "CO3", diff --git a/tests/entries/test_entry_tools.py b/tests/entries/test_entry_tools.py index 73d2d721d7b..0ce519a2176 100644 --- a/tests/entries/test_entry_tools.py +++ b/tests/entries/test_entry_tools.py @@ -9,12 +9,12 @@ from pymatgen.core import Element from pymatgen.entries.computed_entries import ComputedEntry from pymatgen.entries.entry_tools import EntrySet, group_entries_by_composition, group_entries_by_structure -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/entries" -class TestFunc(PymatgenTest): +class TestFunc(MatSciTest): def test_group_entries_by_structure(self): entries = loadfn(f"{TEST_DIR}/TiO2_entries.json") groups = group_entries_by_structure(entries) @@ -49,8 +49,8 @@ def test_group_entries_by_composition(self): assert group == sorted(group, key=lambda e: e.energy_per_atom) -class TestEntrySet(PymatgenTest): - def setUp(self): +class TestEntrySet(MatSciTest): + def setup_method(self): entries = loadfn(f"{TEST_DIR}/Li-Fe-P-O_entries.json") self.entry_set = EntrySet(entries) diff --git a/tests/entries/test_exp_entries.py b/tests/entries/test_exp_entries.py index 4ddc4ab1d40..db3364c39de 100644 --- a/tests/entries/test_exp_entries.py +++ b/tests/entries/test_exp_entries.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase from monty.json import MontyDecoder from pytest import approx @@ -10,8 +9,8 @@ from pymatgen.util.testing import TEST_FILES_DIR -class TestExpEntry(TestCase): - def setUp(self): +class TestExpEntry: + def setup_method(self): with open(f"{TEST_FILES_DIR}/entries/Fe2O3_exp.json", encoding="utf-8") as file: thermo_data = json.load(file, cls=MontyDecoder) self.entry = ExpEntry("Fe2O3", thermo_data) diff --git a/tests/ext/test_matproj.py b/tests/ext/test_matproj.py index a730bca4dd0..11d23eea39b 100644 --- a/tests/ext/test_matproj.py +++ b/tests/ext/test_matproj.py @@ -23,7 +23,7 @@ from pymatgen.ext.matproj_legacy import MPRestError, TaskType, _MPResterLegacy from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.phonon.dos import CompletePhononDos -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest PMG_MAPI_KEY = SETTINGS.get("PMG_MAPI_KEY", "") if (10 < len(PMG_MAPI_KEY) <= 20) and "PMG_MAPI_KEY" in SETTINGS: @@ -48,8 +48,8 @@ not 10 < len(PMG_MAPI_KEY) <= 20, reason="Legacy PMG_MAPI_KEY environment variable not set.", ) -class TestMPResterOld(PymatgenTest): - def setUp(self): +class TestMPResterOld(MatSciTest): + def setup_method(self): self.rester = _MPResterLegacy() def test_get_all_materials_ids_doc(self): @@ -528,8 +528,8 @@ def test_api_key_is_none(self): not len(PMG_MAPI_KEY) > 20, reason="PMG_MAPI_KEY environment variable not set.", ) -class TestMPResterNewBasic(PymatgenTest): - def setUp(self): +class TestMPResterNewBasic(MatSciTest): + def setup_method(self): self.rester = _MPResterBasic() def test_get_summary(self): diff --git a/tests/ext/test_optimade.py b/tests/ext/test_optimade.py index a4182761168..5be9ca18913 100644 --- a/tests/ext/test_optimade.py +++ b/tests/ext/test_optimade.py @@ -4,7 +4,7 @@ import requests from pymatgen.ext.optimade import OptimadeRester -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest try: # 403 is returned when server detects bot-like behavior @@ -36,7 +36,7 @@ mc2d_down = True -class TestOptimade(PymatgenTest): +class TestOptimade(MatSciTest): @pytest.mark.skipif(mp_website_down, reason="MP OPTIMADE is down.") def test_get_structures_mp(self): with OptimadeRester("mp") as optimade: diff --git a/tests/io/abinit/test_abiobjects.py b/tests/io/abinit/test_abiobjects.py index ad38c49dafe..18da2286a01 100644 --- a/tests/io/abinit/test_abiobjects.py +++ b/tests/io/abinit/test_abiobjects.py @@ -19,10 +19,10 @@ species_by_znucl, structure_to_abivars, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestLatticeFromAbivars(PymatgenTest): +class TestLatticeFromAbivars(MatSciTest): def test_rprim_acell(self): l1 = lattice_from_abivars(acell=3 * [10], rprim=np.eye(3)) assert l1.volume == approx(bohr_to_ang**3 * 1000) @@ -108,7 +108,7 @@ def test_znucl_typat(self): structure_to_abivars(gan, enforce_znucl=enforce_znucl, enforce_typat=None) -class TestSpinMode(PymatgenTest): +class TestSpinMode(MatSciTest): def test_base(self): polarized = SpinMode.as_spinmode("polarized") other_polarized = SpinMode.as_spinmode("polarized") @@ -128,7 +128,7 @@ def test_base(self): self.assert_msonable(unpolarized) -class TestSmearing(PymatgenTest): +class TestSmearing(MatSciTest): def test_base(self): fd1ev = Smearing.as_smearing("fermi_dirac:1 eV") fd1ev.to_abivars() @@ -156,7 +156,7 @@ def test_base(self): self.assert_msonable(fd1ev) -class TestElectronsAlgorithm(PymatgenTest): +class TestElectronsAlgorithm(MatSciTest): def test_base(self): algo = ElectronsAlgorithm(nstep=70) _ = algo.to_abivars() @@ -168,7 +168,7 @@ def test_base(self): self.assert_msonable(algo) -class TestElectrons(PymatgenTest): +class TestElectrons(MatSciTest): def test_base(self): default_electrons = Electrons() assert default_electrons.nsppol == 2 @@ -195,7 +195,7 @@ def test_base(self): self.assert_msonable(custom_electrons) -class TestKSampling(PymatgenTest): +class TestKSampling(MatSciTest): def test_base(self): monkhorst = KSampling.monkhorst((3, 3, 3), (0.5, 0.5, 0.5), 0, use_symmetries=False, use_time_reversal=False) gamma_centered = KSampling.gamma_centered((3, 3, 3), use_symmetries=False, use_time_reversal=False) @@ -207,7 +207,7 @@ def test_base(self): self.assert_msonable(gamma_centered) -class TestRelaxation(PymatgenTest): +class TestRelaxation(MatSciTest): def test_base(self): atoms_and_cell = RelaxationMethod.atoms_and_cell() atoms_only = RelaxationMethod.atoms_only() @@ -227,7 +227,7 @@ def test_base(self): self.assert_msonable(atoms_only) -class TestPPModel(PymatgenTest): +class TestPPModel(MatSciTest): def test_base(self): godby = PPModel.as_ppmodel("godby:12 eV") godby.to_abivars() diff --git a/tests/io/abinit/test_inputs.py b/tests/io/abinit/test_inputs.py index 762ea2acad8..f39a4ce656d 100644 --- a/tests/io/abinit/test_inputs.py +++ b/tests/io/abinit/test_inputs.py @@ -18,7 +18,7 @@ ion_ioncell_relax_input, num_valence_electrons, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/abinit" @@ -33,7 +33,7 @@ def abiref_files(*filenames): return [f"{TEST_DIR}/{file}" for file in filenames] -class TestAbinitInput(PymatgenTest): +class TestAbinitInput(MatSciTest): """Unit tests for BasicAbinitInput.""" def test_api(self): @@ -168,7 +168,7 @@ def test_helper_functions(self): assert len(inp["kptbounds"]) == 12 -class TestMultiDataset(PymatgenTest): +class TestMultiDataset(MatSciTest): """Unit tests for BasicMultiDataset.""" def test_api(self): @@ -251,7 +251,7 @@ def test_api(self): self.serialize_with_pickle(multi, test_eq=False) -class TestShiftMode(PymatgenTest): +class TestShiftMode(MatSciTest): def test_shiftmode(self): gamma = ShiftMode.GammaCentered assert ShiftMode.from_object("G") == gamma @@ -260,8 +260,8 @@ def test_shiftmode(self): ShiftMode.from_object({}) -class TestFactory(PymatgenTest): - def setUp(self): +class TestFactory(MatSciTest): + def setup_method(self): # Si ebands self.si_structure = Structure.from_file(abiref_file("si.cif")) self.si_pseudo = abiref_file("14si.pspnc") diff --git a/tests/io/abinit/test_netcdf.py b/tests/io/abinit/test_netcdf.py index b4b2ffa68c1..d53e86d6bff 100644 --- a/tests/io/abinit/test_netcdf.py +++ b/tests/io/abinit/test_netcdf.py @@ -11,7 +11,7 @@ from pymatgen.core.structure import Structure from pymatgen.io.abinit import EtsfReader from pymatgen.io.abinit.netcdf import AbinitHeader -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: import netCDF4 @@ -21,8 +21,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/abinit" -class TestEtsfReader(PymatgenTest): - def setUp(self): +class TestEtsfReader(MatSciTest): + def setup_method(self): formulas = ["Si2"] self.GSR_paths = dct = {} for formula in formulas: @@ -117,7 +117,7 @@ def test_read_fe(self): assert structure.site_properties["magmom"] == ref_magmom_noncollinear -class TestAbinitHeader(PymatgenTest): +class TestAbinitHeader(MatSciTest): def test_api(self): head = AbinitHeader(foo=1, bar=2) assert head.foo == 1 diff --git a/tests/io/abinit/test_pseudos.py b/tests/io/abinit/test_pseudos.py index 8cd9bace814..5badaada393 100644 --- a/tests/io/abinit/test_pseudos.py +++ b/tests/io/abinit/test_pseudos.py @@ -9,13 +9,13 @@ from pytest import approx from pymatgen.io.abinit.pseudos import Pseudo, PseudoTable -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/abinit" -class TestPseudo(PymatgenTest): - def setUp(self): +class TestPseudo(MatSciTest): + def setup_method(self): nc_pseudo_fnames = defaultdict(list) nc_pseudo_fnames["Si"] = [f"{TEST_DIR}/{file}" for file in ("14si.pspnc", "14si.4.hgh", "14-Si.LDA.fhi")] @@ -198,7 +198,7 @@ def test_oncvpsp_pseudo_fr(self): assert pb.supports_soc -class TestPseudoTable(PymatgenTest): +class TestPseudoTable(MatSciTest): def test_methods(self): """Test PseudoTable methods.""" table = PseudoTable([f"{TEST_DIR}/{file}" for file in ("14si.pspnc", "14si.4.hgh", "14-Si.LDA.fhi")]) diff --git a/tests/io/cp2k/test_inputs.py b/tests/io/cp2k/test_inputs.py index ec0b772c617..152b62d9804 100644 --- a/tests/io/cp2k/test_inputs.py +++ b/tests/io/cp2k/test_inputs.py @@ -22,7 +22,7 @@ Section, SectionList, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/cp2k" @@ -41,7 +41,7 @@ """ -class TestBasis(PymatgenTest): +class TestBasis(MatSciTest): def test_basis_info(self): # Ensure basis metadata can be read from string basis_info = BasisInfo.from_str("cc-pc-DZVP-MOLOPT-q1-SCAN") @@ -92,7 +92,7 @@ def test_basis(self): mol_opt.info.admm = False -class TestPotential(PymatgenTest): +class TestPotential(MatSciTest): all_hydrogen_str = """ H ALLELECTRON ALL 1 0 0 @@ -144,7 +144,7 @@ def test_potentials(self): assert kw.values[0] == "ALL" -class TestCp2kInput(PymatgenTest): +class TestCp2kInput(MatSciTest): si_struct = Structure( lattice=[ [0, 2.734364, 2.734364], @@ -170,7 +170,7 @@ class TestCp2kInput(PymatgenTest): &END """ - def setUp(self): + def setup_method(self): self.ci = Cp2kInput.from_file(f"{TEST_DIR}/cp2k.inp") def test_basic_sections(self): @@ -268,7 +268,7 @@ def test_mongo(self): assert cp2k_input.check("global/subsec2") -class TestDataFile(PymatgenTest): +class TestDataFile(MatSciTest): def test_data_file(self): # make temp file with BASIS_FILE_STR data_file = self.tmp_path / "data-file" diff --git a/tests/io/cp2k/test_outputs.py b/tests/io/cp2k/test_outputs.py index 84c3fab0e18..ee8496beba0 100644 --- a/tests/io/cp2k/test_outputs.py +++ b/tests/io/cp2k/test_outputs.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np from numpy.testing import assert_allclose from pytest import approx @@ -12,8 +10,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/cp2k" -class TestCp2kOutput(TestCase): - def setUp(self): +class TestCp2kOutput: + def setup_method(self): self.out = Cp2kOutput(f"{TEST_DIR}/cp2k.out", auto_load=True) def test_files(self): diff --git a/tests/io/cp2k/test_sets.py b/tests/io/cp2k/test_sets.py index e2c74bc31a6..8f7a0249bc3 100644 --- a/tests/io/cp2k/test_sets.py +++ b/tests/io/cp2k/test_sets.py @@ -6,7 +6,7 @@ from pymatgen.core.structure import Molecule, Structure from pymatgen.io.cp2k.sets import SETTINGS, Cp2kValidationError, DftSet, GaussianTypeOrbitalBasisSet, GthPotential -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest CP2K_TEST_DIR = f"{TEST_FILES_DIR}/io/cp2k" @@ -46,7 +46,7 @@ } -class TestDftSet(PymatgenTest): +class TestDftSet(MatSciTest): def test_dft_set(self) -> None: """Test various DFT set configurations.""" SETTINGS["PMG_CP2K_DATA_DIR"] = CP2K_TEST_DIR diff --git a/tests/io/exciting/test_inputs.py b/tests/io/exciting/test_inputs.py index 0f119448c02..908103069dd 100644 --- a/tests/io/exciting/test_inputs.py +++ b/tests/io/exciting/test_inputs.py @@ -8,7 +8,7 @@ from pymatgen.core import Lattice, Structure from pymatgen.io.exciting import ExcitingInput -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Christian Vorwerk" __copyright__ = "Copyright 2016" @@ -21,7 +21,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/exciting" -class TestExcitingInput(PymatgenTest): +class TestExcitingInput(MatSciTest): def test_fromfile(self): # Test for the import of a structure directly from an exciting # input file diff --git a/tests/io/feff/test_inputs.py b/tests/io/feff/test_inputs.py index 57a41d39675..d5a3b219430 100644 --- a/tests/io/feff/test_inputs.py +++ b/tests/io/feff/test_inputs.py @@ -1,7 +1,6 @@ from __future__ import annotations import os -from unittest import TestCase from numpy.testing import assert_allclose from pytest import approx @@ -27,7 +26,7 @@ * 4 O 0.333333 0.666667 0.378675""" -class TestHeader(TestCase): +class TestHeader: def test_init(self): filepath = f"{FEFF_TEST_DIR}/HEADER" header = Header.header_string_from_file(filepath) @@ -56,9 +55,9 @@ def test_as_dict_and_from_dict(self): assert str(header) == str(header2), "Header failed to and from dict test" -class TestFeffAtoms(TestCase): +class TestFeffAtoms: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.structure = Structure.from_file(f"{TEST_FILES_DIR}/cif/CoO19128.cif") cls.atoms = Atoms(cls.structure, "O", 12.0) @@ -143,7 +142,7 @@ def test_atom_num(self): assert atoms.formula == "Pt37" -class TestFeffTags(TestCase): +class TestFeffTags: def test_init(self): filepath = f"{FEFF_TEST_DIR}/PARAMETERS" parameters = Tags.from_file(filepath) @@ -212,7 +211,7 @@ def test_eels_tags(self): assert dict(tags_2) == ans_1 -class TestFeffPot(TestCase): +class TestFeffPot: def test_init(self): filepath = f"{FEFF_TEST_DIR}/POTENTIALS" feff_pot = Potential.pot_string_from_file(filepath) @@ -245,8 +244,8 @@ def test_as_dict_and_from_dict(self): assert str(pot) == str(pot2), "Potential to and from dict does not match" -class TestPaths(TestCase): - def setUp(self): +class TestPaths: + def setup_method(self): feo = Structure.from_dict( { "lattice": { diff --git a/tests/io/feff/test_outputs.py b/tests/io/feff/test_outputs.py index 7bc93959cba..cd5714ba631 100644 --- a/tests/io/feff/test_outputs.py +++ b/tests/io/feff/test_outputs.py @@ -1,14 +1,12 @@ from __future__ import annotations -from unittest import TestCase - from pymatgen.io.feff.outputs import LDos, Xmu from pymatgen.util.testing import TEST_FILES_DIR FEFF_TEST_DIR = f"{TEST_FILES_DIR}/io/feff" -class TestFeffLdos(TestCase): +class TestFeffLdos: filepath1 = f"{FEFF_TEST_DIR}/feff.inp" filepath2 = f"{FEFF_TEST_DIR}/ldos" ldos = LDos.from_file(filepath1, filepath2) @@ -49,7 +47,7 @@ def test_reci_charge(self): assert charge_trans["1"]["O"]["tot"] == -0.594 -class TestXmu(TestCase): +class TestXmu: def test_init(self): filepath1 = f"{FEFF_TEST_DIR}/xmu.dat" filepath2 = f"{FEFF_TEST_DIR}/feff.inp" diff --git a/tests/io/feff/test_sets.py b/tests/io/feff/test_sets.py index e57e560996c..f1f07970729 100644 --- a/tests/io/feff/test_sets.py +++ b/tests/io/feff/test_sets.py @@ -9,14 +9,14 @@ from pymatgen.core.structure import Lattice, Molecule, Structure from pymatgen.io.feff.inputs import Atoms, Header, Potential, Tags from pymatgen.io.feff.sets import FEFFDictSet, MPELNESSet, MPEXAFSSet, MPXANESSet -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest FEFF_TEST_DIR = f"{TEST_FILES_DIR}/io/feff" -class TestFeffInputSet(PymatgenTest): +class TestFeffInputSet(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.header_string = """* This FEFF.inp file generated by pymatgen TITLE comment: From cif file TITLE Source: CoO19128.cif diff --git a/tests/io/lammps/test_data.py b/tests/io/lammps/test_data.py index c134fd1472d..2f9c719acb1 100644 --- a/tests/io/lammps/test_data.py +++ b/tests/io/lammps/test_data.py @@ -2,7 +2,6 @@ import gzip import json -from unittest import TestCase import numpy as np import pandas as pd @@ -14,14 +13,14 @@ from pymatgen.core import Element, Lattice, Molecule, Structure from pymatgen.io.lammps.data import CombinedData, ForceField, LammpsBox, LammpsData, Topology, lattice_2_lmpbox -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/lammps" -class TestLammpsBox(PymatgenTest): +class TestLammpsBox(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.peptide = LammpsBox( bounds=[ [36.840194, 64.211560], @@ -73,9 +72,9 @@ def test_to_lattice(self): ) -class TestLammpsData(PymatgenTest): +class TestLammpsData(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.peptide = LammpsData.from_file(filename=f"{TEST_DIR}/data.peptide") cls.ethane = LammpsData.from_file(filename=f"{TEST_DIR}/ethane.data") cls.quartz = LammpsData.from_file(filename=f"{TEST_DIR}/data.quartz", atom_style="atomic") @@ -543,7 +542,7 @@ def test_json_dict(self): assert pd.testing.assert_frame_equal(c2h6.topology[key], target_df) is None, key -class TestTopology(TestCase): +class TestTopology: def test_init(self): rng = np.random.default_rng() inner_charge = rng.random(10) - 0.5 @@ -665,9 +664,9 @@ def test_from_bonding(self): assert "Dihedrals" not in topo_etoh2.topologies -class TestForceField(PymatgenTest): +class TestForceField(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): mass_info = [ ("A", "H"), ("B", Element("C")), @@ -785,7 +784,7 @@ def test_from_dict(self): assert decoded.topo_coeffs == self.ethane.topo_coeffs -class TestFunc(TestCase): +class TestFunc: def test_lattice_2_lmpbox(self): rng = np.random.default_rng() matrix = np.diag(rng.integers(5, 14, size=(3,))) + rng.random((3, 3)) * 0.2 - 0.1 @@ -818,9 +817,9 @@ def test_lattice_2_lmpbox(self): ) -class TestCombinedData(TestCase): +class TestCombinedData: @classmethod - def setUpClass(cls): + def setup_class(cls): cls.ec = LammpsData.from_file(filename=f"{TEST_DIR}/ec.data.gz") cls.fec = LammpsData.from_file(filename=f"{TEST_DIR}/fec.data.gz") cls.li = LammpsData.from_file(filename=f"{TEST_DIR}/li.data") diff --git a/tests/io/lammps/test_generators.py b/tests/io/lammps/test_generators.py index d19eddbf8df..8cb549c8d6e 100644 --- a/tests/io/lammps/test_generators.py +++ b/tests/io/lammps/test_generators.py @@ -3,14 +3,14 @@ from pymatgen.core.structure import Structure from pymatgen.io.lammps.data import LammpsData from pymatgen.io.lammps.generators import LammpsMinimization -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/lammps" -class TestLammpsMinimization(PymatgenTest): +class TestLammpsMinimization(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.filename = f"{TEST_DIR}/lgps.in" cls.cif = f"{TEST_DIR}/lgps.cif" cls.structure = Structure.from_file(cls.cif) diff --git a/tests/io/lammps/test_inputs.py b/tests/io/lammps/test_inputs.py index 638a5509ff2..b0dde9cf1a4 100644 --- a/tests/io/lammps/test_inputs.py +++ b/tests/io/lammps/test_inputs.py @@ -11,14 +11,14 @@ from pymatgen.core.structure import Structure from pymatgen.io.lammps.data import LammpsData from pymatgen.io.lammps.inputs import LammpsInputFile, LammpsRun, LammpsTemplateGen, write_lammps_inputs -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/lammps" -class TestLammpsInputFile(PymatgenTest): +class TestLammpsInputFile(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.filename = f"{TEST_DIR}/lgps.in" def test_from_file(self): @@ -640,7 +640,7 @@ def test_add_comment(self): ] -class TestLammpsRun(PymatgenTest): +class TestLammpsRun(MatSciTest): def test_md(self): struct = Structure.from_spacegroup(225, Lattice.cubic(3.62126), ["Cu"], [[0, 0, 0]]) ld = LammpsData.from_structure(struct, atom_style="atomic") @@ -690,7 +690,7 @@ def test_md(self): assert os.path.isfile(f"{self.tmp_path}/md/md.data") -class TestFunc(PymatgenTest): +class TestFunc(MatSciTest): @pytest.mark.filterwarnings("ignore:write_lammps_inputs is deprecated") def test_write_lammps_inputs(self): # script template @@ -727,7 +727,7 @@ def test_write_lammps_inputs(self): pd.testing.assert_frame_equal(obj_read.atoms, obj.atoms) -class TestLammpsTemplateGen(PymatgenTest): +class TestLammpsTemplateGen(MatSciTest): def test_write_inputs(self): # simple script without data file lis = LammpsTemplateGen().get_input_set( diff --git a/tests/io/lammps/test_outputs.py b/tests/io/lammps/test_outputs.py index 9c18bf04130..ceb14156474 100644 --- a/tests/io/lammps/test_outputs.py +++ b/tests/io/lammps/test_outputs.py @@ -2,7 +2,6 @@ import json import os -from unittest import TestCase import numpy as np import pandas as pd @@ -14,9 +13,9 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/lammps" -class TestLammpsDump(TestCase): +class TestLammpsDump: @classmethod - def setUpClass(cls): + def setup_class(cls): with open(f"{TEST_DIR}/dump.rdx_wc.100", encoding="utf-8") as file: rdx_str = file.read() cls.rdx = LammpsDump.from_str(string=rdx_str) @@ -54,7 +53,7 @@ def test_json_dict(self): pd.testing.assert_frame_equal(rdx.data, self.rdx.data) -class TestFunc(TestCase): +class TestFunc: def test_parse_lammps_dumps(self): # gzipped rdx_10_pattern = f"{TEST_DIR}/dump.rdx.gz" diff --git a/tests/io/lammps/test_utils.py b/tests/io/lammps/test_utils.py index 4a116c021a6..f3c7551b30f 100644 --- a/tests/io/lammps/test_utils.py +++ b/tests/io/lammps/test_utils.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - from pymatgen.core.structure import Molecule from pymatgen.io.lammps.data import Topology from pymatgen.io.lammps.utils import Polymer @@ -10,9 +8,9 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/lammps" -class TestPolymer(TestCase): +class TestPolymer: @classmethod - def setUpClass(cls): + def setup_class(cls): # head molecule cls.peo_head = Molecule.from_file(f"{TEST_DIR}/peo_head.xyz") charges = [-0.1187, 0.0861, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861, 0.0861] @@ -82,9 +80,9 @@ def test_polymer_chain_topologies(self): assert topology_linear.topologies["Dihedrals"] != topology_random.topologies["Dihedrals"] -class TestPackmolOutput(TestCase): +class TestPackmolOutput: @classmethod - def setUpClass(cls): + def setup_class(cls): ethanol_coords = [ [0.00720, -0.56870, 0.00000], [-1.28540, 0.24990, 0.00000], diff --git a/tests/io/lobster/test_inputs.py b/tests/io/lobster/test_inputs.py index 8df13ae58a8..fd2cd76b17f 100644 --- a/tests/io/lobster/test_inputs.py +++ b/tests/io/lobster/test_inputs.py @@ -8,7 +8,7 @@ from pymatgen.io.lobster import Lobsterin from pymatgen.io.lobster.inputs import get_all_possible_basis_combinations from pymatgen.io.vasp.inputs import Incar, Kpoints, Potcar -from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/cohp" @@ -19,8 +19,8 @@ __date__ = "Dec 10, 2017" -class TestLobsterin(PymatgenTest): - def setUp(self): +class TestLobsterin(MatSciTest): + def setup_method(self): self.Lobsterin = Lobsterin.from_file(f"{TEST_DIR}/lobsterin.1") self.Lobsterin2 = Lobsterin.from_file(f"{TEST_DIR}/lobsterin.2") self.Lobsterin3 = Lobsterin.from_file(f"{TEST_DIR}/lobsterin.3") @@ -579,7 +579,7 @@ def test_as_from_dict(self): new_lobsterin.to_json() -class TestUtils(PymatgenTest): +class TestUtils(MatSciTest): def test_get_all_possible_basis_combinations(self): # this basis is just for testing (not correct) min_basis = ["Li 1s 2s ", "Na 1s 2s", "Si 1s 2s"] diff --git a/tests/io/lobster/test_lobsterenv.py b/tests/io/lobster/test_lobsterenv.py index 4f9cc9959b8..a18b788c926 100644 --- a/tests/io/lobster/test_lobsterenv.py +++ b/tests/io/lobster/test_lobsterenv.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest from pytest import approx @@ -24,8 +22,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/cohp/environments" -class TestLobsterNeighbors(TestCase): - def setUp(self): +class TestLobsterNeighbors: + def setup_method(self): # test additional conditions first # only consider cation anion bonds diff --git a/tests/io/lobster/test_outputs.py b/tests/io/lobster/test_outputs.py index 2fb647e5d88..dca2652266a 100644 --- a/tests/io/lobster/test_outputs.py +++ b/tests/io/lobster/test_outputs.py @@ -3,7 +3,6 @@ import copy import json import os -from unittest import TestCase import numpy as np import pytest @@ -31,7 +30,7 @@ Wavefunction, ) from pymatgen.io.vasp import Vasprun -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/cohp" @@ -42,8 +41,8 @@ __date__ = "Dec 10, 2017" -class TestBwdf(PymatgenTest): - def setUp(self): +class TestBwdf(MatSciTest): + def setup_method(self): self.bwdf_coop = Bwdf(filename=f"{TEST_DIR}/BWDF.lobster.AlN.gz") self.bwdf_cohp = Bwdf(filename=f"{TEST_DIR}/BWDFCOHP.lobster.NaCl.gz") @@ -57,8 +56,8 @@ def test_attributes(self): assert self.bwdf_cohp.bwdf[Spin.up][103] == approx(-0.01392, abs=1e-4) -class TestCohpcar(PymatgenTest): - def setUp(self): +class TestCohpcar(MatSciTest): + def setup_method(self): self.cohp_bise = Cohpcar(filename=f"{TEST_DIR}/COHPCAR.lobster.BiSe.gz") self.coop_bise = Cohpcar( filename=f"{TEST_DIR}/COOPCAR.lobster.BiSe.gz", @@ -398,8 +397,8 @@ def test_orbital_resolved_cohp(self): assert len(self.cobi6.orb_res_cohp["21"]["2py-1s-2s"]["COHP"][Spin.down]) == 12 -class TestDoscar(TestCase): - def setUp(self): +class TestDoscar: + def setup_method(self): # first for spin polarized version doscar = f"{VASP_OUT_DIR}/DOSCAR.lobster.spin" poscar = f"{VASP_IN_DIR}/POSCAR.lobster.spin_DOS" @@ -637,8 +636,8 @@ def test_is_spin_polarized(self): assert not self.DOSCAR_nonspin_pol.is_spin_polarized -class TestCharge(PymatgenTest): - def setUp(self): +class TestCharge(MatSciTest): + def setup_method(self): self.charge2 = Charge(filename=f"{TEST_DIR}/CHARGE.lobster.MnO") # gzipped file self.charge = Charge(filename=f"{TEST_DIR}/CHARGE.lobster.MnO2.gz") @@ -716,8 +715,8 @@ def test_msonable(self): assert getattr(charge_from_dict, attr_name) == attr_value -class TestLobsterout(PymatgenTest): - def setUp(self): +class TestLobsterout(MatSciTest): + def setup_method(self): self.lobsterout_normal = Lobsterout(filename=f"{TEST_DIR}/lobsterout.normal") # make sure .gz files are also read correctly self.lobsterout_normal = Lobsterout(filename=f"{TEST_DIR}/lobsterout.normal2.gz") @@ -1245,8 +1244,8 @@ def test_msonable(self): Lobsterout(filename=None, invalid="val") -class TestFatband(PymatgenTest): - def setUp(self): +class TestFatband(MatSciTest): + def setup_method(self): self.structure = Vasprun( filename=f"{TEST_DIR}/Fatband_SiO2/Test_p_x/vasprun.xml", ionic_step_skip=None, @@ -1480,8 +1479,8 @@ def test_get_bandstructure(self): assert bs_p_x.get_projection_on_elements()[Spin.up][0][0]["Si"] == approx(3 * (0.001 + 0.064), abs=1e-2) -class TestBandoverlaps(TestCase): - def setUp(self): +class TestBandoverlaps: + def setup_method(self): # test spin-polarized calc and non spin-polarized calc self.band_overlaps1 = Bandoverlaps(f"{TEST_DIR}/bandOverlaps.lobster.1") @@ -1716,8 +1715,8 @@ def test_keys(self): assert len(bo_dict_new[Spin.down]["matrices"]) == 73 -class TestGrosspop(TestCase): - def setUp(self): +class TestGrosspop: + def setup_method(self): self.grosspop1 = Grosspop(f"{TEST_DIR}/GROSSPOP.lobster") self.grosspop_511_sp = Grosspop(f"{TEST_DIR}/GROSSPOP_511_sp.lobster.AlN.gz") self.grosspop_511_nsp = Grosspop(f"{TEST_DIR}/GROSSPOP_511_nsp.lobster.NaCl.gz") @@ -1866,8 +1865,8 @@ def test_msonable(self): assert getattr(grosspop_from_dict, attr_name) == attr_value -class TestIcohplist(TestCase): - def setUp(self): +class TestIcohplist: + def setup_method(self): self.icohp_bise = Icohplist(filename=f"{TEST_DIR}/ICOHPLIST.lobster.BiSe") self.icoop_bise = Icohplist( filename=f"{TEST_DIR}/ICOOPLIST.lobster.BiSe", @@ -2171,8 +2170,8 @@ def test_msonable(self): assert getattr(icohplist_from_dict, attr_name) == attr_value -class TestNciCobiList(TestCase): - def setUp(self): +class TestNciCobiList: + def setup_method(self): self.ncicobi = NciCobiList(filename=f"{TEST_DIR}/NcICOBILIST.lobster") self.ncicobi_gz = NciCobiList(filename=f"{TEST_DIR}/NcICOBILIST.lobster.gz") self.ncicobi_no_spin = NciCobiList(filename=f"{TEST_DIR}/NcICOBILIST.lobster.nospin") @@ -2207,7 +2206,7 @@ def test_ncicobilist(self): ) -class TestWavefunction(PymatgenTest): +class TestWavefunction(MatSciTest): def test_parse_file(self): grid, points, real, imaginary, distance = Wavefunction._parse_file( f"{TEST_DIR}/LCAOWaveFunctionAfterLSO1PlotOfSpin1Kpoint1band1.gz" @@ -2275,8 +2274,8 @@ def test_write_file(self): assert os.path.isfile(density_wavecar_path) -class TestSitePotentials(PymatgenTest): - def setUp(self) -> None: +class TestSitePotentials(MatSciTest): + def setup_method(self) -> None: self.sitepotential = SitePotential(filename=f"{TEST_DIR}/SitePotentials.lobster.perovskite") def test_attributes(self): @@ -2326,8 +2325,8 @@ def test_msonable(self): assert getattr(sitepotential_from_dict, attr_name) == attr_value -class TestMadelungEnergies(PymatgenTest): - def setUp(self) -> None: +class TestMadelungEnergies(MatSciTest): + def setup_method(self) -> None: self.madelungenergies = MadelungEnergies(filename=f"{TEST_DIR}/MadelungEnergies.lobster.perovskite") def test_attributes(self): @@ -2343,8 +2342,8 @@ def test_msonable(self): assert getattr(madelung_from_dict, attr_name) == attr_value -class TestLobsterMatrices(PymatgenTest): - def setUp(self) -> None: +class TestLobsterMatrices(MatSciTest): + def setup_method(self) -> None: self.hamilton_matrices = LobsterMatrices( filename=f"{TEST_DIR}/Na_hamiltonMatrices.lobster.gz", e_fermi=-2.79650354 ) @@ -2493,8 +2492,8 @@ def test_raises(self): self.hamilton_matrices = LobsterMatrices(filename=f"{TEST_DIR}/hamiltonMatrices.lobster") -class TestPolarization(PymatgenTest): - def setUp(self) -> None: +class TestPolarization(MatSciTest): + def setup_method(self) -> None: self.polarization = Polarization(filename=f"{TEST_DIR}/POLARIZATION.lobster.AlN.gz") def test_attributes(self): diff --git a/tests/io/pwmat/test_inputs.py b/tests/io/pwmat/test_inputs.py index e1438482623..b64bd2b2908 100644 --- a/tests/io/pwmat/test_inputs.py +++ b/tests/io/pwmat/test_inputs.py @@ -1,7 +1,7 @@ from __future__ import annotations import importlib -from unittest import mock +from unittest.mock import patch import pytest from monty.io import zopen @@ -18,7 +18,7 @@ LineLocator, ListLocator, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/pwmat" @@ -43,7 +43,7 @@ def test_list_locator(exclusion: str, expected_idx: int): assert aim_idx == expected_idx -class TestACstrExtractor(PymatgenTest): +class TestACstrExtractor(MatSciTest): def test_extract(self): filepath = f"{TEST_DIR}/atom.config" ac_extractor = ACExtractor(file_path=filepath) @@ -60,7 +60,7 @@ def test_extract(self): assert ac_extractor.magmoms[idx] == ac_str_extractor.get_magmoms()[idx] -class TestAtomConfig(PymatgenTest): +class TestAtomConfig(MatSciTest): def test_init(self): filepath = f"{TEST_DIR}/atom.config" structure = Structure.from_file(filepath) @@ -82,7 +82,7 @@ def test_write_file(self): assert_allclose(atom_config.structure.lattice.abc, tmp_atom_config.structure.lattice.abc, 5) -class TestGenKpt(PymatgenTest): +class TestGenKpt(MatSciTest): def test_from_structure(self): pytest.importorskip("seekpath") filepath = f"{TEST_DIR}/atom.config" @@ -107,7 +107,7 @@ def test_write_file(self): assert gen_kpt.get_str() == tmp_gen_kpt_str -class TestHighSymmetryPoint(PymatgenTest): +class TestHighSymmetryPoint(MatSciTest): def test_from_structure(self): pytest.importorskip("seekpath") filepath = f"{TEST_DIR}/atom.config" @@ -136,7 +136,7 @@ def test_write_file(self): def test_err_msg_on_seekpath_not_installed(): """Simulate and test error message when seekpath is not installed.""" - with mock.patch.dict("sys.modules", {"seekpath": None}): + with patch.dict("sys.modules", {"seekpath": None}): # As the import error is raised during init of KPathSeek, # have to import it as well (order matters) importlib.reload(pymatgen.symmetry.kpath) diff --git a/tests/io/pwmat/test_outputs.py b/tests/io/pwmat/test_outputs.py index b2a97f891fe..597fee5f657 100644 --- a/tests/io/pwmat/test_outputs.py +++ b/tests/io/pwmat/test_outputs.py @@ -1,12 +1,12 @@ from __future__ import annotations from pymatgen.io.pwmat.outputs import DosSpin, Movement, OutFermi, Report -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/pwmat" -class TestMovement(PymatgenTest): +class TestMovement(MatSciTest): def test_init_and_properties(self): filepath = f"{TEST_DIR}/MOVEMENT.lzma" movement = Movement(filepath) @@ -26,14 +26,14 @@ def test_init_and_properties(self): assert movement.ionic_steps[0]["e_tot"] == -357677.2281 -class TestOutFermi(PymatgenTest): +class TestOutFermi(MatSciTest): def test_init_and_properties(self): filepath = f"{TEST_DIR}/OUT.FERMI.lzma" out_fermi = OutFermi(filepath) assert out_fermi.e_fermi == -2.359 -class TestReport(PymatgenTest): +class TestReport(MatSciTest): def test_init_and_properties(self): filepath = f"{TEST_DIR}/REPORT" report = Report(filepath) @@ -46,7 +46,7 @@ def test_init_and_properties(self): assert report.hsps == {} -class TestDosSpin(PymatgenTest): +class TestDosSpin(MatSciTest): def test_init_and_properties(self): filepath = f"{TEST_DIR}/DOS.spinup_projected" dos_spin = DosSpin(filepath) diff --git a/tests/io/qchem/test_inputs.py b/tests/io/qchem/test_inputs.py index 5e6a2eb7d84..92b7a9d1eff 100644 --- a/tests/io/qchem/test_inputs.py +++ b/tests/io/qchem/test_inputs.py @@ -8,7 +8,7 @@ from pymatgen.core.structure import Molecule from pymatgen.io.qchem.inputs import QCInput from pymatgen.io.qchem.sets import OptSet -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/qchem" @@ -20,7 +20,7 @@ __credits__ = "Xiaohui Qu" -class TestQCInput(PymatgenTest): +class TestQCInput(MatSciTest): def test_molecule_template(self): species = ["C", "O"] coords = [ diff --git a/tests/io/qchem/test_outputs.py b/tests/io/qchem/test_outputs.py index 22f681f8918..f81d374f2af 100644 --- a/tests/io/qchem/test_outputs.py +++ b/tests/io/qchem/test_outputs.py @@ -17,7 +17,7 @@ hessian_parser, orbital_coeffs_parser, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from openbabel import openbabel @@ -260,7 +260,7 @@ } -class TestQCOutput(PymatgenTest): +class TestQCOutput(MatSciTest): @staticmethod def generate_single_job_dict(): """Used to generate test dictionary for single jobs.""" diff --git a/tests/io/qchem/test_sets.py b/tests/io/qchem/test_sets.py index f870c47c351..c37ffee17e0 100644 --- a/tests/io/qchem/test_sets.py +++ b/tests/io/qchem/test_sets.py @@ -14,7 +14,7 @@ SinglePointSet, TransitionStateSet, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Samuel Blau, Brandon Wood, Shyam Dwaraknath, Evan Spotte-Smith, Ryan Kingsbury" __copyright__ = "Copyright 2018-2022, The Materials Project" @@ -26,7 +26,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/qchem/new_qchem_files" -class TestQChemDictSet(PymatgenTest): +class TestQChemDictSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_dict_set = QChemDictSet( @@ -469,7 +469,7 @@ def test_solvation_warnings(self): ) -class TestSinglePointSet(PymatgenTest): +class TestSinglePointSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_sp_set = SinglePointSet(molecule=test_molecule) @@ -671,7 +671,7 @@ def test_plots_init(self): assert test_sp_set.molecule == test_molecule -class TestOptSet(PymatgenTest): +class TestOptSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_opt_set = OptSet(molecule=test_molecule) @@ -846,7 +846,7 @@ def test_v5_vs_v6(self): assert v6_opt_set_modified.geom_opt == ref_dict -class TestTransitionStateSet(PymatgenTest): +class TestTransitionStateSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_ts_set = TransitionStateSet(molecule=test_molecule) @@ -927,7 +927,7 @@ def test_smd_init(self): assert test_ts_set.molecule == test_molecule -class TestForceSet(PymatgenTest): +class TestForceSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_forceset = ForceSet(molecule=test_molecule) @@ -1004,7 +1004,7 @@ def test_smd_init(self): assert test_forceset.molecule == test_molecule -class TestPESScanSet(PymatgenTest): +class TestPESScanSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pes_scan.qin").molecule @@ -1097,7 +1097,7 @@ def test_smd_init(self): assert test_pes_scan.molecule == test_molecule -class TestFreqSet(PymatgenTest): +class TestFreqSet(MatSciTest): def test_init(self): test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule test_freq_set = FreqSet(molecule=test_molecule) diff --git a/tests/io/qchem/test_utils.py b/tests/io/qchem/test_utils.py index 4ad091b8242..feb65c1158e 100644 --- a/tests/io/qchem/test_utils.py +++ b/tests/io/qchem/test_utils.py @@ -6,7 +6,7 @@ from monty.io import zopen from pymatgen.io.qchem.utils import lower_and_check_unique, process_parsed_hess -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Ryan Kingsbury, Samuel Blau" __copyright__ = "Copyright 2018-2022, The Materials Project" @@ -15,7 +15,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/qchem/new_qchem_files" -class TestUtil(PymatgenTest): +class TestUtil(MatSciTest): """test utils.""" def test_lower_and_check_unique(self): diff --git a/tests/io/test_adf.py b/tests/io/test_adf.py index 364e73582c7..f7019a86028 100644 --- a/tests/io/test_adf.py +++ b/tests/io/test_adf.py @@ -4,7 +4,7 @@ from pymatgen.core.structure import Molecule from pymatgen.io.adf import AdfInput, AdfKey, AdfOutput, AdfTask -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Xin Chen, chenxin13@mails.tsinghua.edu.cn" @@ -242,7 +242,7 @@ def test_serialization(self): } -class TestAdfInput(PymatgenTest): +class TestAdfInput(MatSciTest): def test_main(self): tmp_file = f"{self.tmp_path}/adf.temp" mol = Molecule.from_str(rhb18_xyz, "xyz") diff --git a/tests/io/test_ase.py b/tests/io/test_ase.py index 4328d0f6959..3a3cba80c4d 100644 --- a/tests/io/test_ase.py +++ b/tests/io/test_ase.py @@ -2,7 +2,7 @@ import importlib from importlib.metadata import PackageNotFoundError -from unittest import mock +from unittest.mock import patch import numpy as np import pytest @@ -370,7 +370,7 @@ def test_msonable_atoms(): def test_no_ase_err(): import pymatgen.io.ase - with mock.patch.dict("sys.modules", {"ase.atoms": None}): + with patch.dict("sys.modules", {"ase.atoms": None}): importlib.reload(pymatgen.io.ase) from pymatgen.io.ase import MSONAtoms diff --git a/tests/io/test_atat.py b/tests/io/test_atat.py index a9562f92511..32758929837 100644 --- a/tests/io/test_atat.py +++ b/tests/io/test_atat.py @@ -5,12 +5,12 @@ from pymatgen.core.structure import Structure from pymatgen.io.atat import Mcsqs -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/atat/mcsqs" -class TestAtat(PymatgenTest): +class TestAtat(MatSciTest): def test_mcsqs_import(self): test_str = """1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 diff --git a/tests/io/test_babel.py b/tests/io/test_babel.py index 6a130dd8914..803634de0a5 100644 --- a/tests/io/test_babel.py +++ b/tests/io/test_babel.py @@ -2,7 +2,6 @@ import copy import platform -from unittest import TestCase import pytest from pytest import approx @@ -17,8 +16,8 @@ pybel = pytest.importorskip("openbabel.pybel") -class TestBabelMolAdaptor(TestCase): - def setUp(self): +class TestBabelMolAdaptor: + def setup_method(self): coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], diff --git a/tests/io/test_cif.py b/tests/io/test_cif.py index 0615509d359..591feb91a3a 100644 --- a/tests/io/test_cif.py +++ b/tests/io/test_cif.py @@ -9,7 +9,7 @@ from pymatgen.electronic_structure.core import Magmom from pymatgen.io.cif import CifBlock, CifParser, CifWriter from pymatgen.symmetry.structure import SymmetrizedStructure -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, MatSciTest try: import pybtex @@ -20,7 +20,7 @@ MCIF_TEST_DIR = f"{TEST_FILES_DIR}/io/cif/mcif" -class TestCifBlock(PymatgenTest): +class TestCifBlock(MatSciTest): def test_to_str(self): with open(f"{TEST_FILES_DIR}/cif/Graphite.cif", encoding="utf-8") as file: cif_str = file.read() @@ -164,7 +164,7 @@ def test_long_loop(self): assert str(CifBlock(data, loops, "test")) == cif_str -class TestCifIO(PymatgenTest): +class TestCifIO(MatSciTest): def test_cif_parser(self): parser = CifParser(f"{TEST_FILES_DIR}/cif/LiFePO4.cif") for struct in parser.parse_structures(): @@ -999,8 +999,8 @@ def test_cif_writer_site_properties(self): assert "O O23 1 0.95662769 0.25000000 0.29286233 1 -1.0" in cif_str -class TestMagCif(PymatgenTest): - def setUp(self): +class TestMagCif(MatSciTest): + def setup_method(self): self.mcif = CifParser(f"{MCIF_TEST_DIR}/magnetic.example.NiO.mcif") self.mcif_ncl = CifParser(f"{MCIF_TEST_DIR}/magnetic.ncl.example.GdB4.mcif") self.mcif_incommensurate = CifParser(f"{MCIF_TEST_DIR}/magnetic.incommensurate.example.Cr.mcif") diff --git a/tests/io/test_core.py b/tests/io/test_core.py index a1a62e95eb5..debeada9d58 100644 --- a/tests/io/test_core.py +++ b/tests/io/test_core.py @@ -10,7 +10,7 @@ from pymatgen.core.structure import Structure from pymatgen.io.cif import CifParser, CifWriter from pymatgen.io.core import InputFile, InputSet -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest if TYPE_CHECKING: from typing_extensions import Self @@ -44,7 +44,7 @@ def __str__(self): return f"{self.a}\n{self.b}" -class TestInputFile(PymatgenTest): +class TestInputFile(MatSciTest): def test_file_io(self): with pytest.raises(FileNotFoundError, match="No such file or directory: 'fakepath.cif'"): StructInputFile.from_file("fakepath.cif") @@ -64,9 +64,9 @@ def test_msonable(self): assert sif.structure == temp_sif.structure -class TestInputSet(PymatgenTest): +class TestInputSet(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.sif1 = StructInputFile.from_file(f"{TEST_FILES_DIR}/cif/Li.cif") cls.sif2 = StructInputFile.from_file(f"{TEST_FILES_DIR}/cif/LiFePO4.cif") cls.sif3 = StructInputFile.from_file(f"{TEST_FILES_DIR}/cif/Li2O.cif") diff --git a/tests/io/test_cssr.py b/tests/io/test_cssr.py index 467be18ae3e..84b67c3e58e 100644 --- a/tests/io/test_cssr.py +++ b/tests/io/test_cssr.py @@ -2,8 +2,6 @@ from __future__ import annotations -from unittest import TestCase - from pymatgen.core.structure import Structure from pymatgen.io.cssr import Cssr from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR @@ -18,8 +16,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/cssr" -class TestCssr(TestCase): - def setUp(self): +class TestCssr: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.cssr = Cssr(Structure.from_file(filepath)) diff --git a/tests/io/test_fiesta.py b/tests/io/test_fiesta.py index bcc6904a076..00b7f0acf0d 100644 --- a/tests/io/test_fiesta.py +++ b/tests/io/test_fiesta.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - from pymatgen.core.structure import Molecule from pymatgen.io.fiesta import FiestaInput, FiestaOutput from pymatgen.util.testing import TEST_FILES_DIR @@ -9,8 +7,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/fiesta" -class TestFiestaInput(TestCase): - def setUp(self): +class TestFiestaInput: + def setup_method(self): coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], @@ -71,8 +69,8 @@ def test_str_and_from_str(self): assert cell_in.cohsex_options["eigMethod"] == "C" -class TestFiestaOutput(TestCase): - def setUp(self): +class TestFiestaOutput: + def setup_method(self): self.log_fiesta = FiestaOutput(f"{TEST_DIR}/log_fiesta") def test_props(self): diff --git a/tests/io/test_gaussian.py b/tests/io/test_gaussian.py index 82c4d3f9284..d396d7c2aa4 100644 --- a/tests/io/test_gaussian.py +++ b/tests/io/test_gaussian.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pytest from pytest import approx @@ -13,8 +11,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/gaussian" -class TestGaussianInput(TestCase): - def setUp(self): +class TestGaussianInput: + def setup_method(self): coords = [ [0, 0, 0], [0, 0, 1.089], @@ -278,10 +276,10 @@ def test_no_molecule_func_bset_charge_mult(self): assert input_str == gau_str -class TestGaussianOutput(TestCase): +class TestGaussianOutput: # TODO: Add unittest for PCM type output. - def setUp(self): + def setup_method(self): self.gau_out = GaussianOutput(f"{TEST_DIR}/methane.log") def test_resume(self): diff --git a/tests/io/test_lmto.py b/tests/io/test_lmto.py index 1ddc8c2abcf..b38d31a3781 100644 --- a/tests/io/test_lmto.py +++ b/tests/io/test_lmto.py @@ -10,7 +10,7 @@ from pymatgen.electronic_structure.core import Spin from pymatgen.io.lmto import LMTOCopl, LMTOCtrl from pymatgen.util.num import round_to_sigfigs -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Marco Esters" __copyright__ = "Copyright 2017, The Materials Project" @@ -23,20 +23,16 @@ MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) -class TestCtrl(PymatgenTest): - def setUp(self): - os.chdir(TEST_DIR) - self.ref_bise = LMTOCtrl.from_file(filename="CTRL.BiSe") - self.ref_fe = LMTOCtrl.from_file() - - def tearDown(self): - os.chdir(MODULE_DIR) +class TestCtrl(MatSciTest): + def setup_method(self): + self.ref_bise = LMTOCtrl.from_file(filename=f"{TEST_DIR}/CTRL.BiSe") + self.ref_fe = LMTOCtrl.from_file(filename=f"{TEST_DIR}/CTRL") def test_dict(self): assert self.ref_bise == LMTOCtrl.from_dict(self.ref_bise.as_dict()) def test_structure(self): - bise_poscar = Structure.from_file("POSCAR.BiSe") + bise_poscar = Structure.from_file(f"{TEST_DIR}/POSCAR.BiSe") assert bise_poscar.matches(self.ref_bise.structure) assert self.ref_bise == LMTOCtrl(self.ref_bise.structure, header="Bi6Se6, hexagonal") @@ -47,15 +43,11 @@ def test_read_write(self): assert self.ref_bise.structure.matches(ctrl_file.structure) -class TestCopl(PymatgenTest): - def setUp(self): - os.chdir(TEST_DIR) - self.copl_bise = LMTOCopl("COPL.BiSe") - self.copl_bise_eV = LMTOCopl(filename="COPL.BiSe", to_eV=True) - self.copl_fe = LMTOCopl() - - def tearDown(self): - os.chdir(MODULE_DIR) +class TestCopl(MatSciTest): + def setup_method(self): + self.copl_bise = LMTOCopl(f"{TEST_DIR}/COPL.BiSe") + self.copl_bise_eV = LMTOCopl(filename=f"{TEST_DIR}/COPL.BiSe", to_eV=True) + self.copl_fe = LMTOCopl(f"{TEST_DIR}/COPL") def test_attributes(self): assert not self.copl_bise.is_spin_polarized diff --git a/tests/io/test_nwchem.py b/tests/io/test_nwchem.py index 7304ec4a10e..cf08d9d96f2 100644 --- a/tests/io/test_nwchem.py +++ b/tests/io/test_nwchem.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase import pytest from pytest import approx @@ -22,8 +21,8 @@ mol = Molecule(["C", "H", "H", "H", "H"], coords) -class TestNwTask(TestCase): - def setUp(self): +class TestNwTask: + def setup_method(self): self.task = NwTask( 0, 1, @@ -136,8 +135,8 @@ def test_esp_task(self): assert str(task) == answer -class TestNwInput(TestCase): - def setUp(self): +class TestNwInput: + def setup_method(self): tasks = [ NwTask.dft_task(mol, operation="optimize", xc="b3lyp", basis_set="6-31++G*"), NwTask.dft_task(mol, operation="freq", xc="b3lyp", basis_set="6-31++G*"), diff --git a/tests/io/test_packmol.py b/tests/io/test_packmol.py index 19f33be1655..b32cb605db4 100644 --- a/tests/io/test_packmol.py +++ b/tests/io/test_packmol.py @@ -10,7 +10,7 @@ from pymatgen.analysis.molecule_matcher import MoleculeMatcher from pymatgen.core import Molecule from pymatgen.io.packmol import PackmolBoxGen -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/packmol" # error message is different in CI for unknown reasons (as of 2024-04-12) @@ -48,7 +48,7 @@ water = Molecule(water_atoms, water_coords) -class TestPackmolSet(PymatgenTest): +class TestPackmolSet(MatSciTest): def test_packmol_with_molecule(self): """Test coords input as Molecule.""" pw = PackmolBoxGen().get_input_set( @@ -91,7 +91,7 @@ def test_packmol_with_path(self): {"name": "LiTFSi", "number": 20, "coords": p2}, ], ) - # PymatgenTest makes each test change to a temporary directory + # MatSciTest makes each test change to a temporary directory # Check here we can run in the current directory pw.write_input(".") pw.run(".") @@ -99,7 +99,7 @@ def test_packmol_with_path(self): assert os.path.isfile(f"{self.tmp_path}/packmol.stdout") out = Molecule.from_file(f"{self.tmp_path}/packmol_out.xyz") assert out.composition.num_atoms == 10 * 15 + 20 * 16 - # PymatgenTest makes each test change to a temporary directory + # MatSciTest makes each test change to a temporary directory # Check here we can run in a relative directory pw.write_input("somedir") pw.run("somedir") diff --git a/tests/io/test_phonopy.py b/tests/io/test_phonopy.py index 14848c11bbb..cf6984f0ed4 100644 --- a/tests/io/test_phonopy.py +++ b/tests/io/test_phonopy.py @@ -2,7 +2,6 @@ import os from pathlib import Path -from unittest import TestCase import numpy as np import pytest @@ -27,7 +26,7 @@ get_pmg_structure, get_thermal_displacement_matrices, ) -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from phonopy import Phonopy @@ -40,7 +39,7 @@ PHONON_DIR = f"{TEST_FILES_DIR}/phonon" -class TestPhonopyParser(PymatgenTest): +class TestPhonopyParser(MatSciTest): def test_get_ph_bs(self): ph_bs = get_ph_bs_symm_line(f"{TEST_DIR}/NaCl_band.yaml", has_nac=True) @@ -96,9 +95,9 @@ def test_get_complete_dos(self): @pytest.mark.skipif(Phonopy is None, reason="Phonopy not present") -class TestStructureConversion(PymatgenTest): +class TestStructureConversion(MatSciTest): def test_structure_conversion(self): - struct_pmg = PymatgenTest.get_structure("LiFePO4") + struct_pmg = MatSciTest.get_structure("LiFePO4") # add magmoms to site_properties struct_pmg.add_site_property("magmom", magmoms := [1] * len(struct_pmg)) struct_ph = get_phonopy_structure(struct_pmg) @@ -124,7 +123,7 @@ def test_structure_conversion(self): @pytest.mark.skipif(Phonopy is None, reason="Phonopy not present") -class TestGetDisplacedStructures(PymatgenTest): +class TestGetDisplacedStructures(MatSciTest): def test_get_displaced_structures(self): pmg_s = Structure.from_file(f"{TEST_DIR}/POSCAR-unitcell", primitive=False) supercell_matrix = np.diag((2, 1, 2)) @@ -156,8 +155,8 @@ def test_get_displaced_structures(self): @pytest.mark.skipif(Phonopy is None, reason="Phonopy not present") -class TestPhonopyFromForceConstants(TestCase): - def setUp(self) -> None: +class TestPhonopyFromForceConstants: + def setup_method(self) -> None: test_path = Path(TEST_DIR) structure_file = test_path / "POSCAR-NaCl" fc_file = test_path / "FORCE_CONSTANTS" @@ -240,7 +239,7 @@ def test_gruneisen_parameter(self): @pytest.mark.skipif(Phonopy is None, reason="Phonopy not present") -class TestThermalDisplacementMatrices(PymatgenTest): +class TestThermalDisplacementMatrices(MatSciTest): def test_get_thermal_displacement_matrix(self): list_matrices = get_thermal_displacement_matrices( f"{PHONON_DIR}/thermal_displacement_matrices/thermal_displacement_matrices.yaml", diff --git a/tests/io/test_pwscf.py b/tests/io/test_pwscf.py index 6e39c8b4019..c082e9801c0 100644 --- a/tests/io/test_pwscf.py +++ b/tests/io/test_pwscf.py @@ -6,12 +6,12 @@ from pytest import approx from pymatgen.io.pwscf import PWInput, PWInputError, PWOutput -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/pwscf" -class TestPWInput(PymatgenTest): +class TestPWInput(MatSciTest): def test_init(self): struct = self.get_structure("Li2O") with pytest.raises(PWInputError, match="Missing O2- in pseudo specification"): @@ -542,8 +542,8 @@ def test_custom_decimal_precision_write_and_read_str(self): assert pw_str.strip() == str(PWInput.from_str(pw_str)).strip() -class TestPWOutput(PymatgenTest): - def setUp(self): +class TestPWOutput(MatSciTest): + def setup_method(self): self.pw_out = PWOutput(f"{TEST_DIR}/Si.pwscf.out") def test_properties(self): diff --git a/tests/io/test_shengbte.py b/tests/io/test_shengbte.py index a9cd194753b..ee416bf2921 100644 --- a/tests/io/test_shengbte.py +++ b/tests/io/test_shengbte.py @@ -4,14 +4,14 @@ from numpy.testing import assert_array_equal from pymatgen.io.shengbte import Control -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest f90nml = pytest.importorskip("f90nml") TEST_DIR = f"{TEST_FILES_DIR}/io/shengbte" -class TestShengBTE(PymatgenTest): - def setUp(self): +class TestShengBTE(MatSciTest): + def setup_method(self): self.filename = f"{TEST_DIR}/CONTROL-CSLD_Si" self.test_dict = { "nelements": 1, diff --git a/tests/io/test_template_input.py b/tests/io/test_template_input.py index 72354c8f87f..6bb8c916845 100644 --- a/tests/io/test_template_input.py +++ b/tests/io/test_template_input.py @@ -5,12 +5,12 @@ import pytest from pymatgen.io.template import TemplateInputGen -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io" -class TestTemplateInputGen(PymatgenTest): +class TestTemplateInputGen(MatSciTest): def test_write_inputs(self): input_set = TemplateInputGen().get_input_set( template=f"{TEST_DIR}/template_input_file.txt", diff --git a/tests/io/test_wannier90.py b/tests/io/test_wannier90.py index 93ac0e256e7..df084c6ee3f 100644 --- a/tests/io/test_wannier90.py +++ b/tests/io/test_wannier90.py @@ -8,13 +8,13 @@ from pytest import approx from pymatgen.io.wannier90 import Unk -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/wannier90" -class TestUnk(PymatgenTest): - def setUp(self): +class TestUnk(MatSciTest): + def setup_method(self): rng = np.random.default_rng() self.data_std = rng.random((10, 5, 5, 5)) self.unk_std = Unk(1, self.data_std) diff --git a/tests/io/test_xcrysden.py b/tests/io/test_xcrysden.py index 3a13a2cf7b5..59f57a56a1b 100644 --- a/tests/io/test_xcrysden.py +++ b/tests/io/test_xcrysden.py @@ -4,11 +4,11 @@ from pymatgen.core.structure import Structure from pymatgen.io.xcrysden import XSF -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestXSF(PymatgenTest): - def setUp(self): +class TestXSF(MatSciTest): + def setup_method(self): self.coords = [[0, 0, 0], [0.75, 0.5, 0.75]] self.lattice = [ [3.8401979337, 0.00, 0.00], diff --git a/tests/io/test_xr.py b/tests/io/test_xr.py index 05cfa8bfc8e..78068a65d81 100644 --- a/tests/io/test_xr.py +++ b/tests/io/test_xr.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - from pymatgen.core.structure import Structure from pymatgen.io.xr import Xr from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR @@ -14,8 +12,8 @@ __date__ = "June 23, 2016" -class TestXr(TestCase): - def setUp(self): +class TestXr: + def setup_method(self): struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR") self.xr = Xr(struct) diff --git a/tests/io/test_xyz.py b/tests/io/test_xyz.py index ad57feca5af..2e23887708e 100644 --- a/tests/io/test_xyz.py +++ b/tests/io/test_xyz.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import pandas as pd import pytest from pytest import approx @@ -12,8 +10,8 @@ from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR -class TestXYZ(TestCase): - def setUp(self): +class TestXYZ: + def setup_method(self): coords = [ [0, 0, 0], [0, 0, 1.089000], diff --git a/tests/io/test_zeopp.py b/tests/io/test_zeopp.py index 819f13a2ee8..4ea07b5766b 100644 --- a/tests/io/test_zeopp.py +++ b/tests/io/test_zeopp.py @@ -1,8 +1,5 @@ from __future__ import annotations -import unittest -from unittest import TestCase - import pytest from pytest import approx @@ -29,8 +26,8 @@ __date__ = "Aug 2, 2013" -class TestZeoCssr(TestCase): - def setUp(self): +class TestZeoCssr: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.zeo_cssr = ZeoCssr(Structure.from_file(filepath)) @@ -71,8 +68,8 @@ def test_from_file(self): assert isinstance(zeo_cssr.structure, Structure) -class TestZeoCssrOxi(TestCase): - def setUp(self): +class TestZeoCssrOxi: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" structure = BVAnalyzer().get_oxi_state_decorated_structure(Structure.from_file(filepath)) self.zeo_cssr = ZeoCssr(structure) @@ -114,8 +111,8 @@ def test_from_file(self): assert isinstance(zeocssr.structure, Structure) -class TestZeoVoronoiXYZ(TestCase): - def setUp(self): +class TestZeoVoronoiXYZ: + def setup_method(self): coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], @@ -144,8 +141,8 @@ def test_from_file(self): assert isinstance(voronoi.molecule, Molecule) -class TestGetVoronoiNodes(TestCase): - def setUp(self): +class TestGetVoronoiNodes: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.structure = Structure.from_file(filepath) bv = BVAnalyzer() @@ -167,9 +164,9 @@ def test_get_voronoi_nodes(self): assert isinstance(vor_face_center_struct, Structure) -@unittest.skip("TODO: file free_sph.cif not present") -class TestGetFreeSphereParams(TestCase): - def setUp(self): +@pytest.mark.skip("TODO: file free_sph.cif not present") +class TestGetFreeSphereParams: + def setup_method(self): filepath = f"{TEST_FILES_DIR}/cif/free_sph.cif" self.structure = Structure.from_file(filepath) self.rad_dict = { @@ -189,8 +186,8 @@ def test_get_free_sphere_params(self): assert free_sph_params["inc_sph_along_free_sph_path_max_dia"] == approx(2.58251, abs=1e-1) -class TestGetHighAccuracyVoronoiNodes(TestCase): - def setUp(self): +class TestGetHighAccuracyVoronoiNodes: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.structure = Structure.from_file(filepath) bv = BVAnalyzer() @@ -208,8 +205,8 @@ def test_get_voronoi_nodes(self): assert isinstance(vor_node_struct, Structure) -class TestGetVoronoiNodesMultiOxi(TestCase): - def setUp(self): +class TestGetVoronoiNodesMultiOxi: + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.structure = Structure.from_file(filepath) bv = BVAnalyzer() diff --git a/tests/io/vasp/test_inputs.py b/tests/io/vasp/test_inputs.py index d1fb9b1b337..dd203fdf64e 100644 --- a/tests/io/vasp/test_inputs.py +++ b/tests/io/vasp/test_inputs.py @@ -7,7 +7,6 @@ import re import warnings from shutil import copyfile -from unittest import TestCase from unittest.mock import patch import numpy as np @@ -38,7 +37,7 @@ VaspInput, _gen_potcar_summary_stats, ) -from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest # Filter some expected warnings warnings.filterwarnings( @@ -72,7 +71,7 @@ def _mock_complete_potcar_summary_stats(monkeypatch: pytest.MonkeyPatch) -> None @pytest.mark.filterwarnings( "ignore:POTCAR data with symbol .* is not known to pymatgen:pymatgen.io.vasp.inputs.UnknownPotcarWarning" ) -class TestPoscar(PymatgenTest): +class TestPoscar(MatSciTest): def test_init(self): comp = Structure.from_file(f"{VASP_IN_DIR}/POSCAR").composition assert comp == Composition("Fe4P4O16") @@ -649,8 +648,8 @@ def test_vasp_6_4_2_format(self): assert poscar.structure.formula == "Li4 Fe4 P4 O16" -class TestIncar(PymatgenTest): - def setUp(self): +class TestIncar(MatSciTest): + def setup_method(self): self.incar = Incar.from_file(f"{VASP_IN_DIR}/INCAR") def test_init(self): @@ -1302,8 +1301,8 @@ def test_non_ascii_comment(self): @pytest.mark.filterwarnings( "ignore:POTCAR data with symbol .* is not known to pymatgen:pymatgen.io.vasp.inputs.UnknownPotcarWarning" ) -class TestPotcarSingle(TestCase): - def setUp(self): +class TestPotcarSingle: + def setup_method(self): self.psingle_Mn_pv = PotcarSingle.from_file(f"{FAKE_POTCAR_DIR}/POT_GGA_PAW_PBE/POTCAR.Mn_pv.gz") self.psingle_Fe = PotcarSingle.from_file(f"{FAKE_POTCAR_DIR}/POT_GGA_PAW_PBE/POTCAR.Fe.gz") self.psingle_Fe_54 = PotcarSingle.from_file(f"{FAKE_POTCAR_DIR}/POT_GGA_PAW_PBE_54/POTCAR.Fe.gz") @@ -1542,8 +1541,8 @@ def test_copy(self): @pytest.mark.filterwarnings( "ignore:POTCAR data with symbol .* is not known to pymatgen:pymatgen.io.vasp.inputs.UnknownPotcarWarning" ) -class TestPotcar(PymatgenTest): - def setUp(self): +class TestPotcar(MatSciTest): + def setup_method(self): SETTINGS.setdefault("PMG_VASP_PSP_DIR", str(TEST_FILES_DIR)) self.filepath = f"{FAKE_POTCAR_DIR}/POTCAR.gz" self.potcar = Potcar.from_file(self.filepath) @@ -1621,8 +1620,8 @@ def test_pickle(self): @pytest.mark.filterwarnings( "ignore:POTCAR data with symbol .* is not known to pymatgen:pymatgen.io.vasp.inputs.UnknownPotcarWarning" ) -class TestVaspInput(PymatgenTest): - def setUp(self): +class TestVaspInput(MatSciTest): + def setup_method(self): filepath = f"{VASP_IN_DIR}/INCAR" incar = Incar.from_file(filepath) filepath = f"{VASP_IN_DIR}/POSCAR" diff --git a/tests/io/vasp/test_optics.py b/tests/io/vasp/test_optics.py index 3a2caf7a94a..8ce09028b40 100644 --- a/tests/io/vasp/test_optics.py +++ b/tests/io/vasp/test_optics.py @@ -7,7 +7,7 @@ from pymatgen.io.vasp.optics import DielectricFunctionCalculator, delta_func, delta_methfessel_paxton, step_func from pymatgen.io.vasp.outputs import Vasprun -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Jimmy-Xuan Shen" __copyright__ = "Copyright 2022, The Materials Project" @@ -16,7 +16,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/io/vasp" -class TestVasprun(PymatgenTest): +class TestVasprun(MatSciTest): def test_optics(self): eps_data_path = f"{TEST_DIR}/fixtures/reproduce_eps" vrun = Vasprun(f"{eps_data_path}/vasprun.xml") diff --git a/tests/io/vasp/test_outputs.py b/tests/io/vasp/test_outputs.py index 0f688cf5ce9..f729d071466 100644 --- a/tests/io/vasp/test_outputs.py +++ b/tests/io/vasp/test_outputs.py @@ -41,7 +41,7 @@ Xdatcar, ) from pymatgen.io.wannier90 import Unk -from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest try: import h5py @@ -53,7 +53,7 @@ kpts_opt_vrun_path = f"{TEST_DIR}/fixtures/kpoints_opt/vasprun.xml.gz" -class TestVasprun(PymatgenTest): +class TestVasprun(MatSciTest): def test_vasprun_soc(self): # Test that SOC vaspruns are parsed appropriately, giving just Spin.Up tdos, idos and pdos vasp_run = Vasprun(f"{VASP_OUT_DIR}/vasprun.int_Te_SOC.xml.gz") @@ -843,7 +843,7 @@ def test_parse_potcar_cwd_relative(self): assert vrun.potcar_spec[ipot]["summary_stats"] == potcar[ipot]._summary_stats -class TestOutcar(PymatgenTest): +class TestOutcar(MatSciTest): def test_init(self): outcar = Outcar(f"{VASP_OUT_DIR}/OUTCAR.gz") expected_mag = ( @@ -1450,7 +1450,7 @@ def test_read_table_pattern(self): ) -class TestBSVasprun(PymatgenTest): +class TestBSVasprun(MatSciTest): def test_get_band_structure(self): filepath = f"{VASP_OUT_DIR}/vasprun_Si_bands.xml.gz" vasprun = BSVasprun(filepath, parse_potcar_file=False) @@ -1504,7 +1504,7 @@ def test_kpoints_opt(self): assert {*vrun_dct["output"]} >= {"eigenvalues", "eigenvalues_kpoints_opt"} -class TestOszicar(PymatgenTest): +class TestOszicar(MatSciTest): def test_init(self): fpath = f"{VASP_OUT_DIR}/OSZICAR" oszicar = Oszicar(fpath) @@ -1520,7 +1520,7 @@ def test_static(self): assert set(oszicar.ionic_steps[-1]) == set({"F", "E0", "dE", "mag"}) -class TestLocpot(PymatgenTest): +class TestLocpot(MatSciTest): def test_init(self): filepath = f"{VASP_OUT_DIR}/LOCPOT.gz" locpot = Locpot.from_file(filepath) @@ -1541,9 +1541,9 @@ def test_vasp_6x_style(self): assert {str(ele) for ele in locpot.structure.composition} == {"Mg", "Si"} -class TestChgcar(PymatgenTest): +class TestChgcar(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): filepath = f"{VASP_OUT_DIR}/CHGCAR.nospin.gz" cls.chgcar_no_spin = Chgcar.from_file(filepath) @@ -1665,7 +1665,7 @@ def test_as_dict_and_from_dict(self): ) -class TestAeccars(PymatgenTest): +class TestAeccars(MatSciTest): # https://github.com/materialsproject/pymatgen/pull/3343 def test_read_write_file(self): aeccar0_test = Chgcar.from_file(f"{TEST_FILES_DIR}/command_line/bader/AECCAR0.gz") @@ -1681,7 +1681,7 @@ def test_read_write_file(self): assert_allclose(aeccar2.data["total"], aeccar2_read.data["total"]) -class TestElfcar(PymatgenTest): +class TestElfcar(MatSciTest): def test_init(self): elfcar = Elfcar.from_file(f"{VASP_OUT_DIR}/ELFCAR.gz") assert approx(np.mean(elfcar.data["total"])) == 0.19076207645194002 @@ -1701,7 +1701,7 @@ def test_interpolation(self): assert len(elfcar.linear_slice([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])) == 100 -class TestProcar(PymatgenTest): +class TestProcar(MatSciTest): def test_init(self): filepath = f"{VASP_OUT_DIR}/PROCAR.simple" procar = Procar(filepath) @@ -1844,8 +1844,8 @@ def test_init(self): # TODO: test get_phonon_frequencies once cross-checked -class TestWavecar(PymatgenTest): - def setUp(self): +class TestWavecar(MatSciTest): + def setup_method(self): latt_mat = np.array(np.eye(3) * 10, dtype=float) # lattice vectors self.vol = np.dot(latt_mat[0, :], np.cross(latt_mat[1, :], latt_mat[2, :])) # unit cell volume # reciprocal lattice vectors @@ -2122,7 +2122,7 @@ def test_write_unks(self): assert unk == unk_ncl -class TestEigenval(PymatgenTest): +class TestEigenval(MatSciTest): def test_init(self): eig = Eigenval(f"{VASP_OUT_DIR}/EIGENVAL.gz") assert eig.ispin == 1 @@ -2162,8 +2162,8 @@ def test_eigenvalue_band_properties_separate_spins(self): assert props[3][1] -class TestWaveder(PymatgenTest): - def setUp(self): +class TestWaveder(MatSciTest): + def setup_method(self): wder = Waveder.from_binary(f"{VASP_OUT_DIR}/WAVEDER", "float64") assert wder.nbands == 36 assert wder.nkpoints == 56 @@ -2195,8 +2195,8 @@ def _check(wder): _check(wderf) -class TestWSWQ(PymatgenTest): - def setUp(self): +class TestWSWQ(MatSciTest): + def setup_method(self): self.wswq = WSWQ.from_file(f"{VASP_OUT_DIR}/WSWQ.gz") def test_consistency(self): diff --git a/tests/io/vasp/test_sets.py b/tests/io/vasp/test_sets.py index f4f6281f1b0..59af8da8b13 100644 --- a/tests/io/vasp/test_sets.py +++ b/tests/io/vasp/test_sets.py @@ -56,7 +56,7 @@ get_valid_magmom_struct, ) from pymatgen.symmetry.analyzer import SpacegroupAnalyzer -from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import FAKE_POTCAR_DIR, TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/io/vasp" @@ -93,7 +93,7 @@ def test_yb_2_warning(input_set: VaspInputSet) -> None: assert expected in str(record[0].message) -class TestSetChangeCheck(PymatgenTest): +class TestSetChangeCheck(MatSciTest): def test_sets_changed(self): msg = ( "WARNING! These tests will fail when you change an input set. They are included " @@ -131,9 +131,9 @@ def test_sets_changed(self): assert hash_str == known_hashes[input_set], f"{input_set=}\n{msg}" -class TestVaspInputSet(PymatgenTest): +class TestVaspInputSet(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): filepath = f"{VASP_IN_DIR}/POSCAR" cls.structure = Structure.from_file(filepath) @@ -168,9 +168,9 @@ def test_as_dict(self): assert dict_set.potcar_functional == dict_set.user_potcar_functional -class TestMITMPRelaxSet(PymatgenTest): +class TestMITMPRelaxSet(MatSciTest): @classmethod - def setUpClass(cls): + def setup_class(cls): cls.set = MITRelaxSet cls.mp_set = MPRelaxSet @@ -721,8 +721,8 @@ def test_get_nedos(self): assert vis._get_nedos(0.1) == pytest.approx(741, abs=1) -class TestMPStaticSet(PymatgenTest): - def setUp(self): +class TestMPStaticSet(MatSciTest): + def setup_method(self): self.set = MPStaticSet def test_init(self): @@ -873,8 +873,8 @@ def test_grid_size_from_struct(self): ) -class TestMatPESStaticSet(PymatgenTest): - def setUp(self): +class TestMatPESStaticSet(MatSciTest): + def setup_method(self): self.struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR") self.prev_incar = Incar.from_file(f"{VASP_IN_DIR}/INCAR") @@ -990,8 +990,8 @@ def test_from_prev_calc(self): assert vis.kpoints is None -class TestMPNonSCFSet(PymatgenTest): - def setUp(self): +class TestMPNonSCFSet(MatSciTest): + def setup_method(self): self.set = MPNonSCFSet @skip_if_no_psp_dir @@ -1156,7 +1156,7 @@ def test_user_kpoint_override(self): assert vis.kpoints.style == Kpoints.supported_modes.Gamma -class TestMagmomLdau(PymatgenTest): +class TestMagmomLdau(MatSciTest): def test_structure_from_prev_run(self): vrun = Vasprun(f"{VASP_OUT_DIR}/vasprun.magmom_ldau.xml.gz") structure = vrun.final_structure @@ -1191,8 +1191,8 @@ def test_ln_magmom(self): assert vis.incar["MAGMOM"] == magmom_ans -class TestMITMDSet(PymatgenTest): - def setUp(self): +class TestMITMDSet(MatSciTest): + def setup_method(self): self.set = MITMDSet filepath = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(filepath) @@ -1233,8 +1233,8 @@ def test_user_heat_speed(self): @skip_if_no_psp_dir -class TestMVLNPTMDSet(PymatgenTest): - def setUp(self): +class TestMVLNPTMDSet(MatSciTest): + def setup_method(self): file_path = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(file_path) self.mvl_npt_set = MVLNPTMDSet(self.struct, start_temp=0, end_temp=300, nsteps=1000) @@ -1269,8 +1269,8 @@ def test_as_from_dict(self): assert input_set.incar["NSW"] == 1000 -class TestMPMDSet(PymatgenTest): - def setUp(self): +class TestMPMDSet(MatSciTest): + def setup_method(self): filepath = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(filepath) self.struct_with_H = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_hcp") @@ -1311,8 +1311,8 @@ def test_as_from_dict(self): assert v.incar["NSW"] == 1000 -class TestMITNEBSet(PymatgenTest): - def setUp(self): +class TestMITNEBSet(MatSciTest): + def setup_method(self): c1 = [[0.5] * 3, [0.9] * 3] c2 = [[0.5] * 3, [0.9, 0.1, 0.1]] s1 = Structure(Lattice.cubic(5), ["Si", "Si"], c1) @@ -1359,8 +1359,8 @@ def test_write_input(self): assert not os.path.isfile("04/POSCAR") -class TestMPSOCSet(PymatgenTest): - def setUp(self): +class TestMPSOCSet(MatSciTest): + def setup_method(self): self.set = MPSOCSet def test_from_prev_calc(self): @@ -1396,7 +1396,7 @@ def test_override_from_prev_calc(self): assert vis.incar["SIGMA"] == 0.025 -class TestMPNMRSet(PymatgenTest): +class TestMPNMRSet(MatSciTest): def test_incar(self): filepath = f"{TEST_FILES_DIR}/cif/Li.cif" structure = Structure.from_file(filepath) @@ -1418,8 +1418,8 @@ def test_incar(self): @skip_if_no_psp_dir -class TestMVLSlabSet(PymatgenTest): - def setUp(self): +class TestMVLSlabSet(MatSciTest): + def setup_method(self): self.set = MVLSlabSet struct = self.get_structure("Li2O") gen = SlabGenerator(struct, (1, 0, 0), 10, 10) @@ -1490,7 +1490,7 @@ def test_as_from_dict(self): assert "structure" not in self.vis.as_dict(verbosity=1) -class TestMVLElasticSet(PymatgenTest): +class TestMVLElasticSet(MatSciTest): def test_incar(self): mvlparam = MVLElasticSet(self.get_structure("Graphite")) incar = mvlparam.incar @@ -1501,10 +1501,10 @@ def test_incar(self): @skip_if_no_psp_dir -class TestMVLGWSet(PymatgenTest): - def setUp(self): +class TestMVLGWSet(MatSciTest): + def setup_method(self): self.set = MVLGWSet - self.struct = PymatgenTest.get_structure("Li2O") + self.struct = MatSciTest.get_structure("Li2O") def test_static(self): assert self.set.mode == "STATIC" @@ -1579,8 +1579,8 @@ def test_bse(self): assert mvlgwgbse1.incar["ALGO"] == "Bse" -class TestMPHSERelaxSet(PymatgenTest): - def setUp(self): +class TestMPHSERelaxSet(MatSciTest): + def setup_method(self): self.structure = dummy_structure self.set = MPHSERelaxSet @@ -1609,6 +1609,7 @@ def test_user_incar_settings(self): assert not vis.incar["LASPH"], "LASPH user setting not applied" assert vis.incar["VDW_SR"] == 1.5, "VDW_SR user setting not applied" + @pytest.mark.skipif(not os.path.exists(TEST_DIR), reason="Test files are not present.") def test_from_prev_calc(self): prev_run = os.path.join(TEST_DIR, "fixtures", "relaxation") @@ -1625,6 +1626,7 @@ def test_from_prev_calc(self): assert "VDW_A2" in vis_bj.incar assert "VDW_S8" in vis_bj.incar + @pytest.mark.skipif(not os.path.exists(TEST_DIR), reason="Test files are not present.") def test_override_from_prev_calc(self): prev_run = os.path.join(TEST_DIR, "fixtures", "relaxation") @@ -1644,8 +1646,8 @@ def test_override_from_prev_calc(self): assert "VDW_S8" in vis_bj.incar -class TestMPHSEBS(PymatgenTest): - def setUp(self): +class TestMPHSEBS(MatSciTest): + def setup_method(self): self.set = MPHSEBSSet def test_init(self): @@ -1676,7 +1678,7 @@ def test_init(self): assert vis.reciprocal_density == 100 with pytest.warns(BadInputSetWarning, match=r"Hybrid functionals"): - vis = self.set(PymatgenTest.get_structure("Li2O"), user_incar_settings={"ALGO": "Fast"}) + vis = self.set(MatSciTest.get_structure("Li2O"), user_incar_settings={"ALGO": "Fast"}) vis.incar.items() def test_override_from_prev_calc(self): @@ -1700,8 +1702,8 @@ def test_override_from_prev_calc(self): assert len(vis.kpoints.kpts) == 180 -class TestMVLScanRelaxSet(PymatgenTest): - def setUp(self): +class TestMVLScanRelaxSet(MatSciTest): + def setup_method(self): self.set = MVLScanRelaxSet file_path = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(file_path) @@ -1778,8 +1780,8 @@ def test_as_from_dict(self): assert v.user_incar_settings["NSW"] == 500 -class TestMPScanRelaxSet(PymatgenTest): - def setUp(self): +class TestMPScanRelaxSet(MatSciTest): + def setup_method(self): file_path = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(file_path) self.mp_scan_set = MPScanRelaxSet( @@ -1899,8 +1901,8 @@ def test_write_input(self): assert os.path.isfile(f"{self.tmp_path}/POSCAR") -class TestMPScanStaticSet(PymatgenTest): - def setUp(self): +class TestMPScanStaticSet(MatSciTest): + def setup_method(self): self.set = MPScanStaticSet self.prev_run = f"{TEST_DIR}/fixtures/scan_relaxation" # test inheriting from a previous SCAN relaxation @@ -1989,10 +1991,10 @@ def test_override_from_prev_calc(self): assert lepsilon_vis.incar.get("NPAR") is None -class TestFunc(PymatgenTest): +class TestFunc(MatSciTest): @skip_if_no_psp_dir def test_batch_write_input(self): - structs = list(map(PymatgenTest.get_structure, ("Li2O", "LiFePO4"))) + structs = list(map(MatSciTest.get_structure, ("Li2O", "LiFePO4"))) batch_write_input(structs, sanitize=True) for formula in ("Li4Fe4P4O16_1", "Li2O1_0"): @@ -2001,8 +2003,8 @@ def test_batch_write_input(self): @skip_if_no_psp_dir -class TestMVLGBSet(PymatgenTest): - def setUp(self): +class TestMVLGBSet(MatSciTest): + def setup_method(self): filepath = f"{TEST_FILES_DIR}/cif/Li.cif" self.struct = Structure.from_file(filepath) @@ -2027,8 +2029,8 @@ def test_kpoints(self): assert kpoints.kpts == [(k_a, k_b, 1)] -class TestMVLRelax52Set(PymatgenTest): - def setUp(self): +class TestMVLRelax52Set(MatSciTest): + def setup_method(self): self.set = MVLRelax52Set file_path = f"{VASP_IN_DIR}/POSCAR" self.struct = Structure.from_file(file_path) @@ -2065,8 +2067,8 @@ def test_as_from_dict(self): assert vasp_input.incar["NSW"] == 500 -class TestLobsterSet(PymatgenTest): - def setUp(self): +class TestLobsterSet(MatSciTest): + def setup_method(self): self.set = LobsterSet file_path = f"{VASP_IN_DIR}/POSCAR" file_path2 = f"{VASP_IN_DIR}/POSCAR.lobster.spin_DOS" @@ -2164,8 +2166,8 @@ def test_as_from_dict(self): @skip_if_no_psp_dir -class TestMPAbsorptionSet(PymatgenTest): - def setUp(self): +class TestMPAbsorptionSet(MatSciTest): + def setup_method(self): file_path = f"{TEST_DIR}/fixtures/absorption/static/POSCAR" self.structure = Structure.from_file(file_path) self.set = MPAbsorptionSet @@ -2287,8 +2289,8 @@ def test_dict_set_alias(): assert isinstance(DictSet(), VaspInputSet) -class TestMP24Sets(PymatgenTest): - def setUp(self): +class TestMP24Sets: + def setup_method(self): self.relax_set = MP24RelaxSet self.static_set = MP24StaticSet diff --git a/tests/io/xtb/test_inputs.py b/tests/io/xtb/test_inputs.py index e39d32d392a..af755d447d5 100644 --- a/tests/io/xtb/test_inputs.py +++ b/tests/io/xtb/test_inputs.py @@ -2,7 +2,7 @@ from pymatgen.core.structure import Molecule from pymatgen.io.xtb.inputs import CRESTInput -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Alex Epstein" __copyright__ = "Copyright 2020, The Materials Project" @@ -12,7 +12,7 @@ EXPECTED_DIR = f"{TEST_FILES_DIR}/io/xtb/expected_output" -class TestCRESTInput(PymatgenTest): +class TestCRESTInput(MatSciTest): """ Checks that all attributes of CRESTInput match the expected values for sample inputs. diff --git a/tests/io/xtb/test_outputs.py b/tests/io/xtb/test_outputs.py index c4d3fe69777..ddec65b5a69 100644 --- a/tests/io/xtb/test_outputs.py +++ b/tests/io/xtb/test_outputs.py @@ -7,7 +7,7 @@ from pymatgen.core.structure import Molecule from pymatgen.io.qchem.outputs import check_for_structure_changes from pymatgen.io.xtb.outputs import CRESTOutput -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from openbabel import openbabel @@ -23,7 +23,7 @@ EXPECTED_DIR = f"{TEST_FILES_DIR}/io/xtb/expected_output" -class TestCRESTOutput(PymatgenTest): +class TestCRESTOutput(MatSciTest): """ Checks that all attributes of CRESTOutput match the expected values for a sample CREST output directory. diff --git a/tests/optimization/test_linear_assignment.py b/tests/optimization/test_linear_assignment.py index 961a5032b6d..cc29fe5d713 100644 --- a/tests/optimization/test_linear_assignment.py +++ b/tests/optimization/test_linear_assignment.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest from pytest import approx @@ -9,7 +7,7 @@ from pymatgen.optimization.linear_assignment import LinearAssignment -class TestLinearAssignment(TestCase): +class TestLinearAssignment: def test(self): w0 = np.array( [ diff --git a/tests/optimization/test_neighbors.py b/tests/optimization/test_neighbors.py index 3542acd20ff..2e550d7274d 100644 --- a/tests/optimization/test_neighbors.py +++ b/tests/optimization/test_neighbors.py @@ -4,11 +4,11 @@ from pymatgen.core.lattice import Lattice from pymatgen.optimization.neighbors import find_points_in_spheres -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest -class TestNeighbors(PymatgenTest): - def setUp(self): +class TestNeighbors(MatSciTest): + def setup_method(self): self.lattice = Lattice.cubic(10.0) self.cubic = self.lattice self.tetragonal = Lattice.tetragonal(10, 20) diff --git a/tests/phonon/test_bandstructure.py b/tests/phonon/test_bandstructure.py index 51f0fddaf4e..a35a9c7d718 100644 --- a/tests/phonon/test_bandstructure.py +++ b/tests/phonon/test_bandstructure.py @@ -8,13 +8,13 @@ from pymatgen.electronic_structure.bandstructure import Kpoint from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/bandstructure" -class TestPhononBandStructureSymmLine(PymatgenTest): - def setUp(self): +class TestPhononBandStructureSymmLine(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/NaCl_phonon_bandstructure.json", encoding="utf-8") as file: dct = json.load(file) self.bs = PhononBandStructureSymmLine.from_dict(dct) diff --git a/tests/phonon/test_dos.py b/tests/phonon/test_dos.py index 5690a9eb8d2..02fb028b884 100644 --- a/tests/phonon/test_dos.py +++ b/tests/phonon/test_dos.py @@ -9,13 +9,13 @@ from pymatgen.core import Element from pymatgen.phonon.dos import CompletePhononDos, PhononDos -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/phonon/dos" -class TestPhononDos(PymatgenTest): - def setUp(self): +class TestPhononDos(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/NaCl_ph_dos.json", encoding="utf-8") as file: self.dos = PhononDos.from_dict(json.load(file)) with open(f"{TEST_DIR}/NaCl_complete_ph_dos.json", encoding="utf-8") as file: @@ -182,8 +182,8 @@ def test_dos_fp_exceptions(self): self.dos.get_dos_fp_similarity(dos_fp, dos_fp2, col=1, metric=metric, normalize=False) -class TestCompletePhononDos(PymatgenTest): - def setUp(self): +class TestCompletePhononDos(MatSciTest): + def setup_method(self): with open(f"{TEST_DIR}/NaCl_complete_ph_dos.json", encoding="utf-8") as file: self.cdos = CompletePhononDos.from_dict(json.load(file)) diff --git a/tests/phonon/test_gruneisen.py b/tests/phonon/test_gruneisen.py index 748fd68c8c2..365d9fa229b 100644 --- a/tests/phonon/test_gruneisen.py +++ b/tests/phonon/test_gruneisen.py @@ -9,7 +9,7 @@ from pymatgen.io.phonopy import get_gruneisen_ph_bs_symm_line, get_gruneisenparameter from pymatgen.phonon.gruneisen import GruneisenParameter from pymatgen.phonon.plotter import GruneisenPhononBandStructureSymmLine, GruneisenPhononBSPlotter, GruneisenPlotter -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: import phonopy @@ -21,8 +21,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/phonon/gruneisen" -class TestGruneisenPhononBandStructureSymmLine(PymatgenTest): - def setUp(self) -> None: +class TestGruneisenPhononBandStructureSymmLine(MatSciTest): + def setup_method(self) -> None: self.bs_symm_line = get_gruneisen_ph_bs_symm_line( gruneisen_path=f"{TEST_DIR}/gruneisen_eq_plus_minus_InP.yaml", structure_path=f"{TEST_DIR}/eq/POSCAR_InP", @@ -76,8 +76,8 @@ def test_as_dict_from_dict(self): @pytest.mark.skipif(TotalDos is None, reason="Phonopy not present") -class TestGruneisenParameter(PymatgenTest): - def setUp(self) -> None: +class TestGruneisenParameter(MatSciTest): + def setup_method(self) -> None: self.gruneisen_obj = get_gruneisenparameter( f"{TEST_DIR}/gruneisen_mesh_InP.yaml", structure_path=f"{TEST_DIR}/eq/POSCAR_InP", diff --git a/tests/phonon/test_ir_spectra.py b/tests/phonon/test_ir_spectra.py index 7a7eb40f4ce..f9374b96051 100644 --- a/tests/phonon/test_ir_spectra.py +++ b/tests/phonon/test_ir_spectra.py @@ -2,11 +2,11 @@ from monty.serialization import loadfn -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestIRDielectricTensor(PymatgenTest): - def setUp(self): +class TestIRDielectricTensor(MatSciTest): + def setup_method(self): self.ir_spectra = loadfn(f"{TEST_FILES_DIR}/phonon/dos/ir_spectra_mp-991652_DDB.json") def test_basic(self): diff --git a/tests/phonon/test_plotter.py b/tests/phonon/test_plotter.py index 4b6d2d945d9..042b05f3872 100644 --- a/tests/phonon/test_plotter.py +++ b/tests/phonon/test_plotter.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from unittest import TestCase import matplotlib.pyplot as plt import pytest @@ -16,8 +15,8 @@ plt.rc("text", usetex=False) # Disabling latex for testing -class TestPhononDosPlotter(TestCase): - def setUp(self): +class TestPhononDosPlotter: + def setup_method(self): with open(f"{TEST_DIR}/NaCl_complete_ph_dos.json", encoding="utf-8") as file: self.dos = CompletePhononDos.from_dict(json.load(file)) self.plotter = PhononDosPlotter(sigma=0.2, stack=True) @@ -54,8 +53,8 @@ def test_plot(self): assert ax3.get_ylim() == ax.get_xlim() -class TestPhononBSPlotter(TestCase): - def setUp(self): +class TestPhononBSPlotter: + def setup_method(self): with open( f"{TEST_FILES_DIR}/electronic_structure/bandstructure/NaCl_phonon_bandstructure.json", encoding="utf-8" ) as file: @@ -117,8 +116,8 @@ def test_plot_compare(self): assert ax is None -class TestThermoPlotter(TestCase): - def setUp(self): +class TestThermoPlotter: + def setup_method(self): with open(f"{TEST_DIR}/NaCl_complete_ph_dos.json", encoding="utf-8") as file: self.dos = CompletePhononDos.from_dict(json.load(file)) self.plotter = ThermoPlotter(self.dos, self.dos.structure) diff --git a/tests/phonon/test_thermal_displacements.py b/tests/phonon/test_thermal_displacements.py index 5604e7c4989..b2347070e6b 100644 --- a/tests/phonon/test_thermal_displacements.py +++ b/tests/phonon/test_thermal_displacements.py @@ -6,15 +6,15 @@ from pymatgen.core.structure import Structure from pymatgen.phonon.thermal_displacements import ThermalDisplacementMatrices -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/phonon/thermal_displacement_matrices" -class TestThermalDisplacement(PymatgenTest): +class TestThermalDisplacement(MatSciTest): """Test data from J. George's matlab code https://github.com/JaGeo/MolecularToolbox.""" - def setUp(self) -> None: + def setup_method(self) -> None: self.thermal = ThermalDisplacementMatrices( thermal_displacement_matrix_cart=[ [5.16e-03, 6.13e-03, 4.15e-03, -1.10e-04, -1.58e-03, -8.10e-04], diff --git a/tests/symmetry/test_analyzer.py b/tests/symmetry/test_analyzer.py index ca87247c5ff..34950c11089 100644 --- a/tests/symmetry/test_analyzer.py +++ b/tests/symmetry/test_analyzer.py @@ -1,7 +1,6 @@ from __future__ import annotations from dataclasses import asdict -from unittest import TestCase import numpy as np import pytest @@ -19,13 +18,13 @@ iterative_symmetrize, ) from pymatgen.symmetry.structure import SymmetrizedStructure -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/symmetry/analyzer" -class TestSpacegroupAnalyzer(PymatgenTest): - def setUp(self): +class TestSpacegroupAnalyzer(MatSciTest): + def setup_method(self): self.structure = Structure.from_file(f"{VASP_IN_DIR}/POSCAR") self.sg = SpacegroupAnalyzer(self.structure, 0.001) self.disordered_structure = self.get_structure("Li10GeP2S12") @@ -55,7 +54,7 @@ def test_is_laue(self): assert self.disordered_sg.is_laue() def test_magnetic(self): - lfp = PymatgenTest.get_structure("LiFePO4") + lfp = MatSciTest.get_structure("LiFePO4") sg = SpacegroupAnalyzer(lfp, 0.1) assert sg.get_space_group_symbol() == "Pnma" magmoms = [0] * len(lfp) @@ -444,8 +443,8 @@ def test_bad_structure(self): SpacegroupAnalyzer(struct, 0.1) -class TestSpacegroup(TestCase): - def setUp(self): +class TestSpacegroup: + def setup_method(self): self.structure = Structure.from_file(f"{VASP_IN_DIR}/POSCAR") self.sg1 = SpacegroupAnalyzer(self.structure, 0.001).get_space_group_operations() @@ -537,7 +536,7 @@ def test_are_symmetrically_equivalent(self): ) -class TestPointGroupAnalyzer(PymatgenTest): +class TestPointGroupAnalyzer(MatSciTest): def test_spherical(self): pg_analyzer = PointGroupAnalyzer(CH4) assert pg_analyzer.sch_symbol == "Td" @@ -671,7 +670,7 @@ def test_symmetrize_molecule2(self): def test_get_kpoint_weights(self): for name in ("SrTiO3", "LiFePO4", "Graphite"): - struct = PymatgenTest.get_structure(name) + struct = MatSciTest.get_structure(name) spga = SpacegroupAnalyzer(struct) ir_mesh = spga.get_ir_reciprocal_mesh((4, 4, 4)) weights = [i[1] for i in ir_mesh] @@ -680,7 +679,7 @@ def test_get_kpoint_weights(self): assert weight == approx(expected) for name in ("SrTiO3", "LiFePO4", "Graphite"): - struct = PymatgenTest.get_structure(name) + struct = MatSciTest.get_structure(name) spga = SpacegroupAnalyzer(struct) ir_mesh = spga.get_ir_reciprocal_mesh((1, 2, 3)) weights = [i[1] for i in ir_mesh] @@ -703,7 +702,7 @@ def test_get_kpoint_weights(self): spga.get_kpoint_weights(kpts) -class TestFunc(TestCase): +class TestFunc: def test_cluster_sites(self): site, cluster = cluster_sites(CH4, 0.1) assert isinstance(site, Site) diff --git a/tests/symmetry/test_kpath_hin.py b/tests/symmetry/test_kpath_hin.py index 2a7cce41712..de384d7fe3c 100644 --- a/tests/symmetry/test_kpath_hin.py +++ b/tests/symmetry/test_kpath_hin.py @@ -6,12 +6,12 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.symmetry.kpath import KPathSeek -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest pytest.importorskip("seekpath", reason="seekpath not installed") -class TestKPathSeek(PymatgenTest): +class TestKPathSeek(MatSciTest): def test_kpath_generation(self): triclinic = [1, 2] monoclinic = range(3, 16) diff --git a/tests/symmetry/test_kpath_lm.py b/tests/symmetry/test_kpath_lm.py index 479ffecb65d..bb6299f9ffd 100644 --- a/tests/symmetry/test_kpath_lm.py +++ b/tests/symmetry/test_kpath_lm.py @@ -8,10 +8,10 @@ from pymatgen.core.structure import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.symmetry.kpath import KPathLatimerMunro -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest -class TestKPathLatimerMunro(PymatgenTest): +class TestKPathLatimerMunro(MatSciTest): def test_kpath_generation(self): triclinic = [1, 2] monoclinic = range(3, 16) diff --git a/tests/symmetry/test_kpath_sc.py b/tests/symmetry/test_kpath_sc.py index d88c97f79dd..bede6afd292 100644 --- a/tests/symmetry/test_kpath_sc.py +++ b/tests/symmetry/test_kpath_sc.py @@ -6,12 +6,12 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.symmetry.kpath import KPathSetyawanCurtarolo -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest TEST_DIR = f"{TEST_FILES_DIR}/symmetry/space_group_structs" -class TestBandStructureSC(PymatgenTest): +class TestBandStructureSC(MatSciTest): def test_kpath_generation(self): triclinic = [1, 2] monoclinic = range(3, 16) diff --git a/tests/symmetry/test_kpaths.py b/tests/symmetry/test_kpaths.py index 87c8bd16480..dc3f4c44c5a 100644 --- a/tests/symmetry/test_kpaths.py +++ b/tests/symmetry/test_kpaths.py @@ -7,7 +7,7 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.symmetry.bandstructure import HighSymmKpath -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest try: from seekpath import get_path @@ -17,7 +17,7 @@ TEST_DIR = f"{TEST_FILES_DIR}/electronic_structure/bandstructure" -class TestHighSymmKpath(PymatgenTest): +class TestHighSymmKpath(MatSciTest): @pytest.mark.skipif(get_path is None, reason="No seek path present.") def test_kpath_generation(self): triclinic = [1, 2] diff --git a/tests/symmetry/test_maggroups.py b/tests/symmetry/test_maggroups.py index 876c4979a73..b78100e0ccc 100644 --- a/tests/symmetry/test_maggroups.py +++ b/tests/symmetry/test_maggroups.py @@ -8,7 +8,7 @@ from pymatgen.core.lattice import Lattice from pymatgen.symmetry.groups import SpaceGroup from pymatgen.symmetry.maggroups import MagneticSpaceGroup -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest __author__ = "Matthew Horton" __copyright__ = "Copyright 2017, The Materials Project" @@ -19,8 +19,8 @@ __date__ = "Feb 2017" -class TestMagneticSpaceGroup(PymatgenTest): - def setUp(self): +class TestMagneticSpaceGroup(MatSciTest): + def setup_method(self): self.msg_1 = MagneticSpaceGroup([70, 530]) self.msg_2 = MagneticSpaceGroup([62, 448]) self.msg_3 = MagneticSpaceGroup([20, 37]) diff --git a/tests/symmetry/test_settings.py b/tests/symmetry/test_settings.py index 79a6b56c138..5d4d2db24be 100644 --- a/tests/symmetry/test_settings.py +++ b/tests/symmetry/test_settings.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np from numpy.testing import assert_allclose @@ -16,8 +14,8 @@ __date__ = "Apr 2017" -class TestJonesFaithfulTransformation(TestCase): - def setUp(self): +class TestJonesFaithfulTransformation: + def setup_method(self): self.test_strings = [ "a,b,c;0,0,0", # identity "a-b,a+b,2c;0,0,1/2", diff --git a/tests/symmetry/test_site_symmetries.py b/tests/symmetry/test_site_symmetries.py index 1b33f3a11f0..504f3a81dc6 100644 --- a/tests/symmetry/test_site_symmetries.py +++ b/tests/symmetry/test_site_symmetries.py @@ -6,7 +6,7 @@ from monty.json import MontyDecoder from pymatgen.symmetry import site_symmetries as ss -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest __author__ = "Handong Ling" __version__ = "0.1" @@ -18,8 +18,8 @@ TEST_DIR = f"{TEST_FILES_DIR}/symmetry/site_symmetries" -class TestSiteSymmetries(PymatgenTest): - def setUp(self): +class TestSiteSymmetries(MatSciTest): + def setup_method(self): with gzip.open(f"{TEST_DIR}/point_ops.json.gz", mode="rt") as file: self.point_ops = MontyDecoder().process_decoded(json.load(file)) diff --git a/tests/transformations/test_advanced_transformations.py b/tests/transformations/test_advanced_transformations.py index 1d6a2bc4ded..83cab20349a 100644 --- a/tests/transformations/test_advanced_transformations.py +++ b/tests/transformations/test_advanced_transformations.py @@ -40,7 +40,7 @@ OxidationStateDecorationTransformation, SubstitutionTransformation, ) -from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, VASP_IN_DIR, MatSciTest try: import hiphive @@ -276,8 +276,8 @@ def test_as_dict(self): @pytest.mark.skipif(not enumlib_present, reason="enum_lib not present.") -class TestMagOrderingTransformation(PymatgenTest): - def setUp(self): +class TestMagOrderingTransformation(MatSciTest): + def setup_method(self): lattice = Lattice.cubic(4.17) species = ["Ni", "O"] coords = [[0, 0, 0], [0.5, 0.5, 0.5]] @@ -488,9 +488,9 @@ def test_advanced_usage(self): @pytest.mark.skipif(not enumlib_present, reason="enum_lib not present.") -class TestDopingTransformation(PymatgenTest): +class TestDopingTransformation(MatSciTest): def test_apply_transformation(self): - structure = PymatgenTest.get_structure("LiFePO4") + structure = MatSciTest.get_structure("LiFePO4") spga = SpacegroupAnalyzer(structure, 0.1) structure = spga.get_refined_structure() trafo = DopingTransformation("Ca2+", min_length=10) @@ -524,7 +524,7 @@ def test_apply_transformation(self): assert d["structure"].charge == 0 # Make sure compensation is done with lowest oxi state - structure = PymatgenTest.get_structure("SrTiO3") + structure = MatSciTest.get_structure("SrTiO3") trafo = DopingTransformation( "Nb5+", min_length=5, @@ -551,7 +551,7 @@ def test_find_codopant(self): assert find_codopant(Species("Fe", 2), 3) == Species("In", 3) -class TestSlabTransformation(PymatgenTest): +class TestSlabTransformation(MatSciTest): def test_apply_transformation(self): struct = self.get_structure("LiFePO4") trans = SlabTransformation([0, 0, 1], 10, 10, shift=0.25) @@ -570,7 +570,7 @@ def test_apply_transformation(self): assert_allclose(slab_from_gen.cart_coords, slab_from_trans.cart_coords) -class TestGrainBoundaryTransformation(PymatgenTest): +class TestGrainBoundaryTransformation(MatSciTest): def test_apply_transformation(self): Al_bulk = Structure.from_spacegroup("Fm-3m", Lattice.cubic(2.8575585), ["Al"], [[0, 0, 0]]) gb_gen_params_s5 = { @@ -590,7 +590,7 @@ def test_apply_transformation(self): assert_allclose(gb_from_generator.cart_coords, gb_from_trans.cart_coords) -class TestDisorderedOrderedTransformation(PymatgenTest): +class TestDisorderedOrderedTransformation(MatSciTest): def test_apply_transformation(self): # nonsensical example just for testing purposes struct = self.get_structure("BaNiO3") @@ -603,7 +603,7 @@ def test_apply_transformation(self): @pytest.mark.skipif(not mcsqs_cmd, reason="mcsqs not present.") -class TestSQSTransformation(PymatgenTest): +class TestSQSTransformation(MatSciTest): def test_apply_transformation(self): pzt_structs = loadfn(f"{TEST_FILES_DIR}/io/atat/mcsqs/pzt-structs.json") trans = SQSTransformation(scaling=[2, 1, 1], search_time=0.01, instances=1, wd=0) @@ -649,7 +649,7 @@ def test_spin(self): @pytest.mark.skipif(ClusterSpace is None, reason="icet not installed.") -class TestSQSTransformationIcet(PymatgenTest): +class TestSQSTransformationIcet(MatSciTest): stored_run: dict = loadfn(f"{TEST_FILES_DIR}/transformations/icet-sqs-fcc-Mg_75-Al_25-scaling_8.json.gz") scaling: int = 8 @@ -699,7 +699,7 @@ def test_monte_carlo(self): assert isinstance(sqs_output[0][key], val) -class TestCubicSupercellTransformation(PymatgenTest): +class TestCubicSupercellTransformation(MatSciTest): def test_apply_transformation_cubic_supercell(self): structure = self.get_structure("TlBiSe2") min_atoms = 100 @@ -848,7 +848,7 @@ def test_apply_transformation_orthorhombic_supercell(self): assert transformed_cubic.lattice.angles == transformed_orthorhombic.lattice.angles -class TestAddAdsorbateTransformation(PymatgenTest): +class TestAddAdsorbateTransformation(MatSciTest): def test_apply_transformation(self): co = Molecule(["C", "O"], [[0, 0, 0], [0, 0, 1.23]]) trans = AddAdsorbateTransformation(co) @@ -859,7 +859,7 @@ def test_apply_transformation(self): assert out.reduced_formula == "Pt4CO" -class TestSubstituteSurfaceSiteTransformation(PymatgenTest): +class TestSubstituteSurfaceSiteTransformation(MatSciTest): def test_apply_transformation(self): trans = SubstituteSurfaceSiteTransformation("Au") pt = Structure(Lattice.cubic(5), ["Pt"], [[0, 0, 0]]) # fictitious @@ -870,7 +870,7 @@ def test_apply_transformation(self): @pytest.mark.skipif(not hiphive, reason="hiphive not present") -class TestMonteCarloRattleTransformation(PymatgenTest): +class TestMonteCarloRattleTransformation(MatSciTest): def test_apply_transformation(self): struct = self.get_structure("Si") mcrt = MonteCarloRattleTransformation(0.01, 2, seed=1) diff --git a/tests/transformations/test_site_transformations.py b/tests/transformations/test_site_transformations.py index 0e97aceabc0..bddf1ca817f 100644 --- a/tests/transformations/test_site_transformations.py +++ b/tests/transformations/test_site_transformations.py @@ -1,7 +1,6 @@ from __future__ import annotations from shutil import which -from unittest import TestCase import numpy as np import pytest @@ -17,15 +16,15 @@ ReplaceSiteSpeciesTransformation, TranslateSitesTransformation, ) -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest enum_cmd = which("enum.x") or which("multienum.x") makestr_cmd = which("makestr.x") or which("makeStr.x") or which("makeStr.py") enumlib_present = enum_cmd and makestr_cmd -class TestTranslateSitesTransformation(PymatgenTest): - def setUp(self): +class TestTranslateSitesTransformation(MatSciTest): + def setup_method(self): coords = [ [0, 0, 0], [0.375, 0.375, 0.375], @@ -78,8 +77,8 @@ def test_as_from_dict(self): str(t2) -class TestReplaceSiteSpeciesTransformation(TestCase): - def setUp(self): +class TestReplaceSiteSpeciesTransformation: + def setup_method(self): coords = [ [0, 0, 0], [0.375, 0.375, 0.375], @@ -110,8 +109,8 @@ def test_as_from_dict(self): assert struct.formula == "Na1 Li3 O4" -class TestRemoveSitesTransformation(TestCase): - def setUp(self): +class TestRemoveSitesTransformation: + def setup_method(self): coords = [ [0, 0, 0], [0.375, 0.375, 0.375], @@ -142,8 +141,8 @@ def test_as_from_dict(self): assert struct.formula == "Li2 O4" -class TestInsertSitesTransformation(TestCase): - def setUp(self): +class TestInsertSitesTransformation: + def setup_method(self): coords = [ [0, 0, 0], [0.375, 0.375, 0.375], @@ -179,8 +178,8 @@ def test_as_from_dict(self): assert struct.formula == "Li4 Mn1 Fe1 O4" -class TestPartialRemoveSitesTransformation(TestCase): - def setUp(self): +class TestPartialRemoveSitesTransformation: + def setup_method(self): coords = [ [0, 0, 0], [0.375, 0.375, 0.375], @@ -264,7 +263,7 @@ def test_str(self): ) -class TestAddSitePropertyTransformation(PymatgenTest): +class TestAddSitePropertyTransformation(MatSciTest): def test_apply_transformation(self): struct = self.get_structure("Li2O2") sd = [[True, True, True] for _ in struct] @@ -279,8 +278,8 @@ def test_apply_transformation(self): assert_allclose(trans_set.site_properties[prop], manually_set.site_properties[prop]) -class TestRadialSiteDistortionTransformation(PymatgenTest): - def setUp(self): +class TestRadialSiteDistortionTransformation(MatSciTest): + def setup_method(self): self.molecule = Molecule( species=["C", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H"], coords=[ diff --git a/tests/transformations/test_standard_transformations.py b/tests/transformations/test_standard_transformations.py index 7a49a0bf301..f51e4a37d18 100644 --- a/tests/transformations/test_standard_transformations.py +++ b/tests/transformations/test_standard_transformations.py @@ -4,7 +4,6 @@ import json import operator from shutil import which -from unittest import TestCase import numpy as np import pytest @@ -41,8 +40,8 @@ enumlib_present = which("enum.x") and which("makestr.x") -class TestRotationTransformations(TestCase): - def setUp(self): +class TestRotationTransformations: + def setup_method(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = [ [3.8401979337, 0, 0], @@ -108,8 +107,8 @@ def test_fractional_substitution(self): assert struct_trafo.formula == "Na2 Se1 S1" -class TestSupercellTransformation(TestCase): - def setUp(self): +class TestSupercellTransformation: + def setup_method(self): coords = [[0, 0, 0], [0.75, 0.75, 0.75], [0.5, 0.5, 0.5], [0.25, 0.25, 0.25]] lattice = [ [3.8401979337, 0, 0], diff --git a/tests/util/test_coord.py b/tests/util/test_coord.py index c97914e6319..b8c9b08aaba 100644 --- a/tests/util/test_coord.py +++ b/tests/util/test_coord.py @@ -1,7 +1,5 @@ from __future__ import annotations -from unittest import TestCase - import numpy as np import pytest from numpy.testing import assert_allclose, assert_array_equal @@ -250,8 +248,8 @@ def test_get_angle(self): assert coord.get_angle(v1, v2, units="radians") == approx(0.9553166181245092) -class TestSimplex(TestCase): - def setUp(self): +class TestSimplex: + def setup_method(self): coords = [[0, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]] self.simplex = coord.Simplex(coords) diff --git a/tests/util/test_io.py b/tests/util/test_io.py index 09458240656..7b05276169a 100644 --- a/tests/util/test_io.py +++ b/tests/util/test_io.py @@ -1,10 +1,10 @@ from __future__ import annotations from pymatgen.util.io_utils import micro_pyawk -from pymatgen.util.testing import VASP_OUT_DIR, PymatgenTest +from pymatgen.util.testing import VASP_OUT_DIR, MatSciTest -class TestFunc(PymatgenTest): +class TestFunc(MatSciTest): def test_micro_pyawk(self): data = [] diff --git a/tests/util/test_plotting.py b/tests/util/test_plotting.py index ec68c960d88..e8c55875fbd 100644 --- a/tests/util/test_plotting.py +++ b/tests/util/test_plotting.py @@ -3,7 +3,7 @@ import matplotlib.pyplot as plt from pymatgen.util.plotting import periodic_table_heatmap, van_arkel_triangle -from pymatgen.util.testing import PymatgenTest +from pymatgen.util.testing import MatSciTest try: import pymatviz @@ -12,7 +12,7 @@ pymatviz = None -class TestFunc(PymatgenTest): +class TestFunc(MatSciTest): def test_plot_periodic_heatmap(self): random_data = {"Te": 0.11083, "Au": 0.75756, "Th": 1.24758, "Ni": -2.0354} fig = periodic_table_heatmap(random_data) diff --git a/tests/util/test_provenance.py b/tests/util/test_provenance.py index c44817d6982..70b629ffe79 100644 --- a/tests/util/test_provenance.py +++ b/tests/util/test_provenance.py @@ -3,7 +3,6 @@ from __future__ import annotations from datetime import datetime, timedelta, timezone -from unittest import TestCase import numpy as np import pytest @@ -20,8 +19,8 @@ __date__ = "2/14/13" -class TestStructureNL(TestCase): - def setUp(self): +class TestStructureNL: + def setup_method(self): # set up a Structure self.struct = Structure(np.eye(3, 3) * 3, ["Fe"], [[0, 0, 0]]) self.s2 = Structure(np.eye(3, 3) * 3, ["Al"], [[0, 0, 0]]) diff --git a/tests/util/test_testing.py b/tests/util/test_testing.py index 13a97b823de..70af5e1ea7e 100644 --- a/tests/util/test_testing.py +++ b/tests/util/test_testing.py @@ -1,7 +1,10 @@ +"""Test testing utils.""" + from __future__ import annotations import json import os +import warnings from pathlib import Path from unittest.mock import patch @@ -17,9 +20,20 @@ TEST_FILES_DIR, VASP_IN_DIR, VASP_OUT_DIR, + MatSciTest, PymatgenTest, ) +warnings.filterwarnings("ignore", message="PymatgenTest is deprecated", category=FutureWarning) + + +class TestPymatgenTest(PymatgenTest): + """Test deprecated PymatgenTest.""" + + def test_deprecated_warning(self): + with pytest.warns(FutureWarning, match="PymatgenTest is deprecated"): + TestPymatgenTest() + def test_paths(): """Test paths provided in testing util.""" @@ -34,7 +48,7 @@ def test_paths(): assert any(f.startswith("POTCAR") for _root, _dir, files in os.walk(FAKE_POTCAR_DIR) for f in files) -class TestPMGTestTmpDir(PymatgenTest): +class TestTmpDir(MatSciTest): def test_tmp_dir_initialization(self): """Test that the working directory is correctly set to a temporary directory.""" current_dir = Path.cwd() @@ -55,7 +69,7 @@ def test_creating_files_in_tmp_dir(self): assert test_file.read_text() == "Hello, pytest!" -class TestPMGTestAssertMSONable(PymatgenTest): +class TestAssertMSONable(MatSciTest): def test_valid_msonable(self): """Test a valid MSONable object.""" kpts_obj = Kpoints.monkhorst_automatic((2, 2, 2), [0, 0, 0]) @@ -119,7 +133,7 @@ class NotAKpoints: mock_decoder.assert_called() -class TestPymatgenTest(PymatgenTest): +class TestMatSciTest(MatSciTest): def test_assert_str_content_equal(self): # Cases where strings are equal self.assert_str_content_equal("hello world", "hello world") diff --git a/tests/vis/test_plotters.py b/tests/vis/test_plotters.py index c2108809ba6..9789d4ba4e5 100644 --- a/tests/vis/test_plotters.py +++ b/tests/vis/test_plotters.py @@ -8,15 +8,15 @@ from monty.json import MontyDecoder from pymatgen.analysis.xas.spectrum import XAS -from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest +from pymatgen.util.testing import TEST_FILES_DIR, MatSciTest from pymatgen.vis.plotters import SpectrumPlotter with open(f"{TEST_FILES_DIR}/analysis/spectrum_test/LiCoO2_k_xanes.json", encoding="utf-8") as file: spect_data_dict = json.load(file, cls=MontyDecoder) -class TestSpectrumPlotter(PymatgenTest): - def setUp(self): +class TestSpectrumPlotter(MatSciTest): + def setup_method(self): self.xanes = XAS.from_dict(spect_data_dict) def test_get_plot(self):