如何在 Django 测试中手动清除数据库?

时间:2020-12-20 22:40:16

标签: python-3.x django django-rest-framework django-testing django-tests

我正在使用: python = "3.8.3", django="3.0.5"

我已经用 APITestCase 编写了一个 Django 测试。我在我的测试类中运行其他测试。我试图在我的测试类中调用其他函数。为了做到这一点,我在一个列表中有一个字典,我像这样映射:

[
   {
      "class_name": class_name,
      "func_name": "test_add_product", # Comes test name
      "trigger_type": trigger_type, # Comes from model choices field.
      "request_type": RequestTypes.POST,
      "success": True,
   },
   {
       ...
   },

]

我用一个 for 循环来循环这些并运行每一个。每次循环后都应清除数据库以免出错。我尝试使用:

# Lets say that, we have a Foo model
Foo.objects.all().delete()

这个方法有效,但我想要一个更好的解决方案。

如何在测试完成前手动清除测试数据库?

1 个答案:

答案 0 :(得分:0)

你可以这样做

from django.test import Client, TestCase

class TestsDB(TestCase):
    def __init__(self):
       self.e = Client()
    def test_delete_db(self):
        foo = Foo.objects.all()
        foo.delete()
    
相关问题