当 运行 个其他线程时 Pytest 挂起

Pytest hangs when running with other threads

我正在尝试 运行 在 运行 一个线程之后从 python 中进行 pytest, 这是一个简单的例子:

import time
import threading
import pytest


class A(object):
    def __init__(self):
        self._thread_a = threading.Thread(target=self.do_a)
        self._thread_a.start()
        pytest.main()

    def do_a(self):
        print "a"
        time.sleep(2)
        self.do_a()


if __name__ == "__main__":
    a = A()

但是 pytest 一直挂起。这是输出的样子:

============================= test session starts ==============================
platform darwin -- Python 2.7.10, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
metadata: {'Python': '2.7.10', 'Platform': 'Darwin-17.3.0-x86_64-i386-64bit', 'Packages': {'py': '1.5.2', 'pytest': '3.3.2', 'pluggy': '0.6.0'}, 'Plugins': {'session2file': '0.1.9', 'celery': '4.0.0','html': '1.16.1', 'metadata': '1.5.1'}}
rootdir: /Users/path/to/root/dir, inifile:
plugins: session2file-0.1.9, metadata-1.5.1, html-1.16.1, celery-4.0.0

它就这样一直挂着,直到我强行退出它。 有什么方法可以使它起作用吗?

有两点值得一提:

  1. 如果您的代码已完成某项操作,您可能希望停止该线程。
  2. 您也可以将您的代码与测试代码分开。

假设:

file.py

import time
import threading

class A(object):
    def __init__(self):
        self._thread_a = threading.Thread(target=self.do_a)
        self._thread_a.daemon = True
        self._thread_a.start()

    def do_a(self):
        print "a"
        time.sleep(2)
        self.do_a()

    def stop(self, timeout):
        self._thread_a.join(timeout)

test_file.py

import pytest

from .file import A

@pytest.fixture()
def a():
    return A()


def test_sth(a):
    a.start()
    print('I can do sth else')
    a.stop(timeout=1)