Boo*_*aKa 5 python multithreading pytest
我试图在运行线程后从 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()
Run Code Online (Sandbox Code Playgroud)
但 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
Run Code Online (Sandbox Code Playgroud)
它就这样挂着,直到我强行退出它。有什么办法可以使这项工作?
有两件事值得一提:
可以说:
文件.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)
Run Code Online (Sandbox Code Playgroud)
测试文件.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)
Run Code Online (Sandbox Code Playgroud)