Pytest Fixtures参数化调用Fixture On

2024-06-16 10:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个fixture返回端点作为该端点的名称(传入)

名称是测试中设置的字符串。我在测试中每次调用端点(参数化)都搞砸了,现在我不知道如何在每次都不调用端点的情况下让相同的功能正常工作。你知道吗

基本上,我只需要调用一次端点,然后在该文件中的所有测试之间传递数据(理想情况下不需要创建类并在测试中调用它之类的任何操作)。我有大约12个类似的测试文件,每个我想减少锅炉板。理想情况下,如果它可以在夹具/参数化水平上完成,没有全局变量。你知道吗

以下是我目前掌握的情况:

@pytest.mark.parametrize('field', [('beskrivelse'), ('systemId')])
def test_intgra_001_elevforhold_req_fields(return_endpoint, field):
    ep_to_get = 'get_elevforhold'
    ep_returned = return_endpoint(ep_to_get)
    apiv2 = Apiv2()
    apiv2.entity_check(ep_returned, field, ep_to_get, False)


@pytest.fixture()
def return_endpoint():

    def endpoint_initialisation(ep_name):
        apiv2 = Apiv2()
        ep_data = apiv2.get_ep_name(ep_name)
        response = apiv2.get_endpoint_local(ep_data, 200)
        content = json.loads(response.content)
        apiv2.content_filt(content)
        apiv2_data = content['data']

        return apiv2_data

    return endpoint_initialisation

Tags: toname名称fielddatagetreturndef
1条回答
网友
1楼 · 发布于 2024-06-16 10:15:05

创建return_endpoint作为具有作用域session的fixture,并在获取数据后将其存储在字典中。fixture不返回初始化函数,而是返回访问字典的函数。你知道吗

@pytest.mark.parametrize('field', [('beskrivelse'), ('systemId')])
def test_intgra_001_elevforhold_req_fields(return_endpoint, field):
    ep_to_get = 'get_elevforhold'
    ep_returned = return_endpoint(ep_to_get)
    apiv2 = Apiv2()
    apiv2.entity_check(ep_returned, field, ep_to_get, False)


@pytest.fixture(scope='session')
def return_endpoint():
    def endpoint_initialisation(ep_name):
        apiv2 = Apiv2()
        ep_data = apiv2.get_ep_name(ep_name)
        response = apiv2.get_endpoint_local(ep_data, 200)
        content = json.loads(response.content)
        apiv2.content_filt(content)
        apiv2_data = content['data']

        return apiv2_data

    ep_data = dict()
    def access(ep_name):
        try:
            return ep_data[ep_name]  # or use copy.deepcopy
        except KeyError:
            ep_data[ep_name] = endpoint_initialisation(ep_name)
            return ep_data[ep_name]  # or use copy.deepcopy

    return access

这里有一些警告。如果endpoint_initialisation()返回的对象是可变的,那么您可能会在测试之间创建不需要的依赖关系。可以通过返回对象的(深度)副本来避免这种情况。你可以用copy module来做这个。你知道吗

相关问题 更多 >