Skip to content

Commit cc37aee

Browse files
Bail early if an unsupported doctype is passed to export_od() (#486)
Fixes #485
1 parent 92a6e11 commit cc37aee

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

canopen/objectdictionary/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,19 @@ def export_od(
3737
:raises ValueError:
3838
When exporting to an unknown format.
3939
"""
40+
supported_doctypes = {"eds", "dcf"}
41+
if doc_type and doc_type not in supported_doctypes:
42+
supported = ", ".join(supported_doctypes)
43+
raise ValueError(
44+
f"Cannot export to the {doc_type!r} format; "
45+
f"supported formats: {supported}"
46+
)
4047

4148
opened_here = False
4249
try:
43-
doctypes = {"eds", "dcf"}
4450
if isinstance(dest, str):
4551
if doc_type is None:
46-
for t in doctypes:
52+
for t in supported_doctypes:
4753
if dest.endswith(f".{t}"):
4854
doc_type = t
4955
break
@@ -58,12 +64,6 @@ def export_od(
5864
elif doc_type == "dcf":
5965
from canopen.objectdictionary import eds
6066
return eds.export_dcf(od, dest)
61-
else:
62-
allowed = ", ".join(doctypes)
63-
raise ValueError(
64-
f"Cannot export to the {doc_type!r} format; "
65-
f"supported formats: {allowed}"
66-
)
6767
finally:
6868
# If dest is opened in this fn, it should be closed
6969
if opened_here:

test/test_eds.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,14 @@ def test_export_eds_unknown_doctype(self):
222222
import io
223223
filelike_object = io.StringIO()
224224
self.addCleanup(filelike_object.close)
225-
self.addCleanup(os.unlink, "filename")
226225
for dest in "filename", None, filelike_object:
227226
with self.subTest(dest=dest):
228227
with self.assertRaisesRegex(ValueError, "'unknown'"):
229228
canopen.export_od(self.od, dest, doc_type="unknown")
229+
# Make sure no files are created is a filename is supplied.
230+
if isinstance(dest, str):
231+
with self.assertRaises(FileNotFoundError):
232+
os.stat(dest)
230233

231234
def test_export_eds_to_filelike_object(self):
232235
import io

0 commit comments

Comments
 (0)