-
-
Save rob-b/3249309 to your computer and use it in GitHub Desktop.
Mock a Django Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on https://github.com/dcramer/mock-django | |
import mock | |
from django.utils.unittest import TestCase | |
from project.app.models import Category | |
class ModelMock(mock.MagicMock): | |
def _get_child_mock(self, **kwargs): | |
name = kwargs.get('name', '') | |
if name == 'pk': | |
return self.id | |
return super(ModelMock, self)._get_child_mock(**kwargs) | |
Category = ModelMock(spec=Category()) | |
class TestModelTests(TestCase): | |
def test_category(self): | |
category = Category() | |
category.breakfast_set.all.return_value = ['bacon', 'eggs', 'milk'] | |
assert category.breakfast_set.all() | |
category.subcategory.all.return_value = ['set A', 'set B'] | |
assert category.subcategory.all() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment