Django: Best way to unit-test an abstract model

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

    I think what you are looking for is something like this.

    This is the full code from the link:

    from django.test import TestCase
    from django.db import connection
    from django.core.management.color import no_style
    from django.db.models.base import ModelBase
    
    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                              
            self._style = no_style()                                            
            sql, _ = connection.creation.sql_create_model(self.model, self._style)
    
            self._cursor = connection.cursor()                                  
            for statement in sql:                                               
                self._cursor.execute(statement)                                 
    
        def tearDown(self):                                                     
            # Delete the schema for the test model                              
            sql = connection.creation.sql_destroy_model(self.model, (), self._style)
            for statement in sql:                                               
                self._cursor.execute(statement)                                 
    

提交回复
热议问题