4

During unit testing and Selenium functional testing files are generated which are not cleaned up afterwards. I have spent a very long time trying to get django-cleanup working, but it just does nothing.

I figure I need to create a temporary file structure which files can be uploaded to during testing then destroyed after. This is how I created a temp MEDIA_ROOT file:

MEDIA_ROOT = tempfile.mkdtemp()

@override_settings(MEDIA_ROOT=MEDIA_ROOT)
class UnitTest(TestCase):

    @classmethod
    def tearDownClass(cls): 
        shutil.rmtree(MEDIA_ROOT, ignore_errors=True)
        super().tearDownClass()

The problem is that, while I may have created a temporary MEDIA_ROOT folder, it doesn't create the subfolders and files.

My file structure in my project looks like this

MEDIA_ROOT
    profile_pics
        default.jpg
    user_files

Prior to executing each test a user is created and during user creation the user is assigned a profile pic 'default.jpg'. This crashes every test as neither the profile_pics folder nor the default.jpg image exist. If it didn't crash here it would crash later as it would try to save files within folders located within MEDIA, which won't exist in my tempfile.

How can I delete all files after testing without using Django Cleanup? Or how can I create a temporary media file (similar to what I'm already doing), and also the file structure within it (it also would have to include the default.jpg image which is needed during user creation)?

Thank you.

horse
  • 479
  • 7
  • 25

1 Answers1

0

For resource prepare you should use setup and tearDown methods

class MyViewSetTestCase(TestCase):
    def setUp(self):
        # do directory & files creation here
        pass

    def tearDown(self):
        # do cleanup (remove all dirs & files) here
        pass

setUp is called before each test and tearDown after each test

You could create directory tree using os.makedirs

You could delete directory tree using shutil.rmtree

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
Michael Ushakov
  • 1,639
  • 1
  • 10
  • 18
  • Thank you. While I may not have shown that in the code above, I have actually tried doing this. The problem is ```os.makedirs``` makes the MEDIA directory but not the sub files and image file within the MEDIA folder. I also need a solution for unit tests – horse Aug 14 '20 at 22:20
  • A bit later i'll make code sample for you if i correctly and fully understand your problem – Michael Ushakov Aug 16 '20 at 13:41