繁体   English   中英

使用从数据库加载的夹具参数化pytest

[英]Parameterize pytest using fixture loaded from database

我正在尝试使用pytest来获取要运行的套件的ID,从数据库中加载套件,然后以参数化方式生成测试用例。 下面的代码显示了我想做什么的要点,但是fixture 'case' not found带有fixture 'case' not found错误。

如何使用从数据库查找返回的ID参数化case

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_harness.settings")
application = get_wsgi_application()

from unitrunner.models import TestSuiteModel as SuiteModel


def pytest_addoption(parser):
    parser.addoption("--suite", action="append", default=[],
        help="Suite ID to evaluate")


def pytest_generate_tests(metafunc):
    if 'suite' in metafunc.fixturenames:
        suite_id = metafunc.fixturenames['suite']

        this_suite = SuiteModel.objects.get(id=suite_id)
        test_cases = this_suite.testCases.all()

        metafunc.parametrize(
            "case",
            [item.id for item in test_cases]
        )


def test_case(case):
    print(case)

    assert False

fixture 'case' not found意味着fixture 'case' not found进行参数化:

metafunc.parametrize(
    "case",
    [item.id for item in test_cases]
)

没有执行。 这并不test_case ,因为您没有在test_case使用夹具suite ,因此, if 'suite' in metafunc.fixturenames test_case if 'suite' in metafunc.fixturenames将返回False 例如,如果您实际在test_case使用固定装置, test_case

@pytest.fixture
def suite():
    pass

@pytest.mark.usefixtures('suite')
def test_case(case):
    print(case)

    assert False

测试将正确设置参数。 顺便说一句,在我的示例中, suite夹具正在用作标记,应该将其更好地重做:

def pytest_generate_tests(metafunc):
    try:
        suite_id = getattr(metafunc.function, 'suite')
    except AttributeError:  # no suite marker
        pass
    else:
        this_suite = SuiteModel.objects.get(id=suite_id)
        test_cases = this_suite.testCases.all()

        metafunc.parametrize(
            "case",
            [item.id for item in test_cases]
        )

现在,只需标记相关测试:

@pytest.mark.suite(1)
def test_case(case):
    assert case == 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM