简体   繁体   English

如何在Python和Django中针对不同的数据库状态测试功能? (避免重复)

[英]How to test a function for different database states in Python and Django? (avoiding repetitions)

I wrote unit tests first, then I made all the tests pass, now I am looking how to refactor the code to avoid repetitions . 我首先编写了单元测试,然后使所有测试通过,现在我正在寻找如何重构代码以避免重复的方法

I have a function which returns different values depending on the context. 我有一个函数,根据上下文返回不同的值。 All context is extracted on-the-fly from the Django models. 所有上下文都是从Django模型中即时提取的。

Currently my code is structured like that: 目前,我的代码结构如下:

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

Obviously, the code is quite repetitive: the first two lines are the same in each function. 显然,代码是很重复的:每个函数的前两行都是相同的。

My first idea was to use a shared setup function: 我的第一个想法是使用共享的设置功能:

def setUp(self):
    self.user = User.objects.create(username='user')
    self.tested_class = MyClass(user)
  • but this solution didn't work: all model updates were shared, and tests became dependent on each other. 但是此解决方案不起作用:共享所有模型更新,并且测试变得相互依赖。
  • What I need instead is a clean state ("empty database") before starting each test. 我需要的是开始每个测试之前的干净状态(“空数据库”)。

What else can I try? 我还能尝试什么?

Why don't you just destroy all the objects you don't want in your teardown? 您为什么不只销毁拆解中不需要的所有对象? Looks like Django allows you to do this type of thing pretty easily. 看起来Django使您可以很轻松地完成这种事情。

def tearDown(self):
    User.objects.all().delete()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM