我正在尝试为将数据写入CSV文件的功能编写单元测试。为此,我想使用tempfile.NamedTemporaryFile
写入一个命名的临时文件,然后再次打开它,据我所知,在Unix平台上应该可以做到这一点。
但是,如果我尝试此测试,
import csv
import tempfile
def write_csv(csvfile):
writer = csv.DictWriter(csvfile, fieldnames=['foo', 'bar'])
writer.writeheader()
writer.writerow({'foo': 1, 'bar': 2})
def test_write_csv():
with tempfile.NamedTemporaryFile(mode='w') as csvfile:
write_csv(csvfile)
with open(csvfile.name) as csvfile:
reader = csv.DictReader(csvfile)
我得到一个FileNotFoundError
:
> pytest csvtest.py -s
======================================= test session starts ========================================
platform darwin -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /Users/kurtpeek/Documents/Scratch
collected 1 item
csvtest.py F
============================================= FAILURES =============================================
__________________________________________ test_write_csv __________________________________________
def test_write_csv():
with tempfile.NamedTemporaryFile(mode='w') as csvfile:
write_csv(csvfile)
> with open(csvfile.name) as csvfile:
E FileNotFoundError: [Errno 2] No such file or directory: '/var/folders/fr/7gjx_3js67xg0pjxz6sptktc0000gn/T/tmpgml8_fwf'
csvtest.py:16: FileNotFoundError
===================================== 1 failed in 0.03 seconds =====================================
我尝试了各种替代方法,例如尝试在与写入文件相同的with
块中打开文件(在这种情况下,我得到一个未打开以供读取的错误),以{{1 }}模式(在这种情况下,'rw'
不允许我写它)。
如何将CSV写入临时文件并在单元测试中再次读取?
答案 0 :(得分:4)
如果要在关闭后保留临时文件,则需要传递 val wireMockServer = new WireMockServer(
wireMockConfig().port(API_PORT).proxyVia(PROXY_HOST, PROXY_PORT)
)
wireMockServer.start()
WireMock.configureFor("localhost", API_PORT)
wireMockServer.stubFor(
put(anyUrl())
.willReturn(
aResponse()
.withStatus(201)
// .proxiedFrom(API_HOST)
)
)
。从您链接的tempfile.NamedTemporaryFile
的文档中:
如果 delete 为true(默认设置),则文件将在关闭后立即删除。
然后您就可以这样做:
delete=False
答案 1 :(得分:1)
一旦离开csvfile
,with
的上下文就会消失,临时文件将被删除。您打算这样做吗?
def test_write_csv():
with tempfile.NamedTemporaryFile(mode='w') as csvfile:
write_csv(csvfile)
with open(csvfile.name) as csvfile:
reader = csv.DictReader(csvfile)
可能不是,因为您重复使用了csvfile
。如果您打算保留文件,则可以通过delete=false
csvfile = tempfile.NamedTemporaryFile(delete=False)
答案 2 :(得分:1)
with
块的执行结束时,文件被删除。因此,也许这不是最好的解决方案,但实际上它可以工作,因此您可以尝试一下:
def test_write_csv():
with tempfile.NamedTemporaryFile(mode='w') as csvfile:
write_csv(csvfile)
with open(csvfile.name) as csvfile:
reader = csv.DictReader(csvfile)