I am working on a project that makes GET and POST API calls. These are performed using the request.Session package. The API calls are made in many Classes.
I'm writing a test which will execute the main code but when it comes to a specific class I want to add basic authentication to the GET or POST requests.
My idea was to use mocking. I would a patch the request.Session call, add the authentication to the arguments, execute the call, and return the response back to the original call in that specific class.
The problem is I only want to do this for a specific class and not every place that request.Session is called during the execution of the main code. I cannot modify the class I'm aiming for as it belongs to a different library.
What I have tried is using a decorator for the main call which includes patching of that specific package. In this example I am only printing the arguments to see how far I could get. The problem being is I cannot modify the patch to only capture the FirstClass call:
from unittest.mock import patch
import requests
class FirstClass:
def make_request(self, url, headers=None):
with requests.Session() as session:
response = session.get(url, headers=headers)
return session
class SecondClass:
def make_request(self, url, headers=None):
with requests.Session() as session:
session.get(url, headers=headers)
return session
def decorator(func):
def decorated_function(class_name, url, **kwargs):
with patch("FirstClass.make_request.requests.Session.get"):
print("Testing")
return func(class_name, url, **kwargs)
return decorated_function
first_class = FirstClass()
second_class = SecondClass()
@decorator
def test_func(class_name, url, **kwargs):
class_name.make_request(url, **kwargs)
test_func(first_class, "https://httpbin.org/status/300", headers={'User-Agent': 'MyApp/1.0'})
test_func(second_class, "https://httpbin.org/status/300", headers={'User-Agent': 'MyApp/1.0'})
Maybe I'm missing something here, or just being silly and there's an easier way of doing it. Any advice would be appreciated.