[Django]-Mock a model method in Django

5👍

You can mock the get_or_create() method, as well as the skill relation to let your test run without accessing the database.

def test_update_skills(self):
    def mock_get_or_create(title):
        return title, True
    mock_skill = set()
    with mock.patch('analytics.models.Skill.objects.get_or_create',
                    mock_get_or_create), \
            mock.patch.object(UserProfile, 'skill', mock_skill):
        userprofile = UserProfile()

        cleaned_skills = ['mysql', 'unix']
        userprofile.update_skills(cleaned_skills)

    self.assertEqual({'mysql', 'unix'}, mock_skill)

I’m helping out with the django_mock_queries project that helps provide a bunch of Django queryset features without accessing the database. It’s made a bunch of our tests way faster.

3👍

  1. Your test looks strange
  2. You can test model methods without creating records in database, just don’t use .create() or .save():

    def test_my_method(self):
        my_model = MyModel(someattr='someval', ...)
        self.assertEqual(my_model.my_method(), ...)
    
  3. Sometimes it is good decision to mock .save() method to disable creating records in database and speedup tests. See few examples of how You can use mock in tests: http://nanvel.name/2014/04/testing-django-application#patchmock

1👍

Try to use Mixer:

from mixer.backend.django import mixer

skill = mixer.blend(Skill, category__title='foo')
userprofile = mixer.blend(UserProfile, user__username='john')

Leave a comment