[Django]-Cleaning up a database in django before every test method

64👍

Use django.test.TestCase not unittest.TestCase. And it works in all major versions of Django!

👤Marcin

2👍

You can use the tearDown method. It will be called after your test is run. You can delete all Blahs there.

1👍

Make them in two different functions both are not test function. Finally call the dependent functions from one test function.

0👍

Why not do the following? This accomplishes what you need without a significant change to your code.

class TestOneForManager(unittest.TestCase):
  def testAddingBlah(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlah(...)
    self.assertEquals(manager.getBlahs(), 1)

class TestTwoForManager(unittest.TestCase):
  def testAddingBlahInDifferentWay(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlahInDifferentWay(...)
    self.assertEquals(manager.getBlahs(), 1)

Edit. The “reset on TestCase” feature gives you complete control.

  • Many test methods in a single TestCase are good when you have test cases that don’t interfere with each other.

  • Few test methods in a single TestCase are good when you have test cases that interfere with each other.

You can choose which model applies to your tests by grouping your test methods in one or many TestCases. You have total and complete control.

👤S.Lott

0👍

For clearing non-default databases, add multi_db = True in the class

eg

class MyTestCase(django.test.TestCase)
    multi_db = True

    def test_one(self):
        self.assertTrue(True)

Leave a comment