Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Patching a method from other file is not working

I have a method say _select_warehouse_for_order in api/controllers/orders.py file. The method is not part of any class.

Now, I have a new file say api/controllers/dispatchers.py where i need to know which warehouse was selected. I am calling _select_warehouse_for_order from this file to get this information.

Now, in my test cases, I am patching _select_warehouse_for_order like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from unittest.mock import patch, call

def test_delivery_assignment(self, app_context):
    with patch('api.controllers.orders._select_warehouse_for_order') as mock_selected_wh:
        mock_selected_wh.return_value = {}
        app_context.client.set_url_prefix('/v2')
        response = app_context.client.get('/delivery/dispatch')
        assert response.status_code == 200

The problem that i am facing is that my patch is not returning empty dictionary. when i started debugging, i noticed that its executed the actual code in _select_warehouse_for_order. Am i missing something here?

Update:
Here is the code in dispatchers.py

from api.controllers.orders import _select_warehouse_for_order

@bp.route("/dispatch")
@login_required
def dispatch():
  warehouses = _select_warehouse_for_order(request=request)
    if len(warehouses) == 0:
        logger.info("No warehouse selected")
        return

    logger.info("Selected warehouse: %s", warehouses[0].name)
    # return response

>Solution :

You must patch where the method is used, not where it is declared. In your case, you are patching 'api.controllers.orders._select_warehouse_for_order' which is where the method is declared. Instead, patch 'dispatchers._select_warehouse_for_order' (possibly prefixed with whatever package contains dispatchers).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading