【问题标题】:Parameterize pytest using fixture loaded from database使用从数据库加载的夹具参数化 pytest
【发布时间】:2018-04-17 18:16:47
【问题描述】:

我正在尝试使用 pytest 获取一个 id 以运行套件,从数据库加载套件,然后以参数化方式生成测试用例。下面的代码显示了我想要做的事情的要点,但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

【问题讨论】:

    标签: python django testing pytest parameterized-tests


    【解决方案1】:

    fixture 'case' not found 表示参数化没有发生:行

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

    没有被执行。这并不奇怪,因为您没有在test_case 中使用夹具suite,因此if 'suite' in metafunc.fixturenames 将返回False。如果你实际使用test_case中的fixture,例如:

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2023-03-03
      • 1970-01-01
      • 2022-12-08
      相关资源
      最近更新 更多