pytest:在线程中运行

10 投票
1 回答
13805 浏览
提问于 2025-04-18 04:34

一个名为 pytest_demo.py 的 Python 文件:

import pytest
import threading

@pytest.mark.test
class TestDemo():
    def test_demo_false(self):
        assert False

    def test_demo_true(self):
        assert True

    def test_demo_thread_true(self):
        thread1 = MyThread(True)
        thread1.start()

    def test_demo_thread_false(self):
        thread1 = MyThread(False)
        thread1.start()


class MyThread(threading.Thread):
    def __init__(self, flag):
        threading.Thread.__init__(self)
        self.flag = flag

    def run(self):
        print "Starting "
        assert self.flag


if __name__ == "__main__":
    pytest.main(['-v', '-m', 'test', 'pytest_demo.py'])

运行 "python pytest_demo.py" 后的输出结果:

pytest_demo.py:8: TestDemo.test_demo_false FAILED
pytest_demo.py:11: TestDemo.test_demo_true PASSED
pytest_demo.py:14: TestDemo.test_demo_thread_true PASSED
pytest_demo.py:18: TestDemo.test_demo_thread_false PASSED

在这个线程中,为什么 TestDemo.test_demo_thread_false 会显示为通过(PASSED)呢?

1 个回答

10

因为AssertionError是在一个单独的线程中出现的。你的test_demo_thread_false方法并没有进行任何断言,它只是启动了一个新的线程,而且每次都能成功启动。

撰写回答