diff --git a/iodata/api.py b/iodata/api.py index c0c6d467..a60fe3de 100644 --- a/iodata/api.py +++ b/iodata/api.py @@ -83,9 +83,13 @@ def _select_format_module(filename: str, attrname: str, fmt: Optional[str] = Non format_module, attrname ): return format_module - else: - return FORMAT_MODULES[fmt] - raise FileFormatError(f"Cannot find file format with feature {attrname}", filename) + raise FileFormatError(f"Cannot find file format with feature {attrname}", filename) + if fmt in FORMAT_MODULES: + format_module = FORMAT_MODULES[fmt] + if not hasattr(format_module, attrname): + raise FileFormatError(f"Format {fmt} does not support feature {attrname}", filename) + return format_module + raise FileFormatError(f"Unknown file format {fmt}", filename) def _find_input_modules(): diff --git a/iodata/test/test_api.py b/iodata/test/test_api.py index 0003a855..c03f0bfe 100644 --- a/iodata/test/test_api.py +++ b/iodata/test/test_api.py @@ -27,9 +27,37 @@ import pytest from numpy.testing import assert_allclose, assert_array_equal -from ..api import dump_many, dump_one, load_many +from ..api import dump_many, dump_one, load_many, write_input from ..iodata import IOData -from ..utils import DumpError, PrepareDumpError +from ..utils import DumpError, FileFormatError, PrepareDumpError + + +def test_json_no_pattern(tmpdir): + path_json = os.path.join(tmpdir, "name.json") + with pytest.raises(FileFormatError): + dump_one(IOData(atnums=[1, 2, 3]), path_json) + assert not os.path.isfile(path_json) + + +def test_nonexisting_format(tmpdir): + path = os.path.join(tmpdir, "foobar") + with pytest.raises(FileFormatError): + dump_one(IOData(atnums=[1, 2, 3]), path, fmt="file-format-does-not-exist-at-all") + assert not os.path.isfile(path) + + +def test_nodump(tmpdir): + path = os.path.join(tmpdir, "foobar") + with pytest.raises(FileFormatError): + dump_one(IOData(atnums=[1, 2, 3]), path, fmt="cp2klog") + assert not os.path.isfile(path) + + +def test_noinput(tmpdir): + path = os.path.join(tmpdir, "foobar") + with pytest.raises(FileFormatError): + write_input(IOData(atnums=[1, 2, 3]), path, fmt="this-input-format-does-not-exist") + assert not os.path.isfile(path) def test_empty_dump_many_no_file(tmpdir):