python - Django 单元测试 - 创建对象的 ID

标签 python django django-unittest

示例模型.py

模型.py

class Food(models.Model):
    name = models.CharField(max_length=50, verbose_name='Food')

    def __str__(self):
        return self.name

假设我已经编写了单元测试:

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

class TestWhateverFunctions(TestCase):
    """
    This class contains tests for whatever functions.
    """

    def setUp(self):
        """
        This method runs before the execution of each test case.
        """
        Food.objects.create(name='Pizza') # Will the created object have id of 1?
        Food.objects.create(name='Pasta') # Will the created object have id of 2?

    def test_if_food_is_pizza(self):
        """
        Test if the given food is pizza.
        """
        food = Food.objects.get(id=1)

        self.assertEqual(food.name, 'Pizza')

    def test_if_food_is_pasta(self):
        """
        Test if the given food is pasta.
        """
        food = Food.objects.get(id=2)

        self.assertEqual(food.name, 'Pasta')

我想知道是否可以安全地假设在 setUp() 方法 中创建的对象的 ID 总是从 id 1 开始,依此类推?如果不是,是否有特定原因导致测试数据库在运行所有测试后总是被破坏

最佳答案

假设 ID 总是从 1 开始并递增是安全的。如果其他测试已预先运行并创建了 Food 行,并且单元测试未按任何保证顺序执行,则它们可能具有更高的 ID。

在测试设置中保存对模型实例的引用:

class TestWhateverFunctions(TestCase):

    def setUp(self):
        self.food1 = Food.objects.create(name='Pizza')
        self.food2 = Food.objects.create(name='Pasta')

关于python - Django 单元测试 - 创建对象的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242885/

相关文章:

python - Django Manager 的顺序会影响哪些功能?

django - 如何在 `APIClient`中的 `django rest_framework test` header 中添加身份验证 token

Django 1.6.1 : Transaction error. 在 unitest 中的原子 block 结束之前无法执行查询

python - python中的延续

python - PyUSB 1.0 : NotImplementedError: Operation not supported or unimplemented on this platform

python - 根据 python 列表中的出现情况移动文件

django - HttpResponse 对象在传递给 assertContains 时变为字符串

python - 给定一个单词列表,识别长度为 4 或更大的所有相同子串

python - "Add a related_name argument to the definition for ' XXX'.的自动解决方案?

python - django - last() 和 first() 返回相同的对象