Django Fake Model

0.1.4 · maintenance · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to use the `model_me` decorator to create a temporary Django model for a specific test method. The fake model is automatically registered and unregistered, ensuring test isolation. This code snippet should be placed within a Django test file and run as part of a Django test suite.

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)

view raw JSON →