Django: Best way to unit-test an abstract model

后端 未结 13 1378
一个人的身影
一个人的身影 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:18

    I stumbled across this recently and wanted to update it for newer Django versions (1.9 and later) You can use the SchemaEditor's create_model instead of the outdated sql_create_model

    from django.db import connection
    from django.db.models.base import ModelBase
    from django.test import TestCase
    
    
    class ModelMixinTestCase(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.
        """
    
        def setUp(self):
            # Create a dummy model which extends the mixin
            self.model = ModelBase('__TestModel__' + self.mixin.__name__, (self.mixin,), {'__module__': self.mixin.__module__})
    
            # Create the schema for our test model
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(self.model)
    
        def tearDown(self):
            # Delete the schema for the test model
            with connection.schema_editor() as schema_editor:
                schema_editor.delete_model(self.model)
    

提交回复
热议问题