首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pytest夹具-参数化-调用夹具一次

Pytest夹具-参数化-调用夹具一次
EN

Stack Overflow用户
提问于 2019-07-09 02:20:19
回答 1查看 115关注 0票数 1

我有一个fixture,它返回端点的名称(传入)

名称是测试中设置的字符串。我在测试中每次都调用端点(参数化的),弄得一团糟,现在我不知道如何在每次不调用端点的情况下获得相同的功能。

基本上,我只需要调用端点一次,然后在该文件中的所有测试之间传递数据(理想情况下,不需要创建类并在测试中调用它。我有大约12个文件,每个文件都有类似的测试,我想减少样板文件。理想情况下,如果它可以在fixture/参数级别完成,而不需要全局变量。

这是我到目前为止所知道的:

代码语言:javascript
复制
@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
EN

回答 1

Stack Overflow用户

发布于 2019-07-10 05:23:39

使用作用域sessionreturn_endpoint创建为fixture,并在获取数据后将其存储在字典中。fixture不返回初始化函数,而是返回一个访问字典的函数。

代码语言:javascript
复制
@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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56940571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档