写pytest函数来检查输出到Python中的文件? [英] writing a pytest function to check outputting to a file in python?

查看:551
本文介绍了写pytest函数来检查输出到Python中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我询问了这个关于如何编写pytest来检查 stdout 中的输出的问题,并得到了一个解决方案。现在我需要写一个测试用例来检查内容是否写入文件,并且内容是按照期望写入的。
例如:


$ b $ $ p $ $ code def defetetoafile():
file = open(output.txt,w)
file.write( hello \\\

file.write(world \\\

file.close()



现在是一个pytest函数来检查它是否写入:

$ p $ def $ test $ write $ $ b file = open(ouput.txt,'r')
expected =hello\\\
world\\\

assert expected == file.read()

虽然这似乎起作用,但我不认为这是理想的,尤其是硬编码。这些类型的测试函数是如何写入通常写入的文件的?

tmpdir fixture ,它将为您创建一个每个测试的临时目录。所以一个测试看起来像这样:

$ p $ def writetoafile(fname):
with open(fname,'w ')as fp:
fp.write('Hello \\\
')

def test_writetofile(tmpdir):
file = tmpdir.join('output.txt')
writetoafile(file.strpath)#或使用str(文件)
assert file.read()=='Hello \\\
'

这里你重构的代码不会被硬编码,这是测试你的代码如何让你设计得更好的一个很好的例子。


I asked this question about how to write a pytest to check output in stdout and got a solution. Now I need to write a test case, to check if the contents are written to the file and that the contents are written as expected eg:

def writetoafile():
   file = open("output.txt",w)
   file.write("hello\n")
   file.write("world\n")
   file.close()

now a pytest function to check if it written:

def test_writeToFile():
    file = open("ouput.txt",'r')
    expected = "hello\nworld\n"
    assert expected==file.read()

while this seems to work, I do not think this is ideal, especially hard-coding. how are these kind of test functions of writing to a file usually written?

解决方案

There is the tmpdir fixture which will create you a per-test temporary directory. So a test would look something like this:

def writetoafile(fname):
    with open(fname, 'w') as fp:
        fp.write('Hello\n')

def test_writetofile(tmpdir):
    file = tmpdir.join('output.txt')
    writetoafile(file.strpath)  # or use str(file)
    assert file.read() == 'Hello\n'

Here you're refactoring the code to not be hardcoded either, which is a prime example of how testing your code makes you design it better.

这篇关于写pytest函数来检查输出到Python中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆