Django: Best way to unit-test an abstract model

后端 未结 13 1363
一个人的身影
一个人的身影 2020-12-24 12:28

I need to write some unit tests for an abstract base model, that provides some basic functionality that should be used by other apps. It it would be necessary to define a mo

13条回答
  •  情歌与酒
    2020-12-24 13:20

    Having read through all the answers above, I found out a solution that worked for me, in Django 3.1.1 with PostgreSQL 12.4 database.

    from django.db import connection
    from django.db.utils import ProgrammingError
    from django.test import TestCase
    
    
    class AbstractModelTestCase(TestCase):
        """
        Base class for tests of model mixins. To use, subclass and specify the
        mixin class variable. A model using the mixin will be made available in
        self.model
        """
    
        @classmethod
        def setUpClass(cls):
            if not hasattr(cls, "model"):
                super(AbstractModelTestCase, cls).setUpClass()
            else:
                # Create the schema for our test model. If the table already exists, will pass
                try:
                    with connection.schema_editor() as schema_editor:
                        schema_editor.create_model(cls.model)
                    super(AbstractModelTestCase, cls).setUpClass()
                except ProgrammingError:
                    pass
    
        @classmethod
        def tearDownClass(cls):
            if hasattr(cls, "model"):
                # Delete the schema for the test model
                with connection.schema_editor() as schema_editor:
                    schema_editor.delete_model(cls.model)
            super(AbstractModelTestCase, cls).tearDownClass()
    

    It also gets rid of the annoying RuntimeWarning: Model 'xxx' was already registered warning.

提交回复
热议问题