如何在Django中将参数传递给我的TestCase?

时间:2018-10-23 09:36:12

标签: django django-tests

使用Django自己的文档中的示例的编辑版本,可以说我的代码如下:

from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):

    def __init__(self, animal_family):
        self.animal_family = animal_family        

    def setUp(self):
        Animal.objects.create(name="lion", sound="roar", family=self.animal_family)

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        lion = Animal.objects.get(name="lion")
        self.assertEqual(lion.speak(), 'The mammal lion says "roar"')

基本上,我想将animal_family参数传递到测试中,或者至少从终端中传递类似的参数。像这样

python manage.py test myapp.tests.AnimalTestCase 'mammal'

显然,以上命令不起作用。我想将“哺乳动物”作为animal_family发送到测试类中的__init__方法中。

我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

虽然自包含测试是最佳实践,但如果您确实想执行此操作,则可以在执行测试命令时设置环境变量。

例如:

import os
from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):      

    def setUp(self):
        # Retrieve the animal family from the environment variable
        animal_family = os.environ['animal_family']
        Animal.objects.create(name="lion", sound="roar", family=animal_family)

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        lion = Animal.objects.get(name="lion")
        self.assertEqual(lion.speak(), 'The mammal lion says "roar"')

然后调用测试命令,例如:

export animal_family=mammal;python manage.py test myapp.tests.AnimalTestCase