Djangoを使った単体テストの便利なメソッド

django.test.TestCaseにはassertTemplateUsedなお、便利なメソッドが多数用意されています。これらメソッドを使うと、単体テストをよりスムーズに進めることができると思います。

テストケースの例:

--- views.py ---

from django import shortcuts

def index(request):
    return shortcuts.render_to_response(‘index.html', {})

def index2(request):
    return shortcuts.redirect(‘/index/', ())
--- test.py ---

import os
import unittest
os.environ[u'DJANGO_SETTINGS_MODULE'] = u'settings'
from django import test
from django.core import management
from django.test import client
from django.test import utils
import settings
utils.setup_test_environment()  # Call to get templates in a response object.
management.setup_environ(settings)  # Set path to this application.


class TestSample(test.TestCase):

    def setUp(self):
        self._client = client.Client()

    def test_views_01(self):
        response = self._client.get(‘/index/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, ‘index.html')

    def test_views_02(self):
        response = self._client.get(‘/index/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, ‘index2.html')  # Raise an AssertionError. ‘

    def test_view2_01(self):
        response = self._client.get(‘/index2/')
        self.assertEqual(response.status_code, 302)

    def test_view2_02(self):
        response = self._client.get(‘/index2/', follow=True)
        self.assertRedirects(response, ‘/index/')

def main():
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    suite.addTest(loader.loadTestsFromTestCase(TestSample))
    unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == ‘__main__':
    main()

結果:

test_view2_01 (__main__.TestSample) … ok
test_view2_02 (__main__.TestSample) … ok
test_views_01 (__main__.TestSample) … ok
test_views_02 (__main__.TestSample) … FAIL

この記事が役に立った場合、シェアしていただけると励みになります!!