Django/unittest run command at the end of the test runner

Viewed 1187

I'm using the Django test runner to run my unit tests. Some of these tests use factories which create TONS of files on my local system. They all have a detectable name, and can be removed reasonably easily.

I'm trying to avoid having to either

  1. Keep a file-deleting cron job running
  2. Change my custom image model's code to delete the file if it detects that we're testing. Instead, I'd like to have a command run once (and only once) at the end of the test run to clean up all files that the tests have generated.

I wrote a small management command that deletes the files that match the intended convention. Is there a way to have the test runner run call_command on that upon completion of the entire test suite (and not just in the tearDown or tearDownClass methods of a particular test)?

3 Answers

If you create a services.py file in the same folder as models.py, you can put the cleanup code in there and then call it from the management command and from the test tearDown while keeping it DRY.

You could maybe exploit the way the django test runner orders the tests (see https://docs.djangoproject.com/en/1.11/topics/testing/overview/#order-in-which-tests-are-executed)

If your test cases are inheriting from django's TestCase class, you could create a dummy cleanup test case inheriting directly from unittest.TestCase. The test runner would execute that last, and you can do your cleanup there.

However, this will break if the django devs ever decide to make changes to the test ordering.

Related