Django: Best way to unit-test an abstract model

后端 未结 13 1368
一个人的身影
一个人的身影 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 tried solutions here but ran into issues like

    RuntimeWarning: Model 'myapp.__test__mymodel' was already registered

    Looking up how to test abstract models with pytest wasn't any successful either. I eventually came up with this solution that works perfectly for me:

    import tempfile
    
    import pytest
    from django.db import connection, models
    from model_mommy import mommy
    
    from ..models import AbstractModel
    
    
    @pytest.fixture(scope='module')
    def django_db_setup(django_db_setup, django_db_blocker):
        with django_db_blocker.unblock():
    
            class DummyModel(AbstractModel):
                pass
    
            class DummyImages(models.Model):
                dummy = models.ForeignKey(
                    DummyModel, on_delete=models.CASCADE, related_name='images'
                )
                image = models.ImageField()
    
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(DummyModel)
                schema_editor.create_model(DummyImages)
    
    
    @pytest.fixture
    def temporary_image_file():
        image = tempfile.NamedTemporaryFile()
        image.name = 'test.jpg'
        return image.name
    
    
    @pytest.mark.django_db
    def test_fileuploader_model_file_name(temporary_image_file):
        image = mommy.make('core.dummyimages', image=temporary_image_file)
        assert image.file_name == 'test.jpg'
    
    
    @pytest.mark.django_db
    def test_fileuploader_model_file_mime_type(temporary_image_file):
        image = mommy.make('core.dummyimages', image=temporary_image_file)
        assert image.file_mime_type == 'image/jpeg'
    

    As you can see, I define a Class that inherits from the Abstractmodel, and add it as a fixture. Now with the flexibility of model mommy, I can create a DummyImages object, and it will automatically create a DummyModel for me too!

    Alternatively, I could've made the example simple by not including foreign keys, but it demonstrates the flexibility of pytest and model mommy in combination quite well.

提交回复
热议问题