Django: Best way to unit-test an abstract model

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

    I thought I could share with you my solution, which is in my opinion much simpler and I do not see any cons.

    Example goes for using two abstract classes.

    from django.db import connection
    from django.db.models.base import ModelBase
    from mailalert.models import Mailalert_Mixin, MailalertManager_Mixin
    
    class ModelMixinTestCase(TestCase):   
    
        @classmethod
        def setUpTestData(cls):
    
            # we define our models "on the fly", based on our mixins
            class Mailalert(Mailalert_Mixin):
                """ For tests purposes only, we fake a Mailalert model """
                pass
    
            class Profile(MailalertManager_Mixin):
                """ For tests purposes only, we fake a Profile model """
                user = models.OneToOneField(User, on_delete=models.CASCADE, 
                    related_name='profile', default=None)
    
            # then we make those models accessible for later
            cls.Mailalert = Mailalert
            cls.Profile = Profile
    
            # we create our models "on the fly" in our test db
            with connection.schema_editor() as editor:
                editor.create_model(Profile)
                editor.create_model(Mailalert)
    
            # now we can create data using our new added models "on the fly"
            cls.user = User.objects.create_user(username='Rick')
            cls.profile_instance = Profile(user=cls.user)
            cls.profile_instance.save()
            cls.mailalert_instance = Mailalert()
            cls.mailalert_instance.save()
    
    # then you can use this ModelMixinTestCase
    class Mailalert_TestCase(ModelMixinTestCase):
        def test_method1(self):
           self.assertTrue(self.mailalert_instance.method1())
           # etc
    

提交回复
热议问题