如果Python单元测试使用无限循环测试程序,则退出

2024-06-18 11:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python Unittest测试一些函数。如果我的程序有一个无限循环,我不知道如何退出该测试。 我尝试了timeout decorator和wrapt timeout decorator,但两者都不起作用。我想要一个Windows中的解决方案。 也许我必须终止处理单元测试的过程,你认为呢


Tags: 函数程序过程windowstimeoutdecorator单元测试unittest
1条回答
网友
1楼 · 发布于 2024-06-18 11:23:36

我们到了! 这两个测试通过(test_loop_infinite和test_loop_finite)

询问任何问题:

import unittest
import time
import threading
import ctypes


def my_fct(param):
    print("Start my loop function")
    if param:
        print("Params make my function is infinite loop")
        while True:
            print("Looping...")
            time.sleep(1)
    else:
        print("Params make my function return")
        return


def terminate_thread(thread):
    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class Test(unittest.TestCase):
    def raise_loop(self, timeout, fct, args):
        x = threading.Thread(target=fct, args=args)
        t0 = time.time()
        x.start()
        time.sleep(timeout)
        if x.is_alive():
            terminate_thread(x)
            raise Exception("TimeOut loop")

    def test_loop_infinite(self):
        with self.assertRaises(Exception):
            self.raise_loop(2, my_fct, (True, ))

    def test_loop_finite(self):
        self.raise_loop(2, my_fct, (False, ))
    

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

相关问题 更多 >