如果测试文件具有设置和拆卸部分,如何使用pytest并行执行测试

时间:2020-07-14 07:47:45

标签: pytest

我的测试脚本如下

@pytest.fixture(scope="Module", Autouse="True")
def setup_test():
    ....................
    yield
    ............

def test_1()
    ...............

def test_2()
    ...............

def test_3()
 ...............

顺序脚本执行正常。 (首次测试设置-> Test1-> Test2-> Test3->拆卸) pytest。

如何并行运行脚本执行,如:-首次测试设置->所有测试用例并行->拆除?

如果我将-n选项与pytest执行一起使用,它甚至会在setup节完成之前并行触发所有测试,并在所有测试用例之后执行拆解节。

我尝试提供--dist=load选项,将设置和拆卸文件放入conftest文件等。 在我的情况下没有任何效果。

2 个答案:

答案 0 :(得分:0)

尝试--dist = loadscope

0.0.0.0/0

输出-

import pytest
import logging
logging.basicConfig(format='%(message)s')

@pytest.fixture(scope="session", autouse=True)
def setup_test():
    logging.warning("Setup")
    yield
    logging.warning("Tear down")

def test_1():
    logging.warning("Test1")

def test_2():
    logging.warning("Test2")

def test_3():
    logging.warning("Test3")

答案 1 :(得分:0)

我尝试了--dist = loadscope,它按顺序执行测试,而不是并行执行

import logging
import time
import pytest
@pytest.fixture(scope="session", autouse="True")
def create_test_setup():
    logging.info("Setup start")
    time.sleep(10)
    logging.info("Setup ends")
    yield
    logging.info("Tear down start")
    time.sleep(10)
    logging.info("Tear down ends")
def test_1():
    logging.info("Test1 start")
    time.sleep(10)
    logging.info("Test1 ends")
def test_2():
    logging.info("Test2 start")
    time.sleep(20)
    logging.info("Test2 ends")
def test_3():
    logging.info("Test3 start")
    time.sleep(30)
    logging.info("Test3 end")
def test_4():
    logging.info("Test4 start")
    time.sleep(40)
    logging.info("Test4 ends")


pytest -n 4 --dist=loadscope
============================= test session starts ==============================
platform linux -- Python 3.6.8, pytest-5.2.0, py-1.9.0, pluggy-0.13.1 -- 
.......................................
...................................
scheduling tests via LoadScopeScheduling
test.py::test_1
test.py::test_2
test.py::test_3
test.py::test_4
======================== 4 passed in 136.40s (0:02:16) =========================
Process finished with exit code 0
[gw0] [ 25%] PASSED test.py::test_1 2020-07-14 19:10:29,359 - INFO [root] -  test.py:20 - Test1 start
2020-07-14 19:10:39,363 - INFO [root] -  test.py:22 - Test1 ends
[gw0] [ 50%] PASSED test.py::test_2 2020-07-14 19:10:39,377 - INFO [root] -  test.py:26 - Test2 start
2020-07-14 19:10:59,397 - INFO [root] -  test.py:28 - Test2 ends
[gw0] [ 75%] PASSED test.py::test_3 2020-07-14 19:10:59,413 - INFO [root] -  test.py:32 - Test3 start
2020-07-14 19:11:29,436 - INFO [root] -  test.py:34 - Test3 end
[gw0] [100%] PASSED test.py::test_4 2020-07-14 19:11:29,450 - INFO [root] -  test.py:38 - Test4 start
2020-07-14 19:12:09,486 - INFO [root] -  test.py:40 - Test4 ends
2020-07-14 19:12:09,576 - INFO [root] -  test.py:14 - Tear down start
2020-07-14 19:12:19,586 - INFO [root] -  test.py:16 - Tear down ends