Skip to main content
 首页 » 编程设计

python之Pytest 在与其他线程一起运行时挂起

2025年01月19日9telwanggs

我正在尝试在运行线程后从 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. 您也可以将您的代码与测试代码分开。

让我们说:

文件.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) 

测试文件.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)