Skip to content

Commit 55d870e

Browse files
Tests: make sure temporary files are pre-closed (#507)
Windows fails with a permission error if the temporary file is already opened. Fixes #501
1 parent 3aa509d commit 55d870e

File tree

3 files changed

+14
-8
lines changed

3 files changed

+14
-8
lines changed

test/test_eds.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import canopen
55
from canopen.objectdictionary.eds import _signed_int_from_hex
66
from canopen.utils import pretty_index
7-
from .util import SAMPLE_EDS, DATATYPES_EDS
7+
from .util import SAMPLE_EDS, DATATYPES_EDS, tmp_file
88

99

1010
class TestEDS(unittest.TestCase):
@@ -223,10 +223,9 @@ def test_comments(self):
223223
""".strip())
224224

225225
def test_export_eds_to_file(self):
226-
import tempfile
227226
for suffix in ".eds", ".dcf":
228227
for implicit in True, False:
229-
with tempfile.NamedTemporaryFile(suffix=suffix) as tmp:
228+
with tmp_file(suffix=suffix) as tmp:
230229
dest = tmp.name
231230
doctype = None if implicit else suffix[1:]
232231
with self.subTest(dest=dest, doctype=doctype):
@@ -235,9 +234,8 @@ def test_export_eds_to_file(self):
235234

236235
def test_export_eds_to_file_unknown_extension(self):
237236
import io
238-
import tempfile
239237
for suffix in ".txt", "":
240-
with tempfile.NamedTemporaryFile(suffix=suffix) as tmp:
238+
with tmp_file(suffix=suffix) as tmp:
241239
dest = tmp.name
242240
with self.subTest(dest=dest, doctype=None):
243241
canopen.export_od(self.od, dest)

test/test_pdo.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import unittest
22

33
import canopen
4-
from .util import SAMPLE_EDS
4+
from .util import SAMPLE_EDS, tmp_file
55

66

77
class TestPDO(unittest.TestCase):
@@ -64,14 +64,13 @@ def test_pdo_save(self):
6464
self.node.rpdo.save()
6565

6666
def test_pdo_export(self):
67-
import tempfile
6867
try:
6968
import canmatrix
7069
except ImportError:
7170
raise unittest.SkipTest("The PDO export API requires canmatrix")
7271

7372
for pdo in "tpdo", "rpdo":
74-
with tempfile.NamedTemporaryFile(suffix=".csv") as tmp:
73+
with tmp_file(suffix=".csv") as tmp:
7574
fn = tmp.name
7675
with self.subTest(filename=fn, pdo=pdo):
7776
getattr(self.node, pdo).export(fn)

test/util.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1+
import contextlib
12
import os
3+
import tempfile
24

35

46
DATATYPES_EDS = os.path.join(os.path.dirname(__file__), "datatypes.eds")
57
SAMPLE_EDS = os.path.join(os.path.dirname(__file__), "sample.eds")
8+
9+
10+
@contextlib.contextmanager
11+
def tmp_file(*args, **kwds):
12+
with tempfile.NamedTemporaryFile(*args, **kwds) as tmp:
13+
tmp.close()
14+
yield tmp

0 commit comments

Comments
 (0)