[Python] Trouble Adding Mocks and Patches to a Test on a Route

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Flask API with a route like:

    from flask import current_app
    from utils.linked_list_handler import get_ll
    import json

    @detail_bp.route("/get_base_details", methods=["GET"])
    def get_all_base_details():
    """Get the details of all nodes with the q_type 'base'"""
    ll = get_ll(current_app)
    base_list=ll.getByQType("base")
    return json.dumps(base_list)


    that I am trying to test. In order to do so, I want to patch get_ll() and mock ll and ll.getByQType(). I tried to do this like:

    class TestGetBaseDetails:
    def test_get_some_base_details(self, test_client: FlaskClient, mocker):
    """
    GIVEN a Flask app configured for testing
    WHEN the '/get_base_details' route is requested with the
    'GET' method while there is a linked list with at least
    one Node with a Question with a q_type of "base"
    THEN check that the response shows the q_detail of those
    base questions
    """
    # mock get_ll
    mock_get_ll = mocker.patch("backend.routes.blueprints.details.get_ll")
    # mock a ll
    mock_ll = mocker.Mock()
    mock_ll.getByQType.return_value = ["q_detail_1", "q_detail_2"]
    # mock the assignment
    mock_get_ll.return_value = mock_ll

    response = test_client.get("/get_base_details")
    assert response.status_code == 200
    assert json.loads(response.data) == ["q_detail_1", "q_detail_2"]

    mock_get_ll.assert_called_once()
    mock_ll.assert_called_once()


    However, this tests fails with the following message: FAILED backend/tests/test_details.py::TestGetBaseDetails::test_get_some_base_details - AssertionError: assert [] == ['q_detail_1', 'q_detail_2']

    An empty list is the return value the route gives when the search doesn't match anything. Checking the two assert_called_once() methods, it shows that neither are ever called. I assume that this is all due to some error within my implementation of the patch and mocks, but I don't know what specifically went wrong or how to check for it.

    Any advice would be greatly appreciated. Thank you in advance.

    Continue reading...

Compartilhe esta Página