I know how to create a temporary directory in Python using tempfile.
I have though a class that encapsulates the user environment. I have also a Unit test which creates a temporary dummy user environment and populates it with some files that are used for testing. After this is done I want to clean everything up, thus removing everything from that dummy user directory (using shutils.rmtree)
I have a dummy class wrapping the original one that prevents it from getting the real user directory and returns the dummy instead. Though I’m afraid somebody might forget this and perhaps change it or completely remove the wrapper class. This might work and the developer will end up loosing everything from his/her home directory. Though this might teach him/her a good lesson, it is not acceptable.
I can check that ‘/tmp/’ is at the path start of the user home, so that I know it’s safe to delete, but that won’t work with windows. As tempfile already knows how to create a directory it would be also able to tell if a directory is in the temporal area.
Though I can’t find out how to do it.
Any ideas?
This is what
tempfile.gettempdir()is for.However, you may want rethink how you signal that the ‘home directory’ is a temporary test-only setup. You could add an extra file (
.this-is-a-test-homediror similar), use a clear ‘temporary’ username.Or, better yet, remove the dummy wrapper altogether and have the test create the temporary user directory before running the test, then clean it up when tearing down the test.