45👍
For the purposes of the database, tearDown
is pretty pointless, because each test is run in a transaction. However, not everything in a test involves the database. You might test file creation/reading, spin off processes, open network connections, etc. These types of things usually require you to “close” them after you’re done. This is what tearDown
is for, i.e. cleaning up stuff from your setUp
method, not related to the database. (Though, if you were actually directly connecting to a database, i.e. as the actual Django tests must do to make sure all the DBAPI stuff works properly, you’d need to do clean up there too.)
17👍
I was working on a project that handled some file uploads, and i needed to delete the files that were created by the test and the tearDown
method was very useful in that situation.
import shutil
#....
#....
def tearDown(self):
shutil.rmtree(settings.UPLOAD_ROOT)
- [Django]-Django-admin.py makemessages not working
- [Django]-What's the difference between staff, admin, superuser in django?
- [Django]-Is it okay to set instance variables in a Django class based view?
9👍
If you are using an alternative database like MongoDB or Redis and you need to load in a set of initial data (a “collection”), you will need to override the tearDown
method too.
See http://www.belchak.com/2011/02/07/unit-testing-django-with-a-nosql-backend/
In general, django.test.TestCase
does a full database flush at the start of each
new test. This means that we do not need to manually delete objects in our tearDown as Chris Pratt has mentioned above. The next test setUp will make sure the database is clean.
However, if we are using doctests and unittest.TestCase
, there will be no database flush before tests are run again. At the start of a test, the database will be in whatever state the previous
test left. This means that any stray data left by a previous run would cause conflict. So if we are using doctests or unittest.TestCase for our django tests, a cleanup might be good practice.
Finally, in more complicated scenarios, it might also make sense to deliberately persist the test database to hunt down specific unit test bugs.
- [Django]-Django Forms with ReactJS
- [Django]-How can I pass my context variables to a javascript file in Django?
- [Django]-How do I use prepared statements for inserting MULTIPLE records in SQlite using Python / Django?