【问题标题】:All my test functions are loading a fixture that is in the conftest.py, even when they don't need it我所有的测试功能都在加载 conftest.py 中的一个夹具,即使他们不需要它
【发布时间】:2019-04-24 14:02:14
【问题描述】:

我的 conftest.py 中有 2 个不同的测试文件和一些固定装置:

1)“Test_dummy.py”包含这个函数:

def test_nothing():
    return 1

2)“Test_file.py”。其中包含此功能:

def test_run(excelvalidation_io):
    dfInput, expectedOutput=excelvalidation_io
    output=run(dfInput)
    for key, df in expectedOutput.items():
        expected=df.fillna(0)
        real=output[key].fillna(0)
        assert expected.equals(real)

3)“conftest.py”,其中包含这些固定装置:

def pytest_generate_tests(metafunc):
    inputfiles=glob.glob(DATADIR+"**_input.csv", recursive=False)
    iofiles=[(ifile, getoutput(ifile)) for ifile in 
    inputfiles]
    metafunc.parametrize("csvio", iofiles)
@pytest.fixture
def excelvalidation_io(csvio):
    dfInput, expectedOutput= csvio
    return(dfInput, expectedOutput)
@pytest.fixture
def client():
    client = app.test_client()
    return client

当我运行测试时,“Test_dummy.py”也尝试加载“excelvalidation_io”夹具并产生错误:

In test_nothing: function uses no argument 'csvio'

我曾尝试仅将夹具放在“Test_file.py”中,问题已解决,但我了解到在 conftest 文件中定位所有夹具是一个好习惯。

【问题讨论】:

标签: python pytest fixtures


【解决方案1】:

函数 pytest_generate_tests 是一个特殊函数,总是在执行任何测试之前调用,因此在这种情况下,您需要检查 metafunc 是否接受名为“csvio”的参数,否则什么也不做,如:

def pytest_generate_tests(metafunc):
    if "excelvalidation_io" in metafunc.fixturenames:
        inputfiles=glob.glob(DATADIR+"**_input.csv", recursive=False)
        iofiles=[(ifile, getoutput(ifile)) for ifile in 
        inputfiles]
        metafunc.parametrize("csvio", iofiles)

Source

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多