【问题标题】:Python / Django - How to get all methods in a unittest class to share the same database?Python / Django - 如何让单元测试类中的所有方法共享同一个数据库?
【发布时间】:2015-10-24 21:07:38
【问题描述】:

这是我的代码:

我的导入链接在这里: https://github.com/django/django/blob/master/django/core/urlresolvers.py https://github.com/django/django/blob/master/django/contrib/auth/models.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/status.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/test.py

from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase

class UserTests(APITestCase):
    def test_create_user(self):
        """
        Ensure we can create a new user object.
        """
        url = reverse('user-list')
        data = {'username': 'a', 'password': 'a', 'email': 'a@hotmail.com'}
        # Post the data to the URL to create the object
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        # Check the database to see if the object is created.
        # This check works.
        self.assertEqual(User.objects.count(), 1)

    def test_get_user(self):
        """
        Ensure we can get a list of user objects.
        """
        # This fails and returns an error
        self.assertEqual(User.objects.count(), 1)

当我运行测试时,它会引发一个错误,提示 AssertionError: 0 != 1,因为在函数 test_get_user 中,在 test_create_user 中创建的用户不可见。有没有办法让一个类中的所有方法共享同一个数据库,这样如果我在test_create_user 中创建一个用户,我可以在它下面的方法中访问它?

编辑:我希望他们为所有方法共享同一个数据库的原因是因为我在 UserTests 类中的所有测试用例都需要创建一个用户,所以我不想重复相同的代码即使在 test_create_user 中进行测试,也始终如此。

我知道我可以使用def setUp(self),但我正在使用我的第一种方法进行“创建用户”测试,因此我希望能够测试我是否可以先创建它,然后再在def setUp(self) 中创建它。

【问题讨论】:

  • 请添加 APITestCase 和您的导入。
  • 我认为为 unittest 用户创建一个单独的测试用例更容易。它基本上会测试用于创建用户的代码,这些代码可用于在其他测试用例中预填充数据库。
  • @SebastianWozny 我添加了 GitHub 源代码的链接(这是默认的 Django 和 DRF 源代码)。
  • @Ivan Hm,你到底是什么意思?你是说我创建自己的类来对test_create_user 进行单元测试,然后创建一个单独的类来对依赖于创建用户的其他所有内容进行单元测试(这样我就可以在def setUp(self) 方法中创建用户?)。
  • 没错,你不应该试图把所有东西都放在一个TestCase中。

标签: python django unit-testing python-unittest django-unittest


【解决方案1】:

您应该在每个测试中明确设置数据。测试不能相互依赖。

【讨论】:

  • 在我的情况下(请参阅我的帖子底部的编辑),您是否仍然建议在我的所有方法中一遍又一遍地重用代码的同一部分(我创建用户的部分)?或者有更好的方法吗?注意:我不想在def setUp(self)中创建用户,因为我希望能够在创建用户之前测试是否可以先创建用户(测试在第一种方法中完成-def test_create_user(self)
  • 不,你可以直接通过ORM创建对象;如果您没有专门对此进行测试,则无需通过该帖子。但是,如果您愿意,您当然可以将其放入单独的实用程序方法中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2020-05-28
相关资源
最近更新 更多