Python / Django - 如何让单元测试 class 中的所有方法共享同一个数据库?

Python / Django - How to get all methods in a unittest class to share the same database?

这是我的代码:

Link 我的导入在这里: 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 中创建的用户不可见。有没有办法让 class 中的所有方法共享同一个数据库,这样如果我在 test_create_user 中创建用户,我可以在它下面的方法中访问它?

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

中进行测试也是如此

我知道我可以使用 def setUp(self) 但我在我的第一个方法中进行了 "create user" 测试所以我希望能够测试我是否可以先创建它然后再在 def setUp(self).

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