简体   繁体   English

在 requests_mock JSON 响应的 URI 端点中间使用通配符

[英]Using a wildcard in the middle of a URI endpoint for requests_mock JSON responses

I have some code that I would like to test, it is a fairly vanilla GET request wrapper, but the implementation of it requests data from the API multiple times with different IDs.我有一些我想测试的代码,它是一个相当普通的 GET 请求包装器,但它的实现使用不同的 ID 多次请求来自 API 的数据。

Adding mock JSON responses for the tests is problematic as there are hundreds of calls with these IDs and we want to test against one fixed response.为测试添加模拟 JSON 响应是有问题的,因为有数百个带有这些 ID 的调用,我们想针对一个固定响应进行测试。

The target URI looks like https://someurl.com/api/v1/id/1234/data?params目标 URI 看起来像https://someurl.com/api/v1/id/1234/data?params

The issue we are having is not wanting to add a line of code for every mock endpoint.我们遇到的问题是不想为每个模拟端点添加一行代码。

Eg.例如。 rather than have而不是有

mocker.get('https://someurl.com/api/v1/id/1234/data?params',
           json={},
           status_code=200)
mocker.get('https://someurl.com/api/v1/id/5678/data?params',
           json={},
           status_code=200)

I would like to implement some sort of wildcard matching, like this:我想实现某种通配符匹配,如下所示:

mocker.get(re.compile('https://someurl.com/api/v1/id/*/data?params'),
           json={},
           status_code=200)

This should be possible if I understand the docs correctly but this returns an error:如果我正确理解文档,这应该是可能的,但这会返回错误:

Failed: [undefined]requests_mock.exceptions.NoMockAddress: No mock address: GET https://someurl.com/api/v1/id/1234/data?params

That's because * and ?那是因为*? are qualifiers in the regular expression syntax .正则表达式语法中的限定符。 Once you adjust the pattern to escape the question mark ( \? ) and turn the star to a greedy match-any qualifier ( .* ), things should work as expected:一旦您调整模式以转义问号( \? )并将星号变为贪婪匹配任何限定符( .* ),事情应该按预期工作:

>>> requests_mock.get(
...     re.compile(r'https://someurl.com/api/v1/id/.*/data\?params'),
...     json={},
...     status_code=200
... )
>>> requests.get('https://someurl.com/api/v1/id/1234/data?params').status_code
200
>>> requests.get('https://someurl.com/api/v1/id/lorem-ipsum-dolor-sit-amet/data?params').status_code
200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM