Django:防止每次测试后自动删除模型数据
Django: Preventing automatic deletion of model data after each test
我简化了代码以在此处显示效果。
class AccountTests(APITestCase):
def test_post_account(self):
"""
Ensure we can create a new account object
"""
# code that adds one user object and one signup confirmation object
...
...
# test we have one user and one confirmation code
# THIS PASSES OK.
self.assertEqual(User.objects.count(), 1)
self.assertEqual(SignupConfirmationCode.objects.count(), )
def test_post_confirmation_code(self):
"""
test sending confirmation code for an account just created
"""
# THIS FAILS
self.assertEqual(User.objects.count(), 1)
self.assertEqual(SignupConfirmationCode.objects.count(), 1)
我知道 test_post_account
先是 运行 并且通过了 OK。 test_post_confirmation_code
是 运行 第二个,并且由于 User
和 SignupConfirmataionCode
"magically" 在两种测试方法之间丢失了它们的内容而断言。
如何防止第一次测试结束和第二次测试开始之间的数据消失?
你不知道。您设置测试,以便它们各自创建所需的数据。
第一个测试中用于设置用户和确认的代码应提取到 setUp
方法中,该方法在每次测试之前运行。
我简化了代码以在此处显示效果。
class AccountTests(APITestCase):
def test_post_account(self):
"""
Ensure we can create a new account object
"""
# code that adds one user object and one signup confirmation object
...
...
# test we have one user and one confirmation code
# THIS PASSES OK.
self.assertEqual(User.objects.count(), 1)
self.assertEqual(SignupConfirmationCode.objects.count(), )
def test_post_confirmation_code(self):
"""
test sending confirmation code for an account just created
"""
# THIS FAILS
self.assertEqual(User.objects.count(), 1)
self.assertEqual(SignupConfirmationCode.objects.count(), 1)
我知道 test_post_account
先是 运行 并且通过了 OK。 test_post_confirmation_code
是 运行 第二个,并且由于 User
和 SignupConfirmataionCode
"magically" 在两种测试方法之间丢失了它们的内容而断言。
如何防止第一次测试结束和第二次测试开始之间的数据消失?
你不知道。您设置测试,以便它们各自创建所需的数据。
第一个测试中用于设置用户和确认的代码应提取到 setUp
方法中,该方法在每次测试之前运行。