djangoのtest(django-nose, coverage)を使用する時
djangoでtestをするとき、django-nose、coverageが使える。
$ pip install nose $ pip install django-nose $ pip install coverage
- settigns.py
INSTALLED_APPS += ['django_nose', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--with-coverage', # coverage を取る '--cover-html', '--cover-package=app.search', '--nocapture', '--nologcapture', ]
tests.py
import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): # Every test needs a client. self.client = Client() def test_details(self): # Issue a GET request. response = self.client.get('/customer/details/') # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # Check that the rendered context contains 5 customers. self.assertEqual(len(response.context['customers']), 5)
上記設定をした後に、以下を回す。
$ python apps/manage.py test app --settings=product.settings
$ tree cover/ cover/ ├── coverage_html.js ├── index.html ├── app_views_py.html ├── jquery.hotkeys.js ├── jquery.isonscreen.js ├── jquery.min.js ├── jquery.tablesorter.min.js ├── keybd_closed.png ├── keybd_open.png ├── status.json └── style.css $ cd cover/ $ python -m http.server 9090
http.server --- HTTP サーバ — Python 3.8.0 ドキュメント
Tips
django.test.TestCase
は、unittest.TestCase
と違い、関数内のテストで保存されたdatabaseをclear する。--failfast
をオプションに追加することで、errror や fail 次第、graceful exit する