如何在 Python 和 Django 中测试不同数据库状态的函数? (避免重复)
How to test a function for different database states in Python and Django? (avoiding repetitions)
我先写了单元测试,然后我让所有测试都通过了,现在我正在研究如何重构代码以避免重复。
我有一个函数,根据上下文 returns 不同的值。所有上下文都是从 Django 模型中即时提取的。
目前我的代码结构如下:
from django.test import TestCase
class MyTest(TestCase):
def test_case1(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model1.objects.create(...) # one type of context
self.assertEqual(...) # test the class method for this type of context
def test_case2(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model2.objects.create(...) # another type of context
self.assertEqual(...) # test the class method for this type of context
def test_case3(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model1.objects.create(...) # yet another type of context
Model2.objects.create(...)
self.assertEqual(...) # test the class method for this type of context
显然,代码是相当重复的:前两行在每个函数中都是相同的。
我的第一个想法是使用共享设置函数:
def setUp(self):
self.user = User.objects.create(username='user')
self.tested_class = MyClass(user)
- 但此解决方案不起作用:所有模型更新都共享,并且测试变得相互依赖。
- 我需要的是在开始每个测试之前的干净状态 ("empty database")。
我还能尝试什么?
为什么不在拆解中销毁所有不需要的对象?看起来 Django 可以让你很容易地做这种事情。
def tearDown(self):
User.objects.all().delete()
我先写了单元测试,然后我让所有测试都通过了,现在我正在研究如何重构代码以避免重复。
我有一个函数,根据上下文 returns 不同的值。所有上下文都是从 Django 模型中即时提取的。
目前我的代码结构如下:
from django.test import TestCase
class MyTest(TestCase):
def test_case1(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model1.objects.create(...) # one type of context
self.assertEqual(...) # test the class method for this type of context
def test_case2(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model2.objects.create(...) # another type of context
self.assertEqual(...) # test the class method for this type of context
def test_case3(self):
user = User.objects.create(username='user')
tested_class = MyClass(user)
Model1.objects.create(...) # yet another type of context
Model2.objects.create(...)
self.assertEqual(...) # test the class method for this type of context
显然,代码是相当重复的:前两行在每个函数中都是相同的。
我的第一个想法是使用共享设置函数:
def setUp(self):
self.user = User.objects.create(username='user')
self.tested_class = MyClass(user)
- 但此解决方案不起作用:所有模型更新都共享,并且测试变得相互依赖。
- 我需要的是在开始每个测试之前的干净状态 ("empty database")。
我还能尝试什么?
为什么不在拆解中销毁所有不需要的对象?看起来 Django 可以让你很容易地做这种事情。
def tearDown(self):
User.objects.all().delete()