开发者

Run Django unit tests from custom management command

I used to have a standalone script with some unit tests to test data in our database. I did not use the builtin Django testing tool, as that would create an empty testing database, which is not what I want.

In that script, I created three different classes extending unittest.TestCase co开发者_如何学Gontaining some test functions that directly executed SQL statements.

Now I would prefer to be able to access the Django ORM directly. The easiest way to do this is via a custom management commant (./manage.py datatests).

In the standalone script, I could call all unit tests via the following function:

if __name__ == '__main__':
    unittest.main()

It would discover all tests in the current file and run them.

How can I do an equivalent thing (run some test suites) from within a custom Django management command?


I'm sorry for not having searched for an answer long enough before asking, but I found the solution to this problem myself in another Stackoverflow answer:

  • How to run django unit-tests on production database?

Essentially, instead of unittest.main() the following code can be used:

suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseClass)
unittest.TextTestRunner(verbosity=2).run(suite)

This will load all tests in the specified TestCaseClass. If you want to load all tests in the current module, creating the suite this way will help:

suite = TestLoader().loadTestsFromName(__name__)

The Stackoverflow answer linked above contains a full example. Furthermore, the Basic Example section of the unittest module docs describes the same thing. For other options to load tests, see Loading and running tests in the docs.


You may want to specify the contents of your start-up db through fixtures. It will load up the context for db for particular test. And you can take a snapshot of db with

$ ./manage.py dumpdata my_app > fixtures/my_pre_test_db.json`

Now in your unit test you will have something like this:

class MyTestCase(TestCase):
    fixtures = ['fixtures/my_pre_test_db.json']

    def testThisFeature(self):
        ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜