Skip to content

Commit

Permalink
Bail early if an unsupported doctype is passed to export_od() (#486)
Browse files Browse the repository at this point in the history
Fixes #485
  • Loading branch information
erlend-aasland authored Jul 3, 2024
1 parent 92a6e11 commit cc37aee
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
16 changes: 8 additions & 8 deletions canopen/objectdictionary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,19 @@ def export_od(
:raises ValueError:
When exporting to an unknown format.
"""
supported_doctypes = {"eds", "dcf"}
if doc_type and doc_type not in supported_doctypes:
supported = ", ".join(supported_doctypes)
raise ValueError(
f"Cannot export to the {doc_type!r} format; "
f"supported formats: {supported}"
)

opened_here = False
try:
doctypes = {"eds", "dcf"}
if isinstance(dest, str):
if doc_type is None:
for t in doctypes:
for t in supported_doctypes:
if dest.endswith(f".{t}"):
doc_type = t
break
Expand All @@ -58,12 +64,6 @@ def export_od(
elif doc_type == "dcf":
from canopen.objectdictionary import eds
return eds.export_dcf(od, dest)
else:
allowed = ", ".join(doctypes)
raise ValueError(
f"Cannot export to the {doc_type!r} format; "
f"supported formats: {allowed}"
)
finally:
# If dest is opened in this fn, it should be closed
if opened_here:
Expand Down
5 changes: 4 additions & 1 deletion test/test_eds.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,14 @@ def test_export_eds_unknown_doctype(self):
import io
filelike_object = io.StringIO()
self.addCleanup(filelike_object.close)
self.addCleanup(os.unlink, "filename")
for dest in "filename", None, filelike_object:
with self.subTest(dest=dest):
with self.assertRaisesRegex(ValueError, "'unknown'"):
canopen.export_od(self.od, dest, doc_type="unknown")
# Make sure no files are created is a filename is supplied.
if isinstance(dest, str):
with self.assertRaises(FileNotFoundError):
os.stat(dest)

def test_export_eds_to_filelike_object(self):
import io
Expand Down

0 comments on commit cc37aee

Please sign in to comment.