簡體   English   中英

當燒瓶服務器運行另一個線程時,Pytest掛起

[英]Pytest hangs when a flask server runs another thread

我正在使用Python3,Flask 0.12和Pytest 3.0.7。

我有一個類似的燒瓶應用程序:

class AppInitializer:
    def __init__(self):
        pass

    @staticmethod
    def __function_to_be_refreshed():
        while True:
            try:
                time.sleep(5)
            except Exception as e:
                logger.exception(e)


    def create_app(self):
        daemon_thread = threading.Thread(target=self.__function_to_be_refreshed)
        daemon_thread.daemon = True
        daemon_thread.start()
        atexit.register(daemon_thread.join)
        app_ = Flask(__name__)
        return app_


app_initializer = AppInitializer()
app = app_initializer.create_app()

我正在嘗試使用pytest測試此應用程序,如下所示:

import unittest

import pytest


class TestCheckPriceRequestAPI(unittest.TestCase):
    def setUp(self):
        self.app = api.app.test_client()

    def test_random(self):
        pass

當我使用pytest運行此測試時,此測試(以及所有其他測試)成功運行,但pytest掛起。 如何停止正在運行的pytest進程(或者殺死守護進程線程)?

join命令僅意味着線程將等待直到線程完成,但不會完成。 要以無限循環結束線程,您可以這樣:

class AppInitializer:
    def __init__(self):
        self._run = True
        self._daemon_thread = None

    def __function_to_be_refreshed(self):
        while self._run:
            try:
                time.sleep(5)
            except Exception as e:
                logger.exception(e)

    def __shutdown(self):
        self._run = False
        if self._daemon_thread:
            self._daemon_thread.join()

    def create_app(self):
        self._daemon_thread = threading.Thread(target=self.__function_to_be_refreshed)
        ...
        atexit.register(self.__shutdown)
        ...

暫無
暫無

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

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