getsentry / responses

A utility for mocking out the Python Requests library.
Apache License 2.0
4.08k stars 347 forks source link

Capture Group Support #718

Open jcampbell05 opened 1 month ago

jcampbell05 commented 1 month ago

Describe the bug

It would be great to be able to use capture groups in the Regexp and be able to read their value in the request passed to the callbacks, currently we have to store the regexp in a common place and parse twice.

Additional context

No response

Version of responses

latest

Steps to Reproduce

N/a

Expected Result

N/a

Actual Result

N/a

markstory commented 1 month ago

How would you expect to define and use the captured groups? Perhaps an example of what you want to do but cannot do easily today.

jcampbell05 commented 1 month ago

How would you expect to define and use the captured groups? Perhaps an example of what you want to do but cannot do easily today.

For example I would love to be able to do this:

def fetch_invoice(request):
      print(f"Invoice {request.match.invoice_id}")

invoice_regexp = f"https://{config.CHARGEBEE_SITE}.chargebee.com/api/v2/invoices/(?P<invoice_id>.+)"

self.responses.add_callback(
                responses.GET,
                re.compile(invoice_regexp),
                callback=fetch_invoice
)

Right now I have to write it like so:

def fetch_invoice(request):
            match = re.search(invoice_regexp, request.url)
            invoice_id = match.group("invoice_id")

invoice_regexp = f"https://{config.CHARGEBEE_SITE}.chargebee.com/api/v2/invoices/(?P<invoice_id>.+)"

self.responses.add_callback(
                responses.GET,
                re.compile(invoice_regexp),
                callback=fetch_invoice
)