gpt4 book ai didi

python - 使用异常参数列表测试 python 函数

转载 作者:行者123 更新时间:2023-11-28 20:38:48 25 4
gpt4 key购买 nike

我对测试一无所知,所以需要你的帮助。

得到了一个不时更改的python函数。还有一个参数列表,该函数应该无一异常(exception)地处理这些参数。所以问题 - 如何为此进行正确的简单测试。

我需要类似的东西

for arg in args:
cmd = 'python script.py %s' % arg
p = subprocess.Popen(cmd, shell = True,
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
output, err = p.communicate()
if err:
print arg
print err

用这样的自写脚本可以吗,或者有什么特殊的模块吗?

或者最好的处理方法是什么?

最佳答案

理想情况下,模块 script.py 包含一个函数 main(),当您将 script.py 作为脚本调用时,该函数会被调用,用惯用的成语

import sys

def main(arg1, arg2, arg3):
print(arg1, arg2, arg3)
return 42

if __name__ == "__main__":
main(*sys.argv[1:])

在这种情况下,您可以简单地导入函数 main 并进行测试,而无需所有子进程的麻烦:

from script import main as testsubject

assert testsubject(1, 2, 3) == 42

如果 script.py 不在 python 搜索路径中,您可能需要手动添加它:

import sys
sys.path.append("/path/to/folder/containing/script.py")

from script import main

作为标准库的一部分,有一个名为 unittest 的包,专门用于测试此类功能,并带有可读的文档,因此我强烈建议您尝试一下。

使用 uittest,测试可能如下所示:

import unittest

import script

class Test_Script(unittest.TestCase):

def test_return_value(self):
answer = script.main(1, 2, 3)
self.assertEqual(answer, 42)

if __name__ == "__main__":
unittest.main()

编辑添加:

如果你的函数没有返回值,而你只想知道你的函数是否抛出异常,你的测试函数可以简单地写成这样

    def test_runs_without_exception(self):
script.main(1, 2, 3)

如果 script.main() 抛出异常,则 unittest 将捕获该异常并打印适当的失败消息。

如果您只想简单地测试单个脚本,那么使用 unittest 可能有点矫枉过正,您可以使用更简单的方法

import time

import script

try:
sript.main(1, 2, 3)
except Exception as e:
print("An Exception occured!")
with open("script_log.txt", "a") as logfile:
logfile.write(str(time.time()) + "\t" + str(e))
raise e
else:
print("Everything is fine.")

如果您可以控制 script.py,您可能希望直接在 script.py 中包含一些日志记录工具。在这种情况下,您可能需要查看包 logging

关于python - 使用异常参数列表测试 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42371679/

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