Skip to content

Commit

Permalink
Fix _MPResterLegacy tests in pymatgen/ext/tests/test_matproj.py faili…
Browse files Browse the repository at this point in the history
…ng due to new API key (#2700)

* pymatgen/ext/tests/test_matproj.py raise ValueError with specific err msg if 15 <= len(PMG_MAPI_KEY) <= 17

* pymatgen/ext/tests/test_*.py refactor skipIf website_is_up to website_down check

* fix pymatgen/ext/tests/test_matproj.py:402: AssertionError

assert mo_s3_112[0]["gb_energy"] == pytest.approx(0.47965)
E       assert 0.4796547330588574 == 0.47965 � 4.8e-07
E         comparison failed
E         Obtained: 0.4796547330588574
E         Expected: 0.47965 � 4.8e-07

* remove shebangs from test files

* fix TypeError: MPRester.__init__() got multiple values for argument 'api_key' from MPRester('xxxxxxxxxx')
  • Loading branch information
janosh authored Oct 21, 2022
1 parent aad30d4 commit 3b160fc
Show file tree
Hide file tree
Showing 24 changed files with 60 additions and 112 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env python


import copy
import json
import os
Expand Down Expand Up @@ -467,15 +464,15 @@ def test_periodicity(self):

def test_real_systems(self):
# Initialize geometry and connectivity finders
strat = SimplestChemenvStrategy()
strategy = SimplestChemenvStrategy()
lgf = LocalGeometryFinder()
cf = ConnectivityFinder()

# Connectivity of LiFePO4
struct = self.get_structure("LiFePO4")
lgf.setup_structure(structure=struct)
se = lgf.compute_structure_environments(only_atoms=["Li", "Fe", "P"], maximum_distance_factor=1.2)
lse = LightStructureEnvironments.from_structure_environments(strategy=strat, structure_environments=se)
lse = LightStructureEnvironments.from_structure_environments(strategy=strategy, structure_environments=se)
# Make sure the initial structure and environments are correct
for isite in range(0, 4):
assert lse.structure[isite].specie.symbol == "Li"
Expand Down Expand Up @@ -784,7 +781,7 @@ def test_real_systems(self):
struct = Structure.from_file(os.path.join(self.TEST_FILES_DIR, "Li4Fe3Mn1(PO4)4.cif"))
lgf.setup_structure(structure=struct)
se = lgf.compute_structure_environments(only_atoms=["Li", "Fe", "Mn", "P"], maximum_distance_factor=1.2)
lse = LightStructureEnvironments.from_structure_environments(strategy=strat, structure_environments=se)
lse = LightStructureEnvironments.from_structure_environments(strategy=strategy, structure_environments=se)
# Make sure the initial structure and environments are correct
for isite in range(0, 4):
assert lse.structure[isite].specie.symbol == "Li"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import os

from pymatgen.analysis.chemenv.connectivity.environment_nodes import EnvironmentNode
Expand All @@ -13,6 +8,8 @@
except ModuleNotFoundError:
bson = None

__author__ = "waroquiers"

json_files_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import json
import os

Expand All @@ -26,6 +21,8 @@
except ModuleNotFoundError:
bson = None

__author__ = "waroquiers"


class StructureConnectivityTest(PymatgenTest):
def test_serialization(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import unittest

import pytest
Expand All @@ -16,6 +11,8 @@
)
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"


class StrategyOptionsTest(PymatgenTest):
def test_options(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import unittest

import numpy as np
Expand All @@ -16,6 +11,8 @@
)
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"

allcg = AllCoordinationGeometries()


Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import os
import unittest

Expand All @@ -20,6 +15,8 @@
from pymatgen.core.structure import Lattice, Structure
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"

json_files_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import json
import os
import unittest
Expand All @@ -21,6 +16,8 @@
from pymatgen.core.periodic_table import Species
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"

se_files_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import os
import random
import unittest
Expand All @@ -17,6 +12,8 @@
from pymatgen.core.structure import Structure
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"

json_files_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import json
import os
import unittest
Expand All @@ -24,6 +19,8 @@
)
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"

se_files_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/chemenv/utils/chemenv_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def __init__(self, package_options=None):
"""
:param package_options:
"""
if SETTINGS.get("PMG_MAPI_KEY", "") != "":
self.materials_project_configuration = SETTINGS.get("PMG_MAPI_KEY", "")
if SETTINGS.get("PMG_MAPI_KEY"):
self.materials_project_configuration = SETTINGS.get("PMG_MAPI_KEY")
else:
self.materials_project_configuration = None

Expand Down
15 changes: 4 additions & 11 deletions pymatgen/analysis/chemenv/utils/tests/test_chemenv_config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import os
import unittest

Expand All @@ -12,19 +7,17 @@
from pymatgen.core import SETTINGS
from pymatgen.util.testing import PymatgenTest

config_file_dir = os.path.join(
PymatgenTest.TEST_FILES_DIR,
"chemenv",
"config",
)
__author__ = "waroquiers"

config_file_dir = os.path.join(PymatgenTest.TEST_FILES_DIR, "chemenv", "config")


class ChemenvConfigTest(unittest.TestCase):
def test_chemenv_config(self):
with ScratchDir("."):
config = ChemEnvConfig()

if SETTINGS.get("PMG_MAPI_KEY", "") != "":
if SETTINGS.get("PMG_MAPI_KEY"):
assert config.has_materials_project_access
else:
assert not config.has_materials_project_access
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import itertools
import random
import unittest
Expand All @@ -12,6 +7,8 @@
from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"


class PlanesUtilsTest(PymatgenTest):
def setUp(self):
Expand Down
7 changes: 2 additions & 5 deletions pymatgen/analysis/chemenv/utils/tests/test_func_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import unittest

import numpy as np
Expand All @@ -14,6 +9,8 @@
DeltaCSMRatioFunction,
)

__author__ = "waroquiers"


class FuncUtilsTest(unittest.TestCase):
def test_CSMFiniteRatioFunction(self):
Expand Down
7 changes: 2 additions & 5 deletions pymatgen/analysis/chemenv/utils/tests/test_math_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
#!/usr/bin/env python


__author__ = "waroquiers"

import unittest

import numpy as np
Expand All @@ -22,6 +17,8 @@
)
from pymatgen.util.testing import PymatgenTest

__author__ = "waroquiers"


class MathUtilsTest(PymatgenTest):
def test_list_cartesian_product(self):
Expand Down
2 changes: 0 additions & 2 deletions pymatgen/analysis/tests/test_path_finder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

import os
import unittest

Expand Down
19 changes: 7 additions & 12 deletions pymatgen/ext/matproj.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,6 @@ def get_exp_entry(self, formula):
Returns:
An ExpEntry object.
"""

return ExpEntry(Composition(formula), self.get_exp_thermo_data(formula))

def query(
Expand Down Expand Up @@ -1349,9 +1348,11 @@ def get_cohesive_energy(self, material_id, per_atom=False):
Gets the cohesive for a material (eV per formula unit). Cohesive energy
is defined as the difference between the bulk energy and the sum of
total DFT energy of isolated atoms for atom elements in the bulk.
Args:
material_id (str): Materials Project material_id, e.g. 'mp-123'.
per_atom (bool): Whether or not to return cohesive energy per atom
Returns:
Cohesive energy (eV).
"""
Expand Down Expand Up @@ -1412,7 +1413,6 @@ def get_all_substrates(self):
Returns:
list of material_ids corresponding to possible substrates
"""

return self._make_request("/materials/all_substrate_ids")

def get_surface_data(self, material_id, miller_index=None, inc_structures=False):
Expand All @@ -1433,6 +1433,7 @@ def get_surface_data(self, material_id, miller_index=None, inc_structures=False)
of this specific plane will be returned.
inc_structures (bool): Include final surface slab structures.
These are unnecessary for Wulff shape construction.
Returns:
Surface data for material. Energies are given in SI units (J/m^2).
"""
Expand All @@ -1457,6 +1458,7 @@ def get_wulff_shape(self, material_id):
Args:
material_id (str): Materials Project material_id, e.g. 'mp-123'.
Returns:
pymatgen.analysis.wulff.WulffShape
"""
Expand Down Expand Up @@ -1580,7 +1582,7 @@ def get_interface_reactions(

def get_download_info(self, material_ids, task_types=None, file_patterns=None):
"""
get a list of URLs to retrieve raw VASP output files from the NoMaD repository
Get a list of URLs to retrieve raw VASP output files from the NoMaD repository
Args:
material_ids (list): list of material identifiers (mp-id's)
Expand Down Expand Up @@ -1762,23 +1764,16 @@ def __new__(cls, *args, **kwargs):
*args: Pass through to either legacy or new MPRester.
**kwargs: Pass through to either legacy or new MPRester.
"""

if len(args) > 0:
api_key = args[0]
else:
api_key = kwargs.get("api_key", None)

if api_key is None:
api_key = SETTINGS.get("PMG_MAPI_KEY", "")
api_key = kwargs.get("api_key", SETTINGS.get("PMG_MAPI_KEY"))
kwargs["api_key"] = api_key

if not api_key:
raise ValueError("Please supply an API key. See https://materialsproject.org/api for details.")

if len(api_key) == 32:
return _MPResterNew(*args, **kwargs)
else:
return _MPResterLegacy(*args, **kwargs)
return (_MPResterNew if len(api_key) == 32 else _MPResterLegacy)(*args, **kwargs)


class MPRestError(Exception):
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/ext/tests/test_cod.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
from pymatgen.ext.cod import COD

try:
website_is_up = requests.get("https://www.crystallography.net").status_code == 200
website_down = requests.get("https://www.crystallography.net").status_code != 200
except requests.exceptions.ConnectionError:
website_is_up = False
website_down = True


@unittest.skipIf(not website_is_up, "www.crystallography.net is down.")
@unittest.skipIf(website_down, "www.crystallography.net is down.")
class CODTest(unittest.TestCase):
_multiprocess_shared_ = True

Expand Down
Loading

0 comments on commit 3b160fc

Please sign in to comment.