传递参数以在 Pytest 中实例化对象 [英] Passing arguments to instantiate object in Pytest

查看:154
本文介绍了传递参数以在 Pytest 中实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我想使用不同的输入参数集来实例化它,将结果对象上的属性与传入的值进行比较.

I have a class which I would like to instantiate using different sets of input parameters, comparing a property on the resultant object to a passed in value.

我在@pytest.fixture 上使用间接标志作为发送到类构造函数的参数.我正在尝试在构造函数中解压 kwargs.不成功.这是错误:

I am using the indirect flag on @pytest.fixture for the arguments which are sent to the class constructor. I am trying to unpack kwargs in the constructor. Unsuccesfully. This is the error:

TypeError: ** 之后的类型对象参数必须是映射,而不是 SubRequest

TypeError: type object argument after ** must be a mapping, not SubRequest

代码:

import pytest

class MyClass:
    def __init__(self, a):
        self.a = a

@pytest.fixture
def my_object(request):
    yield MyClass(**request)

# first element = arguments to MyClass, second element = value to compare test to
TEST_CASES = [({"a":1}, 1)]

@pytest.mark.parametrize("test, expected", TEST_CASES, indirect=["test"])
def test_1(my_object, test, expected):
    assert my_object.a == expected

我的目标是将对象参数及其测试值 TEST_CASES 放在一个结构中以便于检查

My goal is to have the object arguments and their test value TEST_CASES in one structure for easy inspection

推荐答案

我向您推荐了一个可行的示例.问题出在测试代码设计中.参数indirect 应该是True.应该按照 文档.并且fixture 在他的request.param 属性中获得了所有 参数.

I've suggest you a working example. Problem was in test code design. The parameter indirect should be True. Indirect parametrization with multiple fixtures should be done as described in docs. And fixture got all params in his request.param attribute.

import pytest


class MyClass:
    def __init__(self, a):
        self.a = a


@pytest.yield_fixture
def test_case(request):
    params, expected = request.param
    yield MyClass(**params), expected


# first element = arguments to MyClass, second element = value to compare test to
TEST_CASES = [({"a": 1}, 1)]


@pytest.mark.parametrize("test_case", TEST_CASES, indirect=True)
def test_1(test_case):
    my_object, expected = test_case
    assert my_object.a == expected

这篇关于传递参数以在 Pytest 中实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆