[英]How to match number pattern in python's responses library
I am unit testing in Python (pytest, responses library - It's for an API project...).我在 Python 中进行单元测试(pytest,响应库 - 它用于 API 项目......)。 I am creating fake responses which have to match a request string.
我正在创建必须匹配请求字符串的虚假响应。 The only difference in those responses is the number in the middle of the string:
这些响应的唯一区别是字符串中间的数字:
responses.add(
GET,
'http://app/projects/1200979733003518/tasks?opt_pretty=false',
status=200,
body=json.dumps(res_t)
)
responses.add(
GET,
'http://app/projects/1200979733003526/tasks?opt_pretty=false',
status=200,
body=json.dumps(res_t)
)
responses.add(
GET,
'http://app/projects/1201345940827570/tasks?opt_pretty=false',
status=200,
body=json.dumps(res_t)
)
I want to get rid of the repetition.我想摆脱重复。 I tried using python's re.compile, my idea was to do something like this:
我尝试使用 python 的 re.compile,我的想法是做这样的事情:
responses.add(
GET,
re.compile('http://app/projects/\\[0-9]+/tasks?opt_pretty=false'),
status=200,
body=json.dumps(res_t)
)
It doesn't work.它不起作用。 Read the manual for re, but can't come up with a working solution.
阅读手册以获取重新,但无法提出可行的解决方案。 How can i achieve that the response matches any number in my strings at this position?
我怎样才能在这个 position 上实现响应匹配我的字符串中的任何数字?
If you just want to generate random values, you can use something like this:如果你只想生成随机值,你可以使用这样的东西:
id = ''.join(random.choices(string.digits, k=16))
responses.add(
GET,
f'http://app/projects/{id}/tasks?opt_pretty=false',
status=200,
body=json.dumps(res_t)
)
Or if you want to use know values, you can use something like Pytest Parametrize feature.或者,如果您想使用已知值,您可以使用Pytest 参数化功能。 That would look like this:
看起来像这样:
@pytest.mark.parametrize("id", ["123456789", "897654321", "654789123"])
def test_api(id):
...
responses.add(
GET,
f'http://app/projects/{id}/tasks?opt_pretty=false',
status=200,
body=json.dumps(res_t)
)
With parametrize, your test will run like in a "for loop" which every run, the id
will have a different given value.使用参数化,您的测试将像在“for 循环”中一样运行,每次运行时,
id
都会有不同的给定值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.