前言

  • 今天在写pytest接口框架时发现conftest.py文件scope='session'时被重复调用了,但是scope='session'时整个session只运行一次,为什么会出现多次调用呢?满脸问号。。。。
  • 以为是自己记忆错误,反复确认scope域是否正确,均没有错误
  • 经过半小时排查,观察到控制台输出在用例RERUN时,conftest.py文件内自动运行的方法会被运行
  • 开始问题回放,发现一个.py文件有多个测试方法时最后一个方法失败重跑时会再执行一次conftest.py文件内的方法
  • 有大佬可以解释下吗

1、问题回放

1.1、pytest.ini文件内容

addopts = -v -s --tb=short --clean-alluredir --reruns 2 --reruns-delay 1
testpaths = case_test_py/mytest/

1.2、conftest.py文件内容

import random
import pytest

@pytest.fixture(scope='session', autouse=True)
def api_client():
    a = random.randint(1, 100)
    test_str = 'test conftest set token ' + str(a)
    print(test_str)
    yield
    print('结束')

1.3、测试文件内容

class TestBug:

    def test_01(self):
        assert 1 == 2

    def test_02(self):
        assert 1 == 1

    def test_03(self):
        assert 1 == 2

1.4、运行后


case_test_py/mytest/test_bug.py::TestBug::test_01 test conftest set token 82
RERUN
case_test_py/mytest/test_bug.py::TestBug::test_01 RERUN
case_test_py/mytest/test_bug.py::TestBug::test_01 FAILED
case_test_py/mytest/test_bug.py::TestBug::test_02 PASSED
case_test_py/mytest/test_bug.py::TestBug::test_03 结束
RERUN
case_test_py/mytest/test_bug.py::TestBug::test_03 test conftest set token 34
结束
RERUN
case_test_py/mytest/test_bug.py::TestBug::test_03 test conftest set token 44
结束
FAILED

2、解决办法

注释rerun后发现运行正常
目前只能注释rerun或者保证最后一个方法最后一个用例的断言不会出错

文章目录