Overlapping URLs in requests_mock can be dealt with by using the adapter
parameter of the register_uri
method. The adapter
parameter allows you to register multiple responses for the same URL based on specific request parameters.
For example, if you have two endpoints that respond to the same URL but with different query parameters, you can register the responses as follows:
import requests_mock
with requests_mock.Mocker() as m:
m.register_uri('GET', 'https://example.com/resource?id=1', text='Response 1')
m.register_uri('GET', 'https://example.com/resource?id=2', text='Response 2')
In this case, requests to https://example.com/resource?id=1
will return Response 1
, and requests to https://example.com/resource?id=2
will return Response 2
.
You can also use regular expressions to match URLs with different patterns. For example, if you have two endpoints with URLs that start with the same path but have different query parameters or paths, you can register the responses as follows:
import requests_mock
import re
with requests_mock.Mocker() as m:
m.register_uri('GET', re.compile('https://example.com/resource/.*'), text='Response 1')
m.register_uri('GET', re.compile('https://example.com/other-resource/.*'), text='Response 2')
In this case, requests to URLs that match https://example.com/resource/.*
will return Response 1
, and requests to URLs that match https://example.com/other-resource/.*
will return Response 2
.
Asked: 2022-01-22 11:00:00 +0000
Seen: 7 times
Last updated: Jan 23 '23