Question

I am making a library as a Django app that's meant to provide generic leaderboards for other apps' models in a game application I'm working on. Clients of my library should extend an abstract base class I'm creating and override methods to provide the code to actually aggregate objects.

I want to keep this charts app self-contained and loosely coupled so that I can easily spin it off and open-source it, and so I'm trying to write unit tests that don't depend on any models in outside apps, even though the whole purpose of the app is to essentially aggregate data from models in outside apps. I could just make a dummy model in the app's own models.py, but then this would cause an unused table to be created for every project that uses the library, which seems non-ideal. Is there an ideal way to do this?

Was it helpful?

Solution

So far, I can see two options.

Option 1: Create unmanaged model classes, and in the tests, create and destroy the database tables manually.

Option 2 (what I chose): Declare test models in my tests module. Follow the advice here and trigger syncdb in the test setUp method to create the tables. Adapted for testing, here's what it looks like:

from django.core.management import call_command
from django.db import models
from django.test import TestCase

class TestModel(models.Model):
    data = models.FloatField()

    class Meta:
        app_label = 'myapp'

class LibraryTests(TestCase):
    def setUp(self):
        super(LibraryTests, self).setUp()
        models.register_models('myapp', TestModel)
        call_command('syncdb')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top