gpt4 book ai didi

针对潜在无限循环的 Python 单元测试

转载 作者:太空狗 更新时间:2023-10-30 00:30:34 25 4
gpt4 key购买 nike

我有一个 python 函数,如果传递的错误数据会陷入无限循环。我想编写一个单元测试来确认它可以优雅地处理错误的参数。问题当然是,如果它没有检测到错误的参数,它就不会返回。

使用线程来为这种类型的东西编写测试是否可以接受?

import threading, unittest
import mymodule

class CallSuspectFunctionThread(threading.Thread):
def __init__(self, func, *args):
self.func = func
self.args = args
super(CallSuspectFunctionThread, self).__init__()
def run(self):
self.func(*self.args)

class TestNoInfiniteLoop(unittest.TestCase):
def test_no_infinite_loop(self):
myobj = mymodule.MyObject()
bad_args = (-1,0)
test_thread = CallSuspectFunctionThread(mybj.func_to_test, *bad_args)
test_thread.daemon = True
test_thread.start()
# fail if func doesn't return after 8 seconds
for i in range(32):
test_thread.join(0.25)
if not test_thread.is_alive():
return
self.fail("function doesn't return")

我看到的唯一问题是,如果测试失败,我就会被这个额外的线程卡住,可能会消耗 cpu 和内存资源,同时执行其余的测试。另一方面,我已经修复了代码,这里回归的可能性非常小,所以我不知道是否包括测试是否重要。

最佳答案

您可以添加超时装饰器。最好将测试用例的逻辑与超时机制实现分开。这将使您的代码更具可读性和更易于维护。

参见 http://pypi.python.org/pypi/timeout.

关于针对潜在无限循环的 Python 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5664453/

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