python - Pytest Fixtures - 参数化 - 调用 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
解决方案
创建return_endpoint
为具有范围的夹具,session
并在获取数据后将数据存储在字典中。夹具不返回初始化函数,而是一个访问字典的函数。
@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()
是可变的,那么您可能会在测试之间创建不需要的依赖关系。您可以通过返回对象的(深层)副本来避免这种情况。您可以为此使用复制模块。
推荐阅读
- android - Android Jsoup spinner 数据检索
- spring - Spring with Kotlin - 开放类中的最终方法无法访问成员变量
- python - 如何从合并表创建 MultiIndex 数据框?
- r - 如何生成 1000 个元素为随机数的 2x2 矩阵?
- excel - Excel vba查找值列表之一的单元格地址
- lucene.net - Lucene.Net 4.8.0 是否支持 Azure Blob Storage 创建索引?
- nio - okhttp 是否有使用异步套接字实现 http2 的计划?
- azure - Azure AAD 门户注册应用清单无法更新
- javascript - selectize.js 仅在与 vue 的 v-for 一起使用时操作一个选项卡的 dom
- c# - 如何在 Unity 3d 中使用 RaycastHit.Point