Django: How to create a model dynamically just for testing

后端 未结 11 821
鱼传尺愫
鱼传尺愫 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 06:06

    This solution works only for earlier versions of django (before 1.7). You can check your version easily:

    import django
    django.VERSION < (1, 7)
    

    Original response:

    It's quite strange but form me works very simple pattern:

    1. add tests.py to app which you are going to test,
    2. in this file just define testing models,
    3. below put your testing code (doctest or TestCase definition),

    Below I've put some code which defines Article model which is needed only for tests (it exists in someapp/tests.py and I can test it just with: ./manage.py test someapp ):

    class Article(models.Model):
        title = models.CharField(max_length=128)
        description = models.TextField()
        document = DocumentTextField(template=lambda i: i.description)
    
        def __unicode__(self):
            return self.title
    
    __test__ = {"doctest": """
    #smuggling model for tests
    >>> from .tests import Article
    
    #testing data
    >>> by_two = Article.objects.create(title="divisible by two", description="two four six eight")
    >>> by_three = Article.objects.create(title="divisible by three", description="three six nine")
    >>> by_four = Article.objects.create(title="divisible by four", description="four four eight")
    
    >>> Article.objects.all().search(document='four')
    [, ]
    >>> Article.objects.all().search(document='three')
    []
    """}
    

    Unit tests also working with such model definition.

提交回复
热议问题