Skip to content

Commit 5409db9

Browse files
committed
add TestMolecule.test_from_sites
document raises ValueError on empty sites in from_sites doc str
1 parent f897eaa commit 5409db9

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

pymatgen/core/structure.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -942,11 +942,14 @@ def from_sites(
942942
Will be serialized when writing the structure to JSON or YAML but is
943943
lost when converting to other formats.
944944
945+
Raises:
946+
ValueError: If sites is empty or sites do not have the same lattice.
947+
945948
Returns:
946949
(Structure) Note that missing properties are set as None.
947950
"""
948951
if len(sites) < 1:
949-
raise ValueError(f"You need at least one site to construct a {cls}")
952+
raise ValueError(f"You need at least 1 site to construct a {cls.__name__}")
950953
prop_keys: list[str] = []
951954
props = {}
952955
labels = [site.label for site in sites]
@@ -2996,7 +2999,15 @@ def from_sites(
29962999
to True.
29973000
properties (dict): dictionary containing properties associated
29983001
with the whole molecule.
3002+
3003+
Raises:
3004+
ValueError: If sites is empty
3005+
3006+
Returns:
3007+
Molecule
29993008
"""
3009+
if len(sites) < 1:
3010+
raise ValueError(f"You need at least 1 site to make a {cls.__name__}")
30003011
props = collections.defaultdict(list)
30013012
for site in sites:
30023013
for k, v in site.properties.items():

tests/core/test_structure.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1392,6 +1392,9 @@ def test_from_sites(self):
13921392
struct = Structure.from_sites(self.struct, to_unit_cell=True)
13931393
assert struct.site_properties["hello"][1] == 2
13941394

1395+
with pytest.raises(ValueError, match="You need at least 1 site to construct a Structure"):
1396+
Structure.from_sites([])
1397+
13951398
def test_charge(self):
13961399
struct = Structure.from_sites(self.struct)
13971400
assert struct.charge == 0, "Initial Structure not defaulting to behavior in SiteCollection"
@@ -1943,6 +1946,13 @@ def test_insert_remove_append(self):
19431946
mol.remove_sites([0, 1])
19441947
assert mol.formula == "H3 N1"
19451948

1949+
def test_from_sites(self):
1950+
mol = Molecule.from_sites(self.mol)
1951+
assert mol == self.mol
1952+
1953+
with pytest.raises(ValueError, match="You need at least 1 site to make a Molecule"):
1954+
Molecule.from_sites([])
1955+
19461956
def test_translate_sites(self):
19471957
self.mol.translate_sites([0, 1], [0.5, 0.5, 0.5])
19481958
assert_array_equal(self.mol.cart_coords[0], [0.5, 0.5, 0.5])

0 commit comments

Comments
 (0)