写pytest函数来检查输出到Python中的文件? [英] writing a pytest function to check outputting to a file in python?
问题描述
我询问了这个关于如何编写pytest来检查 stdout
中的输出的问题,并得到了一个解决方案。现在我需要写一个测试用例
来检查内容是否写入文件,并且内容是按照期望写入的。
例如:
$ b $ $ p $ $ code def defetetoafile():
file = open(output.txt,w)
file.write( hello \\\
)
file.write(world \\\
)
file.close()
虽然这似乎起作用,但我不认为这是理想的,尤其是硬编码。这些类型的 有 tmpdir fixture ,它将为您创建一个每个测试的临时目录。所以一个测试看起来像这样: 这里你重构的代码不会被硬编码,这是测试你的代码如何让你设计得更好的一个很好的例子。 I asked this question about how to write a pytest to check output in now a pytest function to check if it written: while this seems to work, I do not think this is ideal, especially hard-coding. how are these kind of There is the tmpdir fixture which will create you a per-test temporary directory. So a test would look something like this: 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屋!
现在是一个pytest函数来检查它是否写入:
$ p $ def $ test $ write $ $ b file = open(ouput.txt,'r')
expected =hello\\\
world\\\
assert expected == file.read()
测试函数是如何写入通常写入的文件的?
$ 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 \\\
'
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()
def test_writeToFile():
file = open("ouput.txt",'r')
expected = "hello\nworld\n"
assert expected==file.read()
test functions
of writing to a file usually written?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'