Skip to content

Commit

Permalink
Tests: make sure temporary files are pre-closed
Browse files Browse the repository at this point in the history
Windows fails with a permission error if the temporary file is already
opened.

Fixes #501
  • Loading branch information
erlend-aasland committed Jul 9, 2024
1 parent 3aa509d commit fe6eb35
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
8 changes: 3 additions & 5 deletions test/test_eds.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions test/test_pdo.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest

import canopen
from .util import SAMPLE_EDS
from .util import SAMPLE_EDS, tmp_file


class TestPDO(unittest.TestCase):
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions test/util.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit fe6eb35

Please sign in to comment.