I have the following flask app route:
# routes.pyfrom flask import jsonifyfrom app.utils.db import db_connection, db_query@api.route("/some/route", methods=["GET"])@authdef get_data_for_some_route(**kwargs) -> List[Dict]: # connect to db db_client = db_connection() # Query db for data data = db.query(db_client, GET_STUFF) # parse the data example parsed_data = data[0] return jsonify(parsed_data), 200
How can I write a pytest for this route, but mock the db connection and query results?
# test_routes.pyimport pytestfrom fixtures import SOME_ROUTE_JSON_DATAmock_token = "12345"def test_get_data_for_some_route(mocker, client): querystring1 = 'Hello' querystring2 = 'World' # Mock db query function mocked_db_query = mocker.patch('app.utils.database.db_connection') mocked_db_query.return_value = loads(SOME_ROUTE_JSON_DATA) # Call the route response = client.get( f"/some_route", headers={"Authorization": f"{mock_token}"} ) # assert response.json is some value I expect it to be
I'm a little confused how to mock values within the route. So the database connection can be ignored and I can also say 'this is what the return data will be in this case, continue on testing the function pretending that is what the data is.'