FactoryBoy: how to teardown?

2.1k views Asked by At

I don't understand how teardown in FactoryBoy + Django works.

I have a testcase like this:

class TestOptOutCountTestCase(TestCase):
    multi_db = True

    def setUp(self):
        TestCase.setUp(self)
        self.date = datetime.datetime.strptime('05Nov2014', '%d%b%Y')
        OptoutFactory.create(p_id=1, cdate=self.date, email='[email protected]', optin=1)

    def test_optouts2(self):
        report = ReportOptOutsView()
        result = report.get_optouts()
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0][5], -1)

setUp is running once for all tests correct? Now if I had a second test and needed a clean state before running it, how do I achieve this? Thanks

1

There are 1 answers

0
arie On BEST ANSWER

If I understand you correctly you don't need tearDown in this case, as resetting the database between each test is the default behaviour for a TestCase.

See:

At the start of each test case, before setUp() is run, Django will flush the database, returning the database to the state it was in directly after migrate was called.

...

This flush/load procedure is repeated for each test in the test case, so you can be certain that the outcome of a test will not be affected by another test, or by the order of test execution.

Or do you mean to limit the creation of instances via the OutputFactory to certain tests?

Then you probably shouldn’t put the creation of instances into setUp.

Or you create two variants of your TestCase, one for all tests that rely on the factory and one for the ones that don't.


Regarding the uses of tearDown check this answer: Django when to use teardown method