Django: Best way to unit-test an abstract model

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

    I have the same situation as well. I ended up using a version of @dylanboxalot solution. Got extra details from here specifically after reading 'Test structure overview' section.

    The setUp and the tearDown methods are called each time a tests is run. A better solution is to run the creation of the 'abstract' model once, before all the tests are run. To do so, you can implement the setUpClassData and also implement the tearDownClass.

    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
        '''
        @classmethod
        def setUpClass(cls):
            # Create a dummy model which extends the mixin
            cls.model = ModelBase('__TestModel__' +
                cls.mixin.__name__, (cls.mixin,),
                {'__module__': cls.mixin.__module__}
            )
    
            # Create the schema for  our test model
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(cls.model)
            super(ModelMixinTestCase, cls).setUpClass()
    
        @classmethod
        def tearDownClass(cls):
            # Delete the schema for the test model
            with connection.schema_editor() as schema_editor:
                schema_editor.delete_model(cls.model)
            super(ModelMixinTestCase, cls).tearDownClass()
    

    A possible implementation may look like this:

    class MyModelTestCase(ModelMixinTestCase):
        mixin = MyModel
    
        def setUp(self):
            # Runs every time a test is run.
            self.model.objects.create(pk=1)
    
        def test_my_unit(self):
            # a test
            aModel = self.objects.get(pk=1)
            ...
    

    Maybe ModelMixinTestCase class should be added to Django? :P

提交回复
热议问题