[Fixed]-How to avoid a trip to the database in this Test case

1👍

You can patch the call to the database, to return a predefined value set by you. In your case, you could do something like this:

import factory
import pytest
from unittest.mock import Mock, patch
application_types = ['Type 1', 'Type 2']
@pytest.mark.django_db()
@patch('ApplicationType.objects.get')
def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self, db_mocked_call):
    """Populates base_details dict when value is found in database"""
    mocked_db_object = {'id': 'test_id'}
    db_mocked_call.return_value = mocked_db_object
    for entry in application_types:
        application_type = ApplicationTypeFactory.build(title=entry)
        assert self.base_info_values.get_application_type(entry) == True
        assert self.base_info_values.base_details["application_type"] is not None

I suggest you to check as well pytest.parametrize to avoid making use of the for loop in your test, read more about it here: http://doc.pytest.org/en/latest/parametrize.html

In your example the test could look something like the following:

@pytest.mark.django_db()
@pytest.mark.parametrize("entry", ['Type 1', 'Type 2'])
@patch('ApplicationType.objects.get')
def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self, db_mocked_call, entry):
    """Populates base_details dict when value is found in database"""
    mocked_db_object = {'id': 'test_id'}
    db_mocked_call.return_value = mocked_db_object
    application_type = ApplicationTypeFactory.build(title=entry)
    assert self.base_info_values.get_application_type(entry) == True
    assert self.base_info_values.base_details["application_type"] is not None

Leave a comment