Django when to use teardown method

前端 未结 3 2044
-上瘾入骨i
-上瘾入骨i 2021-02-18 13:09

According to the docs:

A TestCase, on the other hand, does not truncate tables and reload initial data at the beginning of a test. Instead, it encloses

相关标签:
3条回答
  • 2021-02-18 13:18

    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.

    0 讨论(0)
  • 2021-02-18 13:27

    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.)

    0 讨论(0)
  • 2021-02-18 13:29

    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)
    
    0 讨论(0)
提交回复
热议问题