django 测试 - 如何避免 ForeignKeyViolation

时间:2021-01-19 08:53:39

标签: django django-testing

我正在努力使用带有外键的对象使用 django 创建测试。测试在单独运行时没有错误运行,但是在运行所有测试时,我在 ForeignKeyViolation 阶段得到 teardown(我不明白它的作用,也找不到关于它的任何信息) .

在启动测试套件时,我正在创建一堆这样的虚拟数据:

def setUp(self) -> None:
    create_bulk_users(5)
    create_categories()
    create_tags()
    create_technologies()
    self.tags = Tag.objects.all()
    self.categories = Category.objects.all()
    self.technologies = Technology.objects.all()

我需要帮助解决的问题是:

  1. teardown 阶段究竟有什么作用?有没有详细的文档?
  2. 我应该如何构建我的测试以避免 ForeignKeyViolation 问题?

1 个答案:

答案 0 :(得分:1)

拆解阶段到底是做什么的?有没有详细的文档?

我找不到任何关于它的详细文档。我发现的只是阅读实际代码。 Teardown 会取消测试期间对数据库执行的任何操作。

The way TestCases work (broadly) is this:

1. SetUp method runs **before** every test
2. individual test method is run
3. TearDown method runs **after** every test
4. Test database is flushed

我应该如何构建我的测试以避免 ForeignKeyViolation 问题?

我的错误是我导入了一个用于创建虚拟数据的函数。 导入的模块正在运行一个函数来填充一些主要数据。问题是没有在 setUp 方法中重新运行每一个,因为在导入文件时它只会运行一个。

# imported module

# will delete all tags after running first test but
# the reference to the old tags will persist

tags = FakeTags.create_bulk();

def create_bulk_articles():
    article = FakeArticle.create()
    article.tags.add(tags)

我只是使用导入函数中的故障函数修复了它。

# imported module

# tags are created each time before running the tests

def create_bulk_articles():
    tags = FakeTags.create_bulk();
    article = FakeArticle.create()
    article.tags.add(tags)
相关问题