Skip to content

Commit

Permalink
test_to_from_file_string() left tmp files lying around when crashing,…
Browse files Browse the repository at this point in the history
… use monty ScratchDir to fix
  • Loading branch information
janosh committed Nov 1, 2022
1 parent 534ece9 commit c35bce5
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 61 deletions.
104 changes: 50 additions & 54 deletions pymatgen/core/tests/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import numpy as np
import pytest
from monty.tempfile import ScratchDir

from pymatgen.core.composition import Composition
from pymatgen.core.lattice import Lattice
Expand Down Expand Up @@ -677,43 +678,41 @@ def test_get_dist_matrix(self):
self.assertArrayAlmostEqual(self.struct.distance_matrix, ans)

def test_to_from_file_string(self):
for fmt in ["cif", "json", "poscar", "cssr"]:
s = self.struct.to(fmt=fmt)
assert s is not None
ss = IStructure.from_str(s, fmt=fmt)
self.assertArrayAlmostEqual(ss.lattice.parameters, self.struct.lattice.parameters, decimal=5)
self.assertArrayAlmostEqual(ss.frac_coords, self.struct.frac_coords)
assert isinstance(ss, IStructure)

assert "Fd-3m" in self.struct.to(fmt="CIF", symprec=0.1)

self.struct.to(filename="POSCAR.testing")
assert os.path.exists("POSCAR.testing")
os.remove("POSCAR.testing")

self.struct.to(filename="Si_testing.yaml")
assert os.path.exists("Si_testing.yaml")
s = Structure.from_file("Si_testing.yaml")
assert s == self.struct
# Test Path support.
s = Structure.from_file(Path("Si_testing.yaml"))
assert s == self.struct

# Test .yml extension works too.
os.replace("Si_testing.yaml", "Si_testing.yml")
s = Structure.from_file("Si_testing.yml")
assert s == self.struct
os.remove("Si_testing.yml")

with pytest.raises(ValueError):
self.struct.to(filename="whatever")
with pytest.raises(ValueError):
self.struct.to(fmt="badformat")

self.struct.to(filename="POSCAR.testing.gz")
s = Structure.from_file("POSCAR.testing.gz")
assert s == self.struct
os.remove("POSCAR.testing.gz")
with ScratchDir("."):
for fmt in ["cif", "json", "poscar", "cssr"]:
s = self.struct.to(fmt=fmt)
assert s is not None
ss = IStructure.from_str(s, fmt=fmt)
self.assertArrayAlmostEqual(ss.lattice.parameters, self.struct.lattice.parameters, decimal=5)
self.assertArrayAlmostEqual(ss.frac_coords, self.struct.frac_coords)
assert isinstance(ss, IStructure)

assert "Fd-3m" in self.struct.to(fmt="CIF", symprec=0.1)

self.struct.to(filename="POSCAR.testing")
assert os.path.exists("POSCAR.testing")

self.struct.to(filename="Si_testing.yaml")
assert os.path.exists("Si_testing.yaml")
s = Structure.from_file("Si_testing.yaml")
assert s == self.struct
# Test Path support.
s = Structure.from_file(Path("Si_testing.yaml"))
assert s == self.struct

# Test .yml extension works too.
os.replace("Si_testing.yaml", "Si_testing.yml")
s = Structure.from_file("Si_testing.yml")
assert s == self.struct

with pytest.raises(ValueError):
self.struct.to(filename="whatever")
with pytest.raises(ValueError):
self.struct.to(fmt="badformat")

self.struct.to(filename="POSCAR.testing.gz")
s = Structure.from_file("POSCAR.testing.gz")
assert s == self.struct

def test_pbc(self):
self.assertArrayEqual(self.struct.pbc, (True, True, True))
Expand Down Expand Up @@ -1056,23 +1055,20 @@ def test_to_from_abivars(self):
assert isinstance(s2, Structure)

def test_to_from_file_string(self):
for fmt in ["cif", "json", "poscar", "cssr", "yaml", "xsf", "res"]:
s = self.structure.to(fmt=fmt)
assert s is not None
ss = Structure.from_str(s, fmt=fmt)
self.assertArrayAlmostEqual(ss.lattice.parameters, self.structure.lattice.parameters, decimal=5)
self.assertArrayAlmostEqual(ss.frac_coords, self.structure.frac_coords)
assert isinstance(ss, Structure)

self.structure.to(filename="POSCAR.testing")
assert os.path.exists("POSCAR.testing")
os.remove("POSCAR.testing")

self.structure.to(filename="structure_testing.json")
assert os.path.exists("structure_testing.json")
s = Structure.from_file("structure_testing.json")
assert s == self.structure
os.remove("structure_testing.json")
with ScratchDir("."):
for fmt in ["cif", "json", "poscar", "cssr", "yaml", "xsf", "res"]:
s = self.structure.to(fmt=fmt)
assert s is not None
ss = Structure.from_str(s, fmt=fmt)
self.assertArrayAlmostEqual(ss.lattice.parameters, self.structure.lattice.parameters, decimal=5)
self.assertArrayAlmostEqual(ss.frac_coords, self.structure.frac_coords)
assert isinstance(ss, Structure)

self.structure.to(filename="POSCAR.testing")
assert os.path.exists("POSCAR.testing")

self.structure.to(filename="structure_testing.json")
assert Structure.from_file("structure_testing.json") == self.structure

def test_from_spacegroup(self):
s1 = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Li", "O"], [[0.25, 0.25, 0.25], [0, 0, 0]])
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/tests/test_packmol.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


# Just skip this whole test for now since packmol is problematic.
if True: # which("packmol") is None:
if True: # if which("packmol") is None:
pytest.skip("packmol executable not present", allow_module_level=True)


Expand Down
15 changes: 9 additions & 6 deletions pymatgen/util/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
Classes and methods related to the Structure Notation Language (SNL)
"""

from __future__ import annotations

import datetime
import json
import re
import sys
from collections import namedtuple
from io import StringIO
from typing import Sequence

from monty.json import MontyDecoder, MontyEncoder
from monty.string import remove_non_ascii
Expand All @@ -34,7 +37,7 @@
MAX_BIBTEX_CHARS = 20000 # maximum number of characters for BibTeX reference


def is_valid_bibtex(reference):
def is_valid_bibtex(reference: str) -> bool:
"""
Use pybtex to validate that a reference is in proper BibTeX format
Expand Down Expand Up @@ -80,14 +83,14 @@ class HistoryNode(namedtuple("HistoryNode", ["name", "url", "description"])):
Structure (dict).
"""

def as_dict(self):
def as_dict(self) -> dict[str, str]:
"""
Returns: Dict
"""
return {"name": self.name, "url": self.url, "description": self.description}

@staticmethod
def from_dict(h_node):
def from_dict(h_node: dict[str, str]) -> HistoryNode:
"""
Args:
d (dict): Dict representation
Expand Down Expand Up @@ -181,7 +184,7 @@ def parse_author(author):

class StructureNL:
"""
The Structure Notation Language (SNL, pronounced 'snail') is container
The Structure Notation Language (SNL, pronounced 'snail') is a container
for a pymatgen Structure/Molecule object with some additional fields for
enhanced provenance. It is meant to be imported/exported in a JSON file
format with the following structure:
Expand Down Expand Up @@ -329,8 +332,8 @@ def from_dict(cls, d):
@classmethod
def from_structures(
cls,
structures,
authors,
structures: Sequence[Structure],
authors: Sequence[dict[str, str]],
projects=None,
references="",
remarks=None,
Expand Down

0 comments on commit c35bce5

Please sign in to comment.