gpt4 book ai didi

python - 使用 Pytest 测试 Python 程序

转载 作者:行者123 更新时间:2023-12-04 16:45:29 25 4
gpt4 key购买 nike

TI 对 Python 编程很陌生,并且对使用 Pytest 进行测试有疑问。概括地说,我有一个程序,它接受 3 条用户输入并最终生成一个文本文件。对于我的测试,我想基本上比较我的程序输出的文件和它应该是什么。
现在,我不确定如何进行测试。程序本身没有参数,只是依赖于 3 条用户输入,我将使用monkeypatch 来模拟。我是否创建了一个名为 program_test.py 的新 python 文件并在此处具有调用原始程序的方法?我已经尝试过这个,但是我在实际调用原始程序和发送模拟输入时遇到了麻烦。或者,我是否在原始程序中进行了测试(这对我来说没有多大意义)。
我想要这样的东西:

import my_program

def test_1():
inputs = iter(['input1', 'input2', 'input3'])
monkeypatch.setattr('builtins.input', lambda x: next(inputs))
my_program
# now do some assertion with some file comparison
# pseudocode
assert filecompare.cmp(expectedfile, actualfile)
这似乎只是在运行原始程序,我认为它与导入语句有关,即它从不运行 test_1(),可能是因为我从不调用它?任何帮助,将不胜感激!

最佳答案

无需提供您的 my_program代码很难说发生了什么。
既然你提到了 import问题,我猜你没有定义 main()if __name__ == "__main__" .
这是一个关于如何测试的小例子。
首先,构建您的 my_programmain包含代码的函数然后添加 if __name__ == "__main__"这将允许您运行 main函数如果 my_program直接执行还要导入my_program作为其他文件的模块(不运行它,有关更多信息,请参阅: What does if name == "main": do? )。
我的程序:

def main():
x = input()
y = input()
z = input()
with open("test", "w") as f_out:
f_out.write(f"{x}-{y}-{z}")


if __name__ == "__main__":
main()
现在您可以创建一个 test.py文件并测试 main my_program 的功能:
import os
import filecmp
import my_program


def test_success(monkeypatch):
inputs = ["input1", "input2", "input3"]
monkeypatch.setattr("builtins.input", lambda: next(iter(inputs)))
my_program.main()
with open("expected", "w") as f_out:
f_out.write("-".join(inputs))
assert filecmp.cmp("expected", "test")
os.remove("test")
os.remove("expected")


def test_fail(monkeypatch):
inputs = ["input1", "input2", "input3"]
monkeypatch.setattr("builtins.input", lambda: next(iter(inputs)))
my_program.main()
with open("expected", "w") as f_out:
f_out.write("something-else-test")
assert not filecmp.cmp("expected", "test")
os.remove("test")
os.remove("expected")

This is an example so I used os.remove to delete the files. Ideally you would define fixtures in your tests to use tempfile and generate random temporary files which will be automatically deleted after your tests.

关于python - 使用 Pytest 测试 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70090448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com