Initializing MEDIA_ROOT Before Each Django Test

I want my Django tests to create and modify media files. Therefore, like Django's database tests, I want to set up an empty MEDIA_ROOT folder before running each test.

I decided that I would create a temporary folder and name it MEDIA_ROOT. However, I cannot figure out where to put the code that does this. In this example , a special one is created Runner. The runner sets the root of the wearer and rips it off.

Unfortunately, it setup_test_environmentis called once before the start of the first test function, and not every time the test is run.

I tried to create a class FileSystemTestCasethat installs a file system in its function setUp, and all my test cases stem from it. Although this works, for every person who writes a test file, be sure to call my method setUpas it is not called automatically.

Normally, I would not bother with this, but the cost of forgetting to call the setUp parent method can be very high - if someone forgets about the call and the tests accidentally run on a live system, bad things will happen.

EDIT: The temporary solution I found is to implement both my own runner and the base TestCase. Both set up a temporary MEDIA_ROOT, so if someone forgot to call my method setUp, the test will run in the temporary folder of the previous test or the one that was set up by the runner. This can lead to test failures, but will not lead to real-time data loss.

I hope for a more elegant solution.

+4
source share
1 answer

It seems to me that you are trying to solve two separate problems:

  • Allow tests to work independently (in relation MEDIA_ROOT) when testers do the right thing (i.e. inherit your test class and call yours setUp()).
  • , , .

, , . setUp() 1. MEDIA_ROOT , , , . : , MEDIA_ROOT None. MEDIA_ROOT; , , setUp(); .

, , ( , Django ), .

+2
source

Source: https://habr.com/ru/post/1527402/


All Articles