From 5a49a953e2c09e5b63cb6e2db1fb98d67afeda36 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Tue, 2 Jul 2024 18:50:01 +0200 Subject: [PATCH] Bail early if an unsupported doctype is passed to export_od() Fixes #485 --- canopen/objectdictionary/__init__.py | 16 ++++++++-------- test/test_eds.py | 5 ++++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/canopen/objectdictionary/__init__.py b/canopen/objectdictionary/__init__.py index 1a723616..1e80283b 100644 --- a/canopen/objectdictionary/__init__.py +++ b/canopen/objectdictionary/__init__.py @@ -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 @@ -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: diff --git a/test/test_eds.py b/test/test_eds.py index 4cbe9148..6caf0fa7 100644 --- a/test/test_eds.py +++ b/test/test_eds.py @@ -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