【问题标题】:How to manually clear DB in a Django test?如何在 Django 测试中手动清除数据库?
【发布时间】:2020-12-20 22:40:16
【问题描述】:

我正在使用: 蟒蛇=“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()

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

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

【问题讨论】:

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


    【解决方案1】:

    你可以这样做

    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()
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2021-01-08
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多