pytest:在线程中运行

Lei*_*Gao 7 python multithreading pytest

一个名为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'])
Run Code Online (Sandbox Code Playgroud)

运行后输出"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
Run Code Online (Sandbox Code Playgroud)

在线程中,为什么TestDemo.test_demo_thread_false被通过?

rad*_*rba 6

因为AssertionError在一个单独的线程中引发.你的test_demo_thread_false方法没有断言任何东西,它只是产生一个新的线程,它总是成功地做到了.