lundi 28 décembre 2015

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.

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?

Aucun commentaire:

Enregistrer un commentaire