Django Fake Model
django-fake-model is a simple Python library designed for creating temporary, in-memory Django models specifically for unit testing purposes. It allows developers to quickly define and use fake models within their tests without polluting the main database schema, facilitating isolated and efficient testing. The current version is 0.1.4, and its release cadence has been very slow, with the last update in 2017.
Warnings
- breaking The library has not been updated since 2017 and is likely incompatible with modern Django versions (3.x, 4.x, 5.x) and newer Python versions (3.8+). It was last officially tested with Django 1.9.
- gotcha The lack of active maintenance since 2017 means the library may have unpatched bugs, security vulnerabilities, or simply not function as expected with contemporary Django ecosystem components.
- gotcha Prior to version 0.1.3, defining and using multiple fake models within the same test context could lead to unexpected behavior or conflicts. This was fixed in 0.1.3.
- gotcha Version 0.1.4 specifically fixed issues related to the `fake_me` class decorator when used with `nose` tests. If you are using `fake_me` with other test runners, thoroughly test its behavior.
Install
-
pip install django-fake-model
Imports
- model_me
from fake_model import model_me
- fake_me
from fake_model import fake_me
Quickstart
import unittest
from django.test import TestCase
from django.db import models
from fake_model import model_me
class MyFakeModelTest(TestCase):
"""
Example demonstrating the model_me decorator for creating a temporary Django model.
To execute this test, ensure you have a Django project configured and run it
via `python manage.py test your_app_name`.
"""
@model_me('my_app', 'MyFakeModel', fields={
'name': models.CharField(max_length=255),
'value': models.IntegerField(default=0),
})
def test_create_and_query_fake_model(self, MyFakeModel):
# MyFakeModel is a temporary model class, available only within this test method
self.assertFalse(MyFakeModel.objects.exists()) # Should be empty initially
instance = MyFakeModel.objects.create(name='Test Item', value=42)
self.assertEqual(instance.name, 'Test Item')
self.assertEqual(instance.value, 42)
retrieved = MyFakeModel.objects.get(name='Test Item')
self.assertEqual(retrieved.pk, instance.pk)
self.assertEqual(retrieved.value, 42)
self.assertEqual(MyFakeModel.objects.count(), 1)