我问this有关如何编写pytest以检查stdout
中的输出并得到解决方案的问题。现在我需要写一个test case
,检查内容是否写入文件,内容是否按预期写入,例如:
def writetoafile():
file = open("output.txt",w)
file.write("hello\n")
file.write("world\n")
file.close()
现在是一个pytest函数来检查它是否写入:
def test_writeToFile():
file = open("ouput.txt",'r')
expected = "hello\nworld\n"
assert expected==file.read()
虽然这似乎有效,但我不认为这是理想的,特别是硬编码。这些test functions
写入文件通常是怎么写的?
有tmpdir fixture将创建一个per-test临时目录。所以测试看起来像这样:
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'
在这里,您重构代码也不是硬编码,这是测试代码如何使您更好地设计它的一个主要示例。
假设你在一个名为main.py
的文件中有这个“神奇”的软件:
"""
main.py
"""
def write_to_file(text):
with open("output.txt", "w") as h:
h.write(text)
if __name__ == "__main__":
write_to_file("Every great dream begins with a dreamer.")
要测试write_to_file
方法,您可以在名为test_main.py
的同一文件夹中的文件中编写类似的内容:
"""
test_main.py
"""
from unittest.mock import patch, mock_open
import main
def test_do_stuff_with_file():
open_mock = mock_open()
with patch("main.open", open_mock, create=True):
main.write_to_file("test-data")
open_mock.assert_called_with("output.txt", "w")
open_mock.return_value.write.assert_called_once_with("test-data")
我总是尽量避免将文件写入磁盘,即使它是专门用于我的测试的临时文件夹:实际上不接触磁盘会使测试更快,特别是如果您在代码中与文件进行大量交互。