I'm having trouble mocking a function that resides inside a FastAPI endpoint handler. No matter what I've tried it doesn't seem to work. A brief explanation of what I'm trying to test. I have a single endpoint that receives a file and does a few things with it including uploading to an S3 bucket using Boto3. The call to boto is in it's own function which is the one I need to mock. I can easily mock it when calling the function directly but when using a FastAPI TestClient to call the endpoint it never works as expected.
# a_module/s3_upload.py
def s3_upload(bucket, filename, file):
client = boto3.client('s3')
client.put_object(Bucket="a-bucket" Key=filename, body=file)
# endpoints/route_file.py
from a_module import s3_upload
@app.put("/")
def route_file(file, filename):
check_valid_file()
s3_upload()
@pytest.fixture
def client():
yield TestClient(app)
# tests/test_routes.py
def test_route_file(client, mocker):
test_file = <whatever>
mocker.patch("endpoints.s3_upload")
response = client.put("/", file=test_file)
When I run this test I will basically see it fail trying to legitimately upload to the s3. I cannot get it to either use my mocked s3 client and bucket, or to simply mock the s3_upload function in the first place. I'm assuming this has something to do with the call to FastAPI, because this works just find if testing the handler directly without the TestClient.
Can someone point me in the right direction on how to properly mock objects or functions that are going to be called inside a handler?