From fe6eb35b6c1f5a20f61477733f64129451e8e125 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Tue, 9 Jul 2024 13:38:10 +0200 Subject: [PATCH] Tests: make sure temporary files are pre-closed Windows fails with a permission error if the temporary file is already opened. Fixes #501 --- test/test_eds.py | 8 +++----- test/test_pdo.py | 5 ++--- test/util.py | 9 +++++++++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/test/test_eds.py b/test/test_eds.py index d953b994..775b7a41 100644 --- a/test/test_eds.py +++ b/test/test_eds.py @@ -4,7 +4,7 @@ import canopen from canopen.objectdictionary.eds import _signed_int_from_hex from canopen.utils import pretty_index -from .util import SAMPLE_EDS, DATATYPES_EDS +from .util import SAMPLE_EDS, DATATYPES_EDS, tmp_file class TestEDS(unittest.TestCase): @@ -223,10 +223,9 @@ def test_comments(self): """.strip()) def test_export_eds_to_file(self): - import tempfile for suffix in ".eds", ".dcf": for implicit in True, False: - with tempfile.NamedTemporaryFile(suffix=suffix) as tmp: + with tmp_file(suffix=suffix) as tmp: dest = tmp.name doctype = None if implicit else suffix[1:] with self.subTest(dest=dest, doctype=doctype): @@ -235,9 +234,8 @@ def test_export_eds_to_file(self): def test_export_eds_to_file_unknown_extension(self): import io - import tempfile for suffix in ".txt", "": - with tempfile.NamedTemporaryFile(suffix=suffix) as tmp: + with tmp_file(suffix=suffix) as tmp: dest = tmp.name with self.subTest(dest=dest, doctype=None): canopen.export_od(self.od, dest) diff --git a/test/test_pdo.py b/test/test_pdo.py index 32c0f174..e3ad219f 100644 --- a/test/test_pdo.py +++ b/test/test_pdo.py @@ -1,7 +1,7 @@ import unittest import canopen -from .util import SAMPLE_EDS +from .util import SAMPLE_EDS, tmp_file class TestPDO(unittest.TestCase): @@ -64,14 +64,13 @@ def test_pdo_save(self): self.node.rpdo.save() def test_pdo_export(self): - import tempfile try: import canmatrix except ImportError: raise unittest.SkipTest("The PDO export API requires canmatrix") for pdo in "tpdo", "rpdo": - with tempfile.NamedTemporaryFile(suffix=".csv") as tmp: + with tmp_file(suffix=".csv") as tmp: fn = tmp.name with self.subTest(filename=fn, pdo=pdo): getattr(self.node, pdo).export(fn) diff --git a/test/util.py b/test/util.py index a4395921..2c8eccca 100644 --- a/test/util.py +++ b/test/util.py @@ -1,5 +1,14 @@ +import contextlib import os +import tempfile DATATYPES_EDS = os.path.join(os.path.dirname(__file__), "datatypes.eds") SAMPLE_EDS = os.path.join(os.path.dirname(__file__), "sample.eds") + + +@contextlib.contextmanager +def tmp_file(*args, **kwds): + with tempfile.NamedTemporaryFile(*args, **kwds) as tmp: + tmp.close() + yield tmp