簡體   English   中英

Python unittest - 如果它使用無限循環測試程序則退出

[英]Python unittest - exit if it tests an program with infinite loop

我想用 Python 單元測試測試一些 function。 如果我的程序有一個無限循環,我不知道如何退出該測試。 我嘗試使用 timeout-decorator 和 wrapt-timeout-decorator,但這些都不起作用。 我想要 Windows 中的解決方案。 也許我必須殺死處理單元測試的進程,你怎么看?

我們到了! 這里兩個測試通過(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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM