Search code examples
pythondjangodjango-modelsmockingdjango-unittest

Mocking django tests - why is this patched function still being called?


I'm trying to test a function in one of my models, and am trying to to mock out the filesytem using mock.patch. No matter what I try, it doesn't seem to intercept the method.

Model to test:

app/models.py

from django.db import models
from .utils.storageutils import get_file
from .utils.datautils import derive_data

Class DataThing(models.Model):
    #defined here

    def set_data_from_file(self):
        data = derive_data(get_file('filepath'))
        setattr(self, 'derived_data', data)
        self.save()

app/utils/datautils.py

import pandas as pd

def derive_data(data_from_file):
    df = pd.DataFrame('...')
    #do stuff with dataframe
    return df

app/tests/unit_tests/tests_models.py

from django.test import TestCase
import mock
from app.models import DataThing

class DataThingModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
      cls.datathing = DataThing

    @mock.patch('app.models.derive_data')
    def test_set_data_from_file(self, mocked_derive_data):
        mocked_derive_data.return_value=('pretend_dataframe')
        self.datathing.set_data_from_file()
        self.assertEquals(self.datathing.derived_data, 'pretend_dataframe')

I would expect this to pass. However, I get an error, because datathing.set_data_from_file() is still ultimately calling utils.storageutils.get_file. I've tried patching in app.utils.datautils.derive_data but have the same issue.


Solution

  • I also needed to patch the get_file function

    @mock.patch('app.models.get_file')
    @mock.patch('app.models.derive_data')
    def test_set_data_from_file(self, mocked_derive_data, mocked_ger_file):
        mocked_get_file.return_value=('placeholder')
        mocked_derive_data.return_value=('pretend_dataframe')
        self.datathing.set_data_from_file()
        self.assertEquals(self.datathing.derived_data, 'pretend_dataframe')