Ask Your Question
2

How can overlapping URLs be dealt with in requests_mock?

asked 2022-01-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-01-23 01:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-22 11:00:00 +0000

Seen: 7 times

Last updated: Jan 23 '23