Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bail early if an unsupported doctype is passed to export_od() #486

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading