Django: How to create a model dynamically just for testing

后端 未结 11 842
鱼传尺愫
鱼传尺愫 2020-12-02 05:15

I have a Django app that requires a settings attribute in the form of:

RELATED_MODELS = (\'appname1.modelname1.attribute1\',
                  \         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 05:55

    I chose a slightly different, albeit more coupled, approach to dynamically creating models just for testing.

    I keep all my tests in a tests subdirectory that lives in my files app. The models.py file in the tests subdirectory contains my test-only models. The coupled part comes in here, where I need to add the following to my settings.py file:

    # check if we are testing right now
    TESTING = 'test' in sys.argv
    
    if TESTING:
        # add test packages that have models
        INSTALLED_APPS += ['files.tests',]
    

    I also set db_table in my test model, because otherwise Django would have created the table with the name tests_, which may have caused a conflict with other test models in another app. Here's my my test model:

    class Recipe(models.Model):
    
        '''Test-only model to test out thumbnail registration.'''
    
        dish_image = models.ImageField(upload_to='recipes/')
    
        class Meta:
            db_table = 'files_tests_recipe'
    

提交回复
热议问题