~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to docs/topics/testing/overview.txt

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2014-04-21 16:47:14 UTC
  • mfrom: (1.3.14)
  • Revision ID: package-import@ubuntu.com-20140421164714-3mlvyr7y1ssdo9e6
Tags: 1.6.3-1
* New upstream security release.
  - Unexpected code execution using ``reverse()``
  - CVE-2014-0472
  - Caching of anonymous pages could reveal CSRF token
  - CVE-2014-0473
  - MySQL typecasting could result in unexpected matches
  - CVE-2014-0474
* Drop patches 07_translation_encoding_fix and ticket21869.diff; merged
  upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
===========================
2
 
Testing Django applications
3
 
===========================
 
1
=========================
 
2
Writing and running tests
 
3
=========================
4
4
 
5
5
.. module:: django.test
6
6
   :synopsis: Testing tools for Django applications.
7
7
 
8
8
.. seealso::
9
9
 
10
 
    The :doc:`testing tutorial </intro/tutorial05>` and the
11
 
    :doc:`advanced testing topics </topics/testing/advanced>`.
 
10
    The :doc:`testing tutorial </intro/tutorial05>`, the :doc:`testing tools
 
11
    reference </topics/testing/tools>`, and the :doc:`advanced testing topics
 
12
    </topics/testing/advanced>`.
12
13
 
13
14
This document is split into two primary sections. First, we explain how to write
14
15
tests with Django. Then, we explain how to run them.
320
321
 
321
322
Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
322
323
algorithm used in fixtures, if any.
323
 
 
324
 
Testing tools
325
 
=============
326
 
 
327
 
Django provides a small set of tools that come in handy when writing tests.
328
 
 
329
 
.. _test-client:
330
 
 
331
 
The test client
332
 
---------------
333
 
 
334
 
.. module:: django.test.client
335
 
   :synopsis: Django's test client.
336
 
 
337
 
The test client is a Python class that acts as a dummy Web browser, allowing
338
 
you to test your views and interact with your Django-powered application
339
 
programmatically.
340
 
 
341
 
Some of the things you can do with the test client are:
342
 
 
343
 
* Simulate GET and POST requests on a URL and observe the response --
344
 
  everything from low-level HTTP (result headers and status codes) to
345
 
  page content.
346
 
 
347
 
* See the chain of redirects (if any) and check the URL and status code at
348
 
  each step.
349
 
 
350
 
* Test that a given request is rendered by a given Django template, with
351
 
  a template context that contains certain values.
352
 
 
353
 
Note that the test client is not intended to be a replacement for Selenium_ or
354
 
other "in-browser" frameworks. Django's test client has a different focus. In
355
 
short:
356
 
 
357
 
* Use Django's test client to establish that the correct template is being
358
 
  rendered and that the template is passed the correct context data.
359
 
 
360
 
* Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
361
 
  *behavior* of Web pages, namely JavaScript functionality. Django also
362
 
  provides special support for those frameworks; see the section on
363
 
  :class:`~django.test.LiveServerTestCase` for more details.
364
 
 
365
 
A comprehensive test suite should use a combination of both test types.
366
 
 
367
 
Overview and a quick example
368
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
369
 
 
370
 
To use the test client, instantiate ``django.test.client.Client`` and retrieve
371
 
Web pages::
372
 
 
373
 
    >>> from django.test.client import Client
374
 
    >>> c = Client()
375
 
    >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
376
 
    >>> response.status_code
377
 
    200
378
 
    >>> response = c.get('/customer/details/')
379
 
    >>> response.content
380
 
    '<!DOCTYPE html...'
381
 
 
382
 
As this example suggests, you can instantiate ``Client`` from within a session
383
 
of the Python interactive interpreter.
384
 
 
385
 
Note a few important things about how the test client works:
386
 
 
387
 
* The test client does *not* require the Web server to be running. In fact,
388
 
  it will run just fine with no Web server running at all! That's because
389
 
  it avoids the overhead of HTTP and deals directly with the Django
390
 
  framework. This helps make the unit tests run quickly.
391
 
 
392
 
* When retrieving pages, remember to specify the *path* of the URL, not the
393
 
  whole domain. For example, this is correct::
394
 
 
395
 
      >>> c.get('/login/')
396
 
 
397
 
  This is incorrect::
398
 
 
399
 
      >>> c.get('http://www.example.com/login/')
400
 
 
401
 
  The test client is not capable of retrieving Web pages that are not
402
 
  powered by your Django project. If you need to retrieve other Web pages,
403
 
  use a Python standard library module such as :mod:`urllib` or
404
 
  :mod:`urllib2`.
405
 
 
406
 
* To resolve URLs, the test client uses whatever URLconf is pointed-to by
407
 
  your :setting:`ROOT_URLCONF` setting.
408
 
 
409
 
* Although the above example would work in the Python interactive
410
 
  interpreter, some of the test client's functionality, notably the
411
 
  template-related functionality, is only available *while tests are
412
 
  running*.
413
 
 
414
 
  The reason for this is that Django's test runner performs a bit of black
415
 
  magic in order to determine which template was loaded by a given view.
416
 
  This black magic (essentially a patching of Django's template system in
417
 
  memory) only happens during test running.
418
 
 
419
 
* By default, the test client will disable any CSRF checks
420
 
  performed by your site.
421
 
 
422
 
  If, for some reason, you *want* the test client to perform CSRF
423
 
  checks, you can create an instance of the test client that
424
 
  enforces CSRF checks. To do this, pass in the
425
 
  ``enforce_csrf_checks`` argument when you construct your
426
 
  client::
427
 
 
428
 
      >>> from django.test import Client
429
 
      >>> csrf_client = Client(enforce_csrf_checks=True)
430
 
 
431
 
Making requests
432
 
~~~~~~~~~~~~~~~
433
 
 
434
 
Use the ``django.test.client.Client`` class to make requests.
435
 
 
436
 
.. class:: Client(enforce_csrf_checks=False, **defaults)
437
 
 
438
 
    It requires no arguments at time of construction. However, you can use
439
 
    keywords arguments to specify some default headers. For example, this will
440
 
    send a ``User-Agent`` HTTP header in each request::
441
 
 
442
 
        >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')
443
 
 
444
 
    The values from the ``extra`` keywords arguments passed to
445
 
    :meth:`~django.test.client.Client.get()`,
446
 
    :meth:`~django.test.client.Client.post()`, etc. have precedence over
447
 
    the defaults passed to the class constructor.
448
 
 
449
 
    The ``enforce_csrf_checks`` argument can be used to test CSRF
450
 
    protection (see above).
451
 
 
452
 
    Once you have a ``Client`` instance, you can call any of the following
453
 
    methods:
454
 
 
455
 
    .. method:: Client.get(path, data={}, follow=False, **extra)
456
 
 
457
 
 
458
 
        Makes a GET request on the provided ``path`` and returns a ``Response``
459
 
        object, which is documented below.
460
 
 
461
 
        The key-value pairs in the ``data`` dictionary are used to create a GET
462
 
        data payload. For example::
463
 
 
464
 
            >>> c = Client()
465
 
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
466
 
 
467
 
        ...will result in the evaluation of a GET request equivalent to::
468
 
 
469
 
            /customers/details/?name=fred&age=7
470
 
 
471
 
        The ``extra`` keyword arguments parameter can be used to specify
472
 
        headers to be sent in the request. For example::
473
 
 
474
 
            >>> c = Client()
475
 
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
476
 
            ...       HTTP_X_REQUESTED_WITH='XMLHttpRequest')
477
 
 
478
 
        ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
479
 
        details view, which is a good way to test code paths that use the
480
 
        :meth:`django.http.HttpRequest.is_ajax()` method.
481
 
 
482
 
        .. admonition:: CGI specification
483
 
 
484
 
            The headers sent via ``**extra`` should follow CGI_ specification.
485
 
            For example, emulating a different "Host" header as sent in the
486
 
            HTTP request from the browser to the server should be passed
487
 
            as ``HTTP_HOST``.
488
 
 
489
 
            .. _CGI: http://www.w3.org/CGI/
490
 
 
491
 
        If you already have the GET arguments in URL-encoded form, you can
492
 
        use that encoding instead of using the data argument. For example,
493
 
        the previous GET request could also be posed as::
494
 
 
495
 
        >>> c = Client()
496
 
        >>> c.get('/customers/details/?name=fred&age=7')
497
 
 
498
 
        If you provide a URL with both an encoded GET data and a data argument,
499
 
        the data argument will take precedence.
500
 
 
501
 
        If you set ``follow`` to ``True`` the client will follow any redirects
502
 
        and a ``redirect_chain`` attribute will be set in the response object
503
 
        containing tuples of the intermediate urls and status codes.
504
 
 
505
 
        If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
506
 
        redirected to ``/final/``, this is what you'd see::
507
 
 
508
 
            >>> response = c.get('/redirect_me/', follow=True)
509
 
            >>> response.redirect_chain
510
 
            [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
511
 
 
512
 
    .. method:: Client.post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
513
 
 
514
 
        Makes a POST request on the provided ``path`` and returns a
515
 
        ``Response`` object, which is documented below.
516
 
 
517
 
        The key-value pairs in the ``data`` dictionary are used to submit POST
518
 
        data. For example::
519
 
 
520
 
            >>> c = Client()
521
 
            >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
522
 
 
523
 
        ...will result in the evaluation of a POST request to this URL::
524
 
 
525
 
            /login/
526
 
 
527
 
        ...with this POST data::
528
 
 
529
 
            name=fred&passwd=secret
530
 
 
531
 
        If you provide ``content_type`` (e.g. :mimetype:`text/xml` for an XML
532
 
        payload), the contents of ``data`` will be sent as-is in the POST
533
 
        request, using ``content_type`` in the HTTP ``Content-Type`` header.
534
 
 
535
 
        If you don't provide a value for ``content_type``, the values in
536
 
        ``data`` will be transmitted with a content type of
537
 
        :mimetype:`multipart/form-data`. In this case, the key-value pairs in
538
 
        ``data`` will be encoded as a multipart message and used to create the
539
 
        POST data payload.
540
 
 
541
 
        To submit multiple values for a given key -- for example, to specify
542
 
        the selections for a ``<select multiple>`` -- provide the values as a
543
 
        list or tuple for the required key. For example, this value of ``data``
544
 
        would submit three selected values for the field named ``choices``::
545
 
 
546
 
            {'choices': ('a', 'b', 'd')}
547
 
 
548
 
        Submitting files is a special case. To POST a file, you need only
549
 
        provide the file field name as a key, and a file handle to the file you
550
 
        wish to upload as a value. For example::
551
 
 
552
 
            >>> c = Client()
553
 
            >>> with open('wishlist.doc') as fp:
554
 
            ...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
555
 
 
556
 
        (The name ``attachment`` here is not relevant; use whatever name your
557
 
        file-processing code expects.)
558
 
 
559
 
        Note that if you wish to use the same file handle for multiple
560
 
        ``post()`` calls then you will need to manually reset the file
561
 
        pointer between posts. The easiest way to do this is to
562
 
        manually close the file after it has been provided to
563
 
        ``post()``, as demonstrated above.
564
 
 
565
 
        You should also ensure that the file is opened in a way that
566
 
        allows the data to be read. If your file contains binary data
567
 
        such as an image, this means you will need to open the file in
568
 
        ``rb`` (read binary) mode.
569
 
 
570
 
        The ``extra`` argument acts the same as for :meth:`Client.get`.
571
 
 
572
 
        If the URL you request with a POST contains encoded parameters, these
573
 
        parameters will be made available in the request.GET data. For example,
574
 
        if you were to make the request::
575
 
 
576
 
        >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
577
 
 
578
 
        ... the view handling this request could interrogate request.POST
579
 
        to retrieve the username and password, and could interrogate request.GET
580
 
        to determine if the user was a visitor.
581
 
 
582
 
        If you set ``follow`` to ``True`` the client will follow any redirects
583
 
        and a ``redirect_chain`` attribute will be set in the response object
584
 
        containing tuples of the intermediate urls and status codes.
585
 
 
586
 
    .. method:: Client.head(path, data={}, follow=False, **extra)
587
 
 
588
 
        Makes a HEAD request on the provided ``path`` and returns a
589
 
        ``Response`` object. This method works just like :meth:`Client.get`,
590
 
        including the ``follow`` and ``extra`` arguments, except it does not
591
 
        return a message body.
592
 
 
593
 
    .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, **extra)
594
 
 
595
 
        Makes an OPTIONS request on the provided ``path`` and returns a
596
 
        ``Response`` object. Useful for testing RESTful interfaces.
597
 
 
598
 
        When ``data`` is provided, it is used as the request body, and
599
 
        a ``Content-Type`` header is set to ``content_type``.
600
 
 
601
 
        .. versionchanged:: 1.5
602
 
 
603
 
            :meth:`Client.options` used to process ``data`` like
604
 
            :meth:`Client.get`.
605
 
 
606
 
        The ``follow`` and ``extra`` arguments act the same as for
607
 
        :meth:`Client.get`.
608
 
 
609
 
    .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, **extra)
610
 
 
611
 
        Makes a PUT request on the provided ``path`` and returns a
612
 
        ``Response`` object. Useful for testing RESTful interfaces.
613
 
 
614
 
        When ``data`` is provided, it is used as the request body, and
615
 
        a ``Content-Type`` header is set to ``content_type``.
616
 
 
617
 
        .. versionchanged:: 1.5
618
 
 
619
 
            :meth:`Client.put` used to process ``data`` like
620
 
            :meth:`Client.post`.
621
 
 
622
 
        The ``follow`` and ``extra`` arguments act the same as for
623
 
        :meth:`Client.get`.
624
 
 
625
 
    .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, **extra)
626
 
 
627
 
        Makes a PATCH request on the provided ``path`` and returns a
628
 
        ``Response`` object. Useful for testing RESTful interfaces.
629
 
 
630
 
        The ``follow`` and ``extra`` arguments act the same as for
631
 
        :meth:`Client.get`.
632
 
 
633
 
    .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, **extra)
634
 
 
635
 
        Makes an DELETE request on the provided ``path`` and returns a
636
 
        ``Response`` object. Useful for testing RESTful interfaces.
637
 
 
638
 
        When ``data`` is provided, it is used as the request body, and
639
 
        a ``Content-Type`` header is set to ``content_type``.
640
 
 
641
 
        .. versionchanged:: 1.5
642
 
 
643
 
            :meth:`Client.delete` used to process ``data`` like
644
 
            :meth:`Client.get`.
645
 
 
646
 
        The ``follow`` and ``extra`` arguments act the same as for
647
 
        :meth:`Client.get`.
648
 
 
649
 
 
650
 
    .. method:: Client.login(**credentials)
651
 
 
652
 
        If your site uses Django's :doc:`authentication system</topics/auth/index>`
653
 
        and you deal with logging in users, you can use the test client's
654
 
        ``login()`` method to simulate the effect of a user logging into the
655
 
        site.
656
 
 
657
 
        After you call this method, the test client will have all the cookies
658
 
        and session data required to pass any login-based tests that may form
659
 
        part of a view.
660
 
 
661
 
        The format of the ``credentials`` argument depends on which
662
 
        :ref:`authentication backend <authentication-backends>` you're using
663
 
        (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
664
 
        setting). If you're using the standard authentication backend provided
665
 
        by Django (``ModelBackend``), ``credentials`` should be the user's
666
 
        username and password, provided as keyword arguments::
667
 
 
668
 
            >>> c = Client()
669
 
            >>> c.login(username='fred', password='secret')
670
 
 
671
 
            # Now you can access a view that's only available to logged-in users.
672
 
 
673
 
        If you're using a different authentication backend, this method may
674
 
        require different credentials. It requires whichever credentials are
675
 
        required by your backend's ``authenticate()`` method.
676
 
 
677
 
        ``login()`` returns ``True`` if it the credentials were accepted and
678
 
        login was successful.
679
 
 
680
 
        Finally, you'll need to remember to create user accounts before you can
681
 
        use this method. As we explained above, the test runner is executed
682
 
        using a test database, which contains no users by default. As a result,
683
 
        user accounts that are valid on your production site will not work
684
 
        under test conditions. You'll need to create users as part of the test
685
 
        suite -- either manually (using the Django model API) or with a test
686
 
        fixture. Remember that if you want your test user to have a password,
687
 
        you can't set the user's password by setting the password attribute
688
 
        directly -- you must use the
689
 
        :meth:`~django.contrib.auth.models.User.set_password()` function to
690
 
        store a correctly hashed password. Alternatively, you can use the
691
 
        :meth:`~django.contrib.auth.models.UserManager.create_user` helper
692
 
        method to create a new user with a correctly hashed password.
693
 
 
694
 
    .. method:: Client.logout()
695
 
 
696
 
        If your site uses Django's :doc:`authentication system</topics/auth/index>`,
697
 
        the ``logout()`` method can be used to simulate the effect of a user
698
 
        logging out of your site.
699
 
 
700
 
        After you call this method, the test client will have all the cookies
701
 
        and session data cleared to defaults. Subsequent requests will appear
702
 
        to come from an :class:`~django.contrib.auth.models.AnonymousUser`.
703
 
 
704
 
Testing responses
705
 
~~~~~~~~~~~~~~~~~
706
 
 
707
 
The ``get()`` and ``post()`` methods both return a ``Response`` object. This
708
 
``Response`` object is *not* the same as the ``HttpResponse`` object returned
709
 
Django views; the test response object has some additional data useful for
710
 
test code to verify.
711
 
 
712
 
Specifically, a ``Response`` object has the following attributes:
713
 
 
714
 
.. class:: Response()
715
 
 
716
 
    .. attribute:: client
717
 
 
718
 
        The test client that was used to make the request that resulted in the
719
 
        response.
720
 
 
721
 
    .. attribute:: content
722
 
 
723
 
        The body of the response, as a string. This is the final page content as
724
 
        rendered by the view, or any error message.
725
 
 
726
 
    .. attribute:: context
727
 
 
728
 
        The template ``Context`` instance that was used to render the template that
729
 
        produced the response content.
730
 
 
731
 
        If the rendered page used multiple templates, then ``context`` will be a
732
 
        list of ``Context`` objects, in the order in which they were rendered.
733
 
 
734
 
        Regardless of the number of templates used during rendering, you can
735
 
        retrieve context values using the ``[]`` operator. For example, the
736
 
        context variable ``name`` could be retrieved using::
737
 
 
738
 
            >>> response = client.get('/foo/')
739
 
            >>> response.context['name']
740
 
            'Arthur'
741
 
 
742
 
    .. attribute:: request
743
 
 
744
 
        The request data that stimulated the response.
745
 
 
746
 
    .. attribute:: status_code
747
 
 
748
 
        The HTTP status of the response, as an integer. See
749
 
        :rfc:`2616#section-10` for a full list of HTTP status codes.
750
 
 
751
 
    .. attribute:: templates
752
 
 
753
 
        A list of ``Template`` instances used to render the final content, in
754
 
        the order they were rendered. For each template in the list, use
755
 
        ``template.name`` to get the template's file name, if the template was
756
 
        loaded from a file. (The name is a string such as
757
 
        ``'admin/index.html'``.)
758
 
 
759
 
You can also use dictionary syntax on the response object to query the value
760
 
of any settings in the HTTP headers. For example, you could determine the
761
 
content type of a response using ``response['Content-Type']``.
762
 
 
763
 
Exceptions
764
 
~~~~~~~~~~
765
 
 
766
 
If you point the test client at a view that raises an exception, that exception
767
 
will be visible in the test case. You can then use a standard ``try ... except``
768
 
block or :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
769
 
 
770
 
The only exceptions that are not visible to the test client are ``Http404``,
771
 
``PermissionDenied`` and ``SystemExit``. Django catches these exceptions
772
 
internally and converts them into the appropriate HTTP response codes. In these
773
 
cases, you can check ``response.status_code`` in your test.
774
 
 
775
 
Persistent state
776
 
~~~~~~~~~~~~~~~~
777
 
 
778
 
The test client is stateful. If a response returns a cookie, then that cookie
779
 
will be stored in the test client and sent with all subsequent ``get()`` and
780
 
``post()`` requests.
781
 
 
782
 
Expiration policies for these cookies are not followed. If you want a cookie
783
 
to expire, either delete it manually or create a new ``Client`` instance (which
784
 
will effectively delete all cookies).
785
 
 
786
 
A test client has two attributes that store persistent state information. You
787
 
can access these properties as part of a test condition.
788
 
 
789
 
.. attribute:: Client.cookies
790
 
 
791
 
    A Python :class:`~Cookie.SimpleCookie` object, containing the current values
792
 
    of all the client cookies. See the documentation of the :mod:`Cookie` module
793
 
    for more.
794
 
 
795
 
.. attribute:: Client.session
796
 
 
797
 
    A dictionary-like object containing session information. See the
798
 
    :doc:`session documentation</topics/http/sessions>` for full details.
799
 
 
800
 
    To modify the session and then save it, it must be stored in a variable
801
 
    first (because a new ``SessionStore`` is created every time this property
802
 
    is accessed)::
803
 
 
804
 
        def test_something(self):
805
 
            session = self.client.session
806
 
            session['somekey'] = 'test'
807
 
            session.save()
808
 
 
809
 
Example
810
 
~~~~~~~
811
 
 
812
 
The following is a simple unit test using the test client::
813
 
 
814
 
    from django.utils import unittest
815
 
    from django.test.client import Client
816
 
 
817
 
    class SimpleTest(unittest.TestCase):
818
 
        def setUp(self):
819
 
            # Every test needs a client.
820
 
            self.client = Client()
821
 
 
822
 
        def test_details(self):
823
 
            # Issue a GET request.
824
 
            response = self.client.get('/customer/details/')
825
 
 
826
 
            # Check that the response is 200 OK.
827
 
            self.assertEqual(response.status_code, 200)
828
 
 
829
 
            # Check that the rendered context contains 5 customers.
830
 
            self.assertEqual(len(response.context['customers']), 5)
831
 
 
832
 
.. seealso::
833
 
 
834
 
    :class:`django.test.client.RequestFactory`
835
 
 
836
 
.. _django-testcase-subclasses:
837
 
 
838
 
Provided test case classes
839
 
--------------------------
840
 
 
841
 
.. currentmodule:: django.test
842
 
 
843
 
Normal Python unit test classes extend a base class of
844
 
:class:`unittest.TestCase`. Django provides a few extensions of this base class:
845
 
 
846
 
.. _testcase_hierarchy_diagram:
847
 
 
848
 
.. figure:: _images/django_unittest_classes_hierarchy.*
849
 
   :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
850
 
   :width: 508
851
 
   :height: 391
852
 
 
853
 
   Hierarchy of Django unit testing classes
854
 
 
855
 
Regardless of the version of Python you're using, if you've installed
856
 
``unittest2``, ``django.utils.unittest`` will point to that library.
857
 
 
858
 
SimpleTestCase
859
 
~~~~~~~~~~~~~~
860
 
 
861
 
.. class:: SimpleTestCase()
862
 
 
863
 
A thin subclass of :class:`unittest.TestCase`, it extends it with some basic
864
 
functionality like:
865
 
 
866
 
* Saving and restoring the Python warning machinery state.
867
 
* Some useful assertions like:
868
 
 
869
 
  * Checking that a callable :meth:`raises a certain exception
870
 
    <SimpleTestCase.assertRaisesMessage>`.
871
 
  * Testing form field :meth:`rendering and error treatment
872
 
    <SimpleTestCase.assertFieldOutput>`.
873
 
  * Testing :meth:`HTML responses for the presence/lack of a given fragment
874
 
    <SimpleTestCase.assertContains>`.
875
 
  * Verifying that a template :meth:`has/hasn't been used to generate a given
876
 
    response content <SimpleTestCase.assertTemplateUsed>`.
877
 
  * Verifying a HTTP :meth:`redirect <SimpleTestCase.assertRedirects>` is
878
 
    performed by the app.
879
 
  * Robustly testing two :meth:`HTML fragments <SimpleTestCase.assertHTMLEqual>`
880
 
    for equality/inequality or :meth:`containment <SimpleTestCase.assertInHTML>`.
881
 
  * Robustly testing two :meth:`XML fragments <SimpleTestCase.assertXMLEqual>`
882
 
    for equality/inequality.
883
 
  * Robustly testing two :meth:`JSON fragments <SimpleTestCase.assertJSONEqual>`
884
 
    for equality.
885
 
 
886
 
* The ability to run tests with :ref:`modified settings <overriding-settings>`.
887
 
* Using the :attr:`~SimpleTestCase.client` :class:`~django.test.client.Client`.
888
 
* Custom test-time :attr:`URL maps <SimpleTestCase.urls>`.
889
 
 
890
 
.. versionchanged:: 1.6
891
 
 
892
 
    The latter two features were moved from ``TransactionTestCase`` to
893
 
    ``SimpleTestCase`` in Django 1.6.
894
 
 
895
 
If you need any of the other more complex and heavyweight Django-specific
896
 
features like:
897
 
 
898
 
* Testing or using the ORM.
899
 
* Database :attr:`~TransactionTestCase.fixtures`.
900
 
* Test :ref:`skipping based on database backend features <skipping-tests>`.
901
 
* The remaining specialized :meth:`assert*
902
 
  <TransactionTestCase.assertQuerysetEqual>` methods.
903
 
 
904
 
then you should use :class:`~django.test.TransactionTestCase` or
905
 
:class:`~django.test.TestCase` instead.
906
 
 
907
 
``SimpleTestCase`` inherits from ``django.utils.unittest.TestCase``.
908
 
 
909
 
TransactionTestCase
910
 
~~~~~~~~~~~~~~~~~~~
911
 
 
912
 
.. class:: TransactionTestCase()
913
 
 
914
 
Django's ``TestCase`` class (described below) makes use of database transaction
915
 
facilities to speed up the process of resetting the database to a known state
916
 
at the beginning of each test. A consequence of this, however, is that the
917
 
effects of transaction commit and rollback cannot be tested by a Django
918
 
``TestCase`` class. If your test requires testing of such transactional
919
 
behavior, you should use a Django ``TransactionTestCase``.
920
 
 
921
 
``TransactionTestCase`` and ``TestCase`` are identical except for the manner
922
 
in which the database is reset to a known state and the ability for test code
923
 
to test the effects of commit and rollback:
924
 
 
925
 
* A ``TransactionTestCase`` resets the database after the test runs by
926
 
  truncating all tables. A ``TransactionTestCase`` may call commit and rollback
927
 
  and observe the effects of these calls on the database.
928
 
 
929
 
* A ``TestCase``, on the other hand, does not truncate tables after a test.
930
 
  Instead, it encloses the test code in a database transaction that is rolled
931
 
  back at the end of the test. Both explicit commits like
932
 
  ``transaction.commit()`` and implicit ones that may be caused by
933
 
  ``transaction.atomic()`` are replaced with a ``nop`` operation. This
934
 
  guarantees that the rollback at the end of the test restores the database to
935
 
  its initial state.
936
 
 
937
 
  When running on a database that does not support rollback (e.g. MySQL with the
938
 
  MyISAM storage engine), ``TestCase`` falls back to initializing the database
939
 
  by truncating tables and reloading initial data.
940
 
 
941
 
.. warning::
942
 
 
943
 
    While ``commit`` and ``rollback`` operations still *appear* to work when
944
 
    used in ``TestCase``, no actual commit or rollback will be performed by the
945
 
    database. This can cause your tests to pass or fail unexpectedly. Always
946
 
    use ``TransactionTestCase`` when testing transactional behavior.
947
 
 
948
 
.. versionchanged:: 1.5
949
 
 
950
 
    Prior to 1.5, :class:`~django.test.TransactionTestCase` flushed the
951
 
    database tables *before* each test. In Django 1.5, this is instead done
952
 
    *after* the test has been run.
953
 
 
954
 
    When the flush took place before the test, it was guaranteed that primary
955
 
    key values started at one in :class:`~django.test.TransactionTestCase`
956
 
    tests.
957
 
 
958
 
    Tests should not depend on this behavior, but for legacy tests that do,
959
 
    the :attr:`~TransactionTestCase.reset_sequences` attribute can be used
960
 
    until the test has been properly updated.
961
 
 
962
 
.. versionchanged:: 1.5
963
 
 
964
 
    The order in which tests are run has changed. See `Order in which tests are
965
 
    executed`_.
966
 
 
967
 
``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
968
 
 
969
 
TestCase
970
 
~~~~~~~~
971
 
 
972
 
.. class:: TestCase()
973
 
 
974
 
This class provides some additional capabilities that can be useful for testing
975
 
Web sites.
976
 
 
977
 
Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is
978
 
easy: Just change the base class of your test from ``'unittest.TestCase'`` to
979
 
``'django.test.TestCase'``. All of the standard Python unit test functionality
980
 
will continue to be available, but it will be augmented with some useful
981
 
additions, including:
982
 
 
983
 
* Automatic loading of fixtures.
984
 
 
985
 
* Wraps each test in a transaction.
986
 
 
987
 
* Creates a TestClient instance.
988
 
 
989
 
* Django-specific assertions for testing for things like redirection and form
990
 
  errors.
991
 
 
992
 
.. versionchanged:: 1.5
993
 
 
994
 
    The order in which tests are run has changed. See `Order in which tests are
995
 
    executed`_.
996
 
 
997
 
``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
998
 
 
999
 
.. _live-test-server:
1000
 
 
1001
 
LiveServerTestCase
1002
 
~~~~~~~~~~~~~~~~~~
1003
 
 
1004
 
.. class:: LiveServerTestCase()
1005
 
 
1006
 
``LiveServerTestCase`` does basically the same as
1007
 
:class:`~django.test.TransactionTestCase` with one extra feature: it launches a
1008
 
live Django server in the background on setup, and shuts it down on teardown.
1009
 
This allows the use of automated test clients other than the
1010
 
:ref:`Django dummy client <test-client>` such as, for example, the Selenium_
1011
 
client, to execute a series of functional tests inside a browser and simulate a
1012
 
real user's actions.
1013
 
 
1014
 
By default the live server's address is ``'localhost:8081'`` and the full URL
1015
 
can be accessed during the tests with ``self.live_server_url``. If you'd like
1016
 
to change the default address (in the case, for example, where the 8081 port is
1017
 
already taken) then you may pass a different one to the :djadmin:`test` command
1018
 
via the :djadminopt:`--liveserver` option, for example:
1019
 
 
1020
 
.. code-block:: bash
1021
 
 
1022
 
    ./manage.py test --liveserver=localhost:8082
1023
 
 
1024
 
Another way of changing the default server address is by setting the
1025
 
`DJANGO_LIVE_TEST_SERVER_ADDRESS` environment variable somewhere in your
1026
 
code (for example, in a :ref:`custom test runner<topics-testing-test_runner>`):
1027
 
 
1028
 
.. code-block:: python
1029
 
 
1030
 
    import os
1031
 
    os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8082'
1032
 
 
1033
 
In the case where the tests are run by multiple processes in parallel (for
1034
 
example, in the context of several simultaneous `continuous integration`_
1035
 
builds), the processes will compete for the same address, and therefore your
1036
 
tests might randomly fail with an "Address already in use" error. To avoid this
1037
 
problem, you can pass a comma-separated list of ports or ranges of ports (at
1038
 
least as many as the number of potential parallel processes). For example:
1039
 
 
1040
 
.. code-block:: bash
1041
 
 
1042
 
    ./manage.py test --liveserver=localhost:8082,8090-8100,9000-9200,7041
1043
 
 
1044
 
Then, during test execution, each new live test server will try every specified
1045
 
port until it finds one that is free and takes it.
1046
 
 
1047
 
.. _continuous integration: http://en.wikipedia.org/wiki/Continuous_integration
1048
 
 
1049
 
To demonstrate how to use ``LiveServerTestCase``, let's write a simple Selenium
1050
 
test. First of all, you need to install the `selenium package`_ into your
1051
 
Python path:
1052
 
 
1053
 
.. code-block:: bash
1054
 
 
1055
 
   pip install selenium
1056
 
 
1057
 
Then, add a ``LiveServerTestCase``-based test to your app's tests module
1058
 
(for example: ``myapp/tests.py``). The code for this test may look as follows:
1059
 
 
1060
 
.. code-block:: python
1061
 
 
1062
 
    from django.test import LiveServerTestCase
1063
 
    from selenium.webdriver.firefox.webdriver import WebDriver
1064
 
 
1065
 
    class MySeleniumTests(LiveServerTestCase):
1066
 
        fixtures = ['user-data.json']
1067
 
 
1068
 
        @classmethod
1069
 
        def setUpClass(cls):
1070
 
            cls.selenium = WebDriver()
1071
 
            super(MySeleniumTests, cls).setUpClass()
1072
 
 
1073
 
        @classmethod
1074
 
        def tearDownClass(cls):
1075
 
            cls.selenium.quit()
1076
 
            super(MySeleniumTests, cls).tearDownClass()
1077
 
 
1078
 
        def test_login(self):
1079
 
            self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
1080
 
            username_input = self.selenium.find_element_by_name("username")
1081
 
            username_input.send_keys('myuser')
1082
 
            password_input = self.selenium.find_element_by_name("password")
1083
 
            password_input.send_keys('secret')
1084
 
            self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
1085
 
 
1086
 
Finally, you may run the test as follows:
1087
 
 
1088
 
.. code-block:: bash
1089
 
 
1090
 
    ./manage.py test myapp.MySeleniumTests.test_login
1091
 
 
1092
 
This example will automatically open Firefox then go to the login page, enter
1093
 
the credentials and press the "Log in" button. Selenium offers other drivers in
1094
 
case you do not have Firefox installed or wish to use another browser. The
1095
 
example above is just a tiny fraction of what the Selenium client can do; check
1096
 
out the `full reference`_ for more details.
1097
 
 
1098
 
.. _Selenium: http://seleniumhq.org/
1099
 
.. _selenium package: https://pypi.python.org/pypi/selenium
1100
 
.. _full reference: http://selenium-python.readthedocs.org/en/latest/api.html
1101
 
.. _Firefox: http://www.mozilla.com/firefox/
1102
 
 
1103
 
.. note::
1104
 
 
1105
 
    ``LiveServerTestCase`` makes use of the :doc:`staticfiles contrib app
1106
 
    </howto/static-files/index>` so you'll need to have your project configured
1107
 
    accordingly (in particular by setting :setting:`STATIC_URL`).
1108
 
 
1109
 
.. note::
1110
 
 
1111
 
    When using an in-memory SQLite database to run the tests, the same database
1112
 
    connection will be shared by two threads in parallel: the thread in which
1113
 
    the live server is run and the thread in which the test case is run. It's
1114
 
    important to prevent simultaneous database queries via this shared
1115
 
    connection by the two threads, as that may sometimes randomly cause the
1116
 
    tests to fail. So you need to ensure that the two threads don't access the
1117
 
    database at the same time. In particular, this means that in some cases
1118
 
    (for example, just after clicking a link or submitting a form), you might
1119
 
    need to check that a response is received by Selenium and that the next
1120
 
    page is loaded before proceeding with further test execution.
1121
 
    Do this, for example, by making Selenium wait until the ``<body>`` HTML tag
1122
 
    is found in the response (requires Selenium > 2.13):
1123
 
 
1124
 
    .. code-block:: python
1125
 
 
1126
 
        def test_login(self):
1127
 
            from selenium.webdriver.support.wait import WebDriverWait
1128
 
            timeout = 2
1129
 
            ...
1130
 
            self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
1131
 
            # Wait until the response is received
1132
 
            WebDriverWait(self.selenium, timeout).until(
1133
 
                lambda driver: driver.find_element_by_tag_name('body'))
1134
 
 
1135
 
    The tricky thing here is that there's really no such thing as a "page load,"
1136
 
    especially in modern Web apps that generate HTML dynamically after the
1137
 
    server generates the initial document. So, simply checking for the presence
1138
 
    of ``<body>`` in the response might not necessarily be appropriate for all
1139
 
    use cases. Please refer to the `Selenium FAQ`_ and
1140
 
    `Selenium documentation`_ for more information.
1141
 
 
1142
 
    .. _Selenium FAQ: http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
1143
 
    .. _Selenium documentation: http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits
1144
 
 
1145
 
Test cases features
1146
 
-------------------
1147
 
 
1148
 
Default test client
1149
 
~~~~~~~~~~~~~~~~~~~
1150
 
 
1151
 
.. attribute:: SimpleTestCase.client
1152
 
 
1153
 
Every test case in a ``django.test.*TestCase`` instance has access to an
1154
 
instance of a Django test client. This client can be accessed as
1155
 
``self.client``. This client is recreated for each test, so you don't have to
1156
 
worry about state (such as cookies) carrying over from one test to another.
1157
 
 
1158
 
This means, instead of instantiating a ``Client`` in each test::
1159
 
 
1160
 
    from django.utils import unittest
1161
 
    from django.test.client import Client
1162
 
 
1163
 
    class SimpleTest(unittest.TestCase):
1164
 
        def test_details(self):
1165
 
            client = Client()
1166
 
            response = client.get('/customer/details/')
1167
 
            self.assertEqual(response.status_code, 200)
1168
 
 
1169
 
        def test_index(self):
1170
 
            client = Client()
1171
 
            response = client.get('/customer/index/')
1172
 
            self.assertEqual(response.status_code, 200)
1173
 
 
1174
 
...you can just refer to ``self.client``, like so::
1175
 
 
1176
 
    from django.test import TestCase
1177
 
 
1178
 
    class SimpleTest(TestCase):
1179
 
        def test_details(self):
1180
 
            response = self.client.get('/customer/details/')
1181
 
            self.assertEqual(response.status_code, 200)
1182
 
 
1183
 
        def test_index(self):
1184
 
            response = self.client.get('/customer/index/')
1185
 
            self.assertEqual(response.status_code, 200)
1186
 
 
1187
 
Customizing the test client
1188
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~
1189
 
 
1190
 
.. attribute:: SimpleTestCase.client_class
1191
 
 
1192
 
If you want to use a different ``Client`` class (for example, a subclass
1193
 
with customized behavior), use the :attr:`~SimpleTestCase.client_class` class
1194
 
attribute::
1195
 
 
1196
 
    from django.test import TestCase
1197
 
    from django.test.client import Client
1198
 
 
1199
 
    class MyTestClient(Client):
1200
 
        # Specialized methods for your environment...
1201
 
 
1202
 
    class MyTest(TestCase):
1203
 
        client_class = MyTestClient
1204
 
 
1205
 
        def test_my_stuff(self):
1206
 
            # Here self.client is an instance of MyTestClient...
1207
 
            call_some_test_code()
1208
 
 
1209
 
.. _topics-testing-fixtures:
1210
 
 
1211
 
Fixture loading
1212
 
~~~~~~~~~~~~~~~
1213
 
 
1214
 
.. attribute:: TransactionTestCase.fixtures
1215
 
 
1216
 
A test case for a database-backed Web site isn't much use if there isn't any
1217
 
data in the database. To make it easy to put test data into the database,
1218
 
Django's custom ``TransactionTestCase`` class provides a way of loading
1219
 
**fixtures**.
1220
 
 
1221
 
A fixture is a collection of data that Django knows how to import into a
1222
 
database. For example, if your site has user accounts, you might set up a
1223
 
fixture of fake user accounts in order to populate your database during tests.
1224
 
 
1225
 
The most straightforward way of creating a fixture is to use the
1226
 
:djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
1227
 
already have some data in your database. See the :djadmin:`dumpdata
1228
 
documentation<dumpdata>` for more details.
1229
 
 
1230
 
.. note::
1231
 
 
1232
 
    If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
1233
 
    already used a fixture without even knowing it! When you call
1234
 
    :djadmin:`syncdb` in the database for the first time, Django
1235
 
    installs a fixture called ``initial_data``. This gives you a way
1236
 
    of populating a new database with any initial data, such as a
1237
 
    default set of categories.
1238
 
 
1239
 
    Fixtures with other names can always be installed manually using
1240
 
    the :djadmin:`manage.py loaddata<loaddata>` command.
1241
 
 
1242
 
.. admonition:: Initial SQL data and testing
1243
 
 
1244
 
    Django provides a second way to insert initial data into models --
1245
 
    the :ref:`custom SQL hook <initial-sql>`. However, this technique
1246
 
    *cannot* be used to provide initial data for testing purposes.
1247
 
    Django's test framework flushes the contents of the test database
1248
 
    after each test; as a result, any data added using the custom SQL
1249
 
    hook will be lost.
1250
 
 
1251
 
Once you've created a fixture and placed it in a ``fixtures`` directory in one
1252
 
of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
1253
 
specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
1254
 
subclass::
1255
 
 
1256
 
    from django.test import TestCase
1257
 
    from myapp.models import Animal
1258
 
 
1259
 
    class AnimalTestCase(TestCase):
1260
 
        fixtures = ['mammals.json', 'birds']
1261
 
 
1262
 
        def setUp(self):
1263
 
            # Test definitions as before.
1264
 
            call_setup_methods()
1265
 
 
1266
 
        def testFluffyAnimals(self):
1267
 
            # A test that uses the fixtures.
1268
 
            call_some_test_code()
1269
 
 
1270
 
Here's specifically what will happen:
1271
 
 
1272
 
* At the start of each test case, before ``setUp()`` is run, Django will
1273
 
  flush the database, returning the database to the state it was in
1274
 
  directly after :djadmin:`syncdb` was called.
1275
 
 
1276
 
* Then, all the named fixtures are installed. In this example, Django will
1277
 
  install any JSON fixture named ``mammals``, followed by any fixture named
1278
 
  ``birds``. See the :djadmin:`loaddata` documentation for more
1279
 
  details on defining and installing fixtures.
1280
 
 
1281
 
This flush/load procedure is repeated for each test in the test case, so you
1282
 
can be certain that the outcome of a test will not be affected by another test,
1283
 
or by the order of test execution.
1284
 
 
1285
 
By default, fixtures are only loaded into the ``default`` database. If you are
1286
 
using multiple databases and set :attr:`multi_db=True
1287
 
<TransactionTestCase.multi_db>`, fixtures will be loaded into all databases.
1288
 
 
1289
 
URLconf configuration
1290
 
~~~~~~~~~~~~~~~~~~~~~
1291
 
 
1292
 
.. attribute:: SimpleTestCase.urls
1293
 
 
1294
 
If your application provides views, you may want to include tests that use the
1295
 
test client to exercise those views. However, an end user is free to deploy the
1296
 
views in your application at any URL of their choosing. This means that your
1297
 
tests can't rely upon the fact that your views will be available at a
1298
 
particular URL.
1299
 
 
1300
 
In order to provide a reliable URL space for your test,
1301
 
``django.test.*TestCase`` classes provide the ability to customize the URLconf
1302
 
configuration for the duration of the execution of a test suite. If your
1303
 
``*TestCase`` instance defines an ``urls`` attribute, the ``*TestCase`` will use
1304
 
the value of that attribute as the :setting:`ROOT_URLCONF` for the duration
1305
 
of that test.
1306
 
 
1307
 
For example::
1308
 
 
1309
 
    from django.test import TestCase
1310
 
 
1311
 
    class TestMyViews(TestCase):
1312
 
        urls = 'myapp.test_urls'
1313
 
 
1314
 
        def testIndexPageView(self):
1315
 
            # Here you'd test your view using ``Client``.
1316
 
            call_some_test_code()
1317
 
 
1318
 
This test case will use the contents of ``myapp.test_urls`` as the
1319
 
URLconf for the duration of the test case.
1320
 
 
1321
 
.. _emptying-test-outbox:
1322
 
 
1323
 
Multi-database support
1324
 
~~~~~~~~~~~~~~~~~~~~~~
1325
 
 
1326
 
.. attribute:: TransactionTestCase.multi_db
1327
 
 
1328
 
Django sets up a test database corresponding to every database that is
1329
 
defined in the :setting:`DATABASES` definition in your settings
1330
 
file. However, a big part of the time taken to run a Django TestCase
1331
 
is consumed by the call to ``flush`` that ensures that you have a
1332
 
clean database at the start of each test run. If you have multiple
1333
 
databases, multiple flushes are required (one for each database),
1334
 
which can be a time consuming activity -- especially if your tests
1335
 
don't need to test multi-database activity.
1336
 
 
1337
 
As an optimization, Django only flushes the ``default`` database at
1338
 
the start of each test run. If your setup contains multiple databases,
1339
 
and you have a test that requires every database to be clean, you can
1340
 
use the ``multi_db`` attribute on the test suite to request a full
1341
 
flush.
1342
 
 
1343
 
For example::
1344
 
 
1345
 
    class TestMyViews(TestCase):
1346
 
        multi_db = True
1347
 
 
1348
 
        def testIndexPageView(self):
1349
 
            call_some_test_code()
1350
 
 
1351
 
This test case will flush *all* the test databases before running
1352
 
``testIndexPageView``.
1353
 
 
1354
 
The ``multi_db`` flag also affects into which databases the
1355
 
attr:`TransactionTestCase.fixtures` are loaded. By default (when
1356
 
``multi_db=False``), fixtures are only loaded into the ``default`` database.
1357
 
If ``multi_db=True``, fixtures are loaded into all databases.
1358
 
 
1359
 
.. _overriding-settings:
1360
 
 
1361
 
Overriding settings
1362
 
~~~~~~~~~~~~~~~~~~~
1363
 
 
1364
 
.. method:: SimpleTestCase.settings
1365
 
 
1366
 
For testing purposes it's often useful to change a setting temporarily and
1367
 
revert to the original value after running the testing code. For this use case
1368
 
Django provides a standard Python context manager (see :pep:`343`)
1369
 
:meth:`~django.test.SimpleTestCase.settings`, which can be used like this::
1370
 
 
1371
 
    from django.test import TestCase
1372
 
 
1373
 
    class LoginTestCase(TestCase):
1374
 
 
1375
 
        def test_login(self):
1376
 
 
1377
 
            # First check for the default behavior
1378
 
            response = self.client.get('/sekrit/')
1379
 
            self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
1380
 
 
1381
 
            # Then override the LOGIN_URL setting
1382
 
            with self.settings(LOGIN_URL='/other/login/'):
1383
 
                response = self.client.get('/sekrit/')
1384
 
                self.assertRedirects(response, '/other/login/?next=/sekrit/')
1385
 
 
1386
 
This example will override the :setting:`LOGIN_URL` setting for the code
1387
 
in the ``with`` block and reset its value to the previous state afterwards.
1388
 
 
1389
 
.. currentmodule:: django.test.utils
1390
 
 
1391
 
.. function:: override_settings
1392
 
 
1393
 
In case you want to override a setting for just one test method or even the
1394
 
whole :class:`~django.test.TestCase` class, Django provides the
1395
 
:func:`~django.test.utils.override_settings` decorator (see :pep:`318`). It's
1396
 
used like this::
1397
 
 
1398
 
    from django.test import TestCase
1399
 
    from django.test.utils import override_settings
1400
 
 
1401
 
    class LoginTestCase(TestCase):
1402
 
 
1403
 
        @override_settings(LOGIN_URL='/other/login/')
1404
 
        def test_login(self):
1405
 
            response = self.client.get('/sekrit/')
1406
 
            self.assertRedirects(response, '/other/login/?next=/sekrit/')
1407
 
 
1408
 
The decorator can also be applied to test case classes::
1409
 
 
1410
 
    from django.test import TestCase
1411
 
    from django.test.utils import override_settings
1412
 
 
1413
 
    @override_settings(LOGIN_URL='/other/login/')
1414
 
    class LoginTestCase(TestCase):
1415
 
 
1416
 
        def test_login(self):
1417
 
            response = self.client.get('/sekrit/')
1418
 
            self.assertRedirects(response, '/other/login/?next=/sekrit/')
1419
 
 
1420
 
.. note::
1421
 
 
1422
 
    When given a class, the decorator modifies the class directly and
1423
 
    returns it; it doesn't create and return a modified copy of it.  So if
1424
 
    you try to tweak the above example to assign the return value to a
1425
 
    different name than ``LoginTestCase``, you may be surprised to find that
1426
 
    the original ``LoginTestCase`` is still equally affected by the
1427
 
    decorator.
1428
 
 
1429
 
You can also simulate the absence of a setting by deleting it after settings
1430
 
have been overriden, like this::
1431
 
 
1432
 
    @override_settings()
1433
 
    def test_something(self):
1434
 
        del settings.LOGIN_URL
1435
 
        ...
1436
 
 
1437
 
When overriding settings, make sure to handle the cases in which your app's
1438
 
code uses a cache or similar feature that retains state even if the
1439
 
setting is changed. Django provides the
1440
 
:data:`django.test.signals.setting_changed` signal that lets you register
1441
 
callbacks to clean up and otherwise reset state when settings are changed.
1442
 
 
1443
 
Django itself uses this signal to reset various data:
1444
 
 
1445
 
================================ ========================
1446
 
Overriden settings               Data reset
1447
 
================================ ========================
1448
 
USE_TZ, TIME_ZONE                Databases timezone
1449
 
TEMPLATE_CONTEXT_PROCESSORS      Context processors cache
1450
 
TEMPLATE_LOADERS                 Template loaders cache
1451
 
SERIALIZATION_MODULES            Serializers cache
1452
 
LOCALE_PATHS, LANGUAGE_CODE      Default translation and loaded translations
1453
 
MEDIA_ROOT, DEFAULT_FILE_STORAGE Default file storage
1454
 
================================ ========================
1455
 
 
1456
 
Emptying the test outbox
1457
 
~~~~~~~~~~~~~~~~~~~~~~~~
1458
 
 
1459
 
If you use any of Django's custom ``TestCase`` classes, the test runner will
1460
 
clear the contents of the test email outbox at the start of each test case.
1461
 
 
1462
 
For more detail on email services during tests, see `Email services`_ below.
1463
 
 
1464
 
.. _assertions:
1465
 
 
1466
 
Assertions
1467
 
~~~~~~~~~~
1468
 
 
1469
 
.. currentmodule:: django.test
1470
 
 
1471
 
As Python's normal :class:`unittest.TestCase` class implements assertion methods
1472
 
such as :meth:`~unittest.TestCase.assertTrue` and
1473
 
:meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
1474
 
provides a number of custom assertion methods that are useful for testing Web
1475
 
applications:
1476
 
 
1477
 
The failure messages given by most of these assertion methods can be customized
1478
 
with the ``msg_prefix`` argument. This string will be prefixed to any failure
1479
 
message generated by the assertion. This allows you to provide additional
1480
 
details that may help you to identify the location and cause of an failure in
1481
 
your test suite.
1482
 
 
1483
 
.. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
1484
 
 
1485
 
    Asserts that execution of callable ``callable_obj`` raised the
1486
 
    ``expected_exception`` exception and that such exception has an
1487
 
    ``expected_message`` representation. Any other outcome is reported as a
1488
 
    failure. Similar to unittest's :meth:`~unittest.TestCase.assertRaisesRegexp`
1489
 
    with the difference that ``expected_message`` isn't a regular expression.
1490
 
 
1491
 
.. method:: SimpleTestCase.assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
1492
 
 
1493
 
    Asserts that a form field behaves correctly with various inputs.
1494
 
 
1495
 
    :param fieldclass: the class of the field to be tested.
1496
 
    :param valid: a dictionary mapping valid inputs to their expected cleaned
1497
 
        values.
1498
 
    :param invalid: a dictionary mapping invalid inputs to one or more raised
1499
 
        error messages.
1500
 
    :param field_args: the args passed to instantiate the field.
1501
 
    :param field_kwargs: the kwargs passed to instantiate the field.
1502
 
    :param empty_value: the expected clean output for inputs in ``empty_values``.
1503
 
 
1504
 
    For example, the following code tests that an ``EmailField`` accepts
1505
 
    "a@a.com" as a valid email address, but rejects "aaa" with a reasonable
1506
 
    error message::
1507
 
 
1508
 
        self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid email address.']})
1509
 
 
1510
 
.. method:: SimpleTestCase.assertFormError(response, form, field, errors, msg_prefix='')
1511
 
 
1512
 
    Asserts that a field on a form raises the provided list of errors when
1513
 
    rendered on the form.
1514
 
 
1515
 
    ``form`` is the name the ``Form`` instance was given in the template
1516
 
    context.
1517
 
 
1518
 
    ``field`` is the name of the field on the form to check. If ``field``
1519
 
    has a value of ``None``, non-field errors (errors you can access via
1520
 
    ``form.non_field_errors()``) will be checked.
1521
 
 
1522
 
    ``errors`` is an error string, or a list of error strings, that are
1523
 
    expected as a result of form validation.
1524
 
 
1525
 
.. method:: SimpleTestCase.assertFormsetError(response, formset, form_index, field, errors, msg_prefix='')
1526
 
 
1527
 
    .. versionadded:: 1.6
1528
 
 
1529
 
    Asserts that the ``formset`` raises the provided list of errors when
1530
 
    rendered.
1531
 
 
1532
 
    ``formset`` is the name the ``Formset`` instance was given in the template
1533
 
    context.
1534
 
 
1535
 
    ``form_index`` is the number of the form within the ``Formset``.  If
1536
 
    ``form_index`` has a value of ``None``, non-form errors (errors you can
1537
 
    access via ``formset.non_form_errors()``) will be checked.
1538
 
 
1539
 
    ``field`` is the name of the field on the form to check. If ``field``
1540
 
    has a value of ``None``, non-field errors (errors you can access via
1541
 
    ``form.non_field_errors()``) will be checked.
1542
 
 
1543
 
    ``errors`` is an error string, or a list of error strings, that are
1544
 
    expected as a result of form validation.
1545
 
 
1546
 
.. method:: SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
1547
 
 
1548
 
    Asserts that a ``Response`` instance produced the given ``status_code`` and
1549
 
    that ``text`` appears in the content of the response. If ``count`` is
1550
 
    provided, ``text`` must occur exactly ``count`` times in the response.
1551
 
 
1552
 
    Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
1553
 
    the response content will be based on HTML semantics instead of
1554
 
    character-by-character equality. Whitespace is ignored in most cases,
1555
 
    attribute ordering is not significant. See
1556
 
    :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
1557
 
 
1558
 
.. method:: SimpleTestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
1559
 
 
1560
 
    Asserts that a ``Response`` instance produced the given ``status_code`` and
1561
 
    that ``text`` does not appears in the content of the response.
1562
 
 
1563
 
    Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
1564
 
    the response content will be based on HTML semantics instead of
1565
 
    character-by-character equality. Whitespace is ignored in most cases,
1566
 
    attribute ordering is not significant. See
1567
 
    :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
1568
 
 
1569
 
.. method:: SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='')
1570
 
 
1571
 
    Asserts that the template with the given name was used in rendering the
1572
 
    response.
1573
 
 
1574
 
    The name is a string such as ``'admin/index.html'``.
1575
 
 
1576
 
    You can use this as a context manager, like this::
1577
 
 
1578
 
        with self.assertTemplateUsed('index.html'):
1579
 
            render_to_string('index.html')
1580
 
        with self.assertTemplateUsed(template_name='index.html'):
1581
 
            render_to_string('index.html')
1582
 
 
1583
 
.. method:: SimpleTestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
1584
 
 
1585
 
    Asserts that the template with the given name was *not* used in rendering
1586
 
    the response.
1587
 
 
1588
 
    You can use this as a context manager in the same way as
1589
 
    :meth:`~SimpleTestCase.assertTemplateUsed`.
1590
 
 
1591
 
.. method:: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='')
1592
 
 
1593
 
    Asserts that the response return a ``status_code`` redirect status, it
1594
 
    redirected to ``expected_url`` (including any GET data), and the final
1595
 
    page was received with ``target_status_code``.
1596
 
 
1597
 
    If your request used the ``follow`` argument, the ``expected_url`` and
1598
 
    ``target_status_code`` will be the url and status code for the final
1599
 
    point of the redirect chain.
1600
 
 
1601
 
.. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
1602
 
 
1603
 
    Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
1604
 
    is based on HTML semantics. The comparison takes following things into
1605
 
    account:
1606
 
 
1607
 
    * Whitespace before and after HTML tags is ignored.
1608
 
    * All types of whitespace are considered equivalent.
1609
 
    * All open tags are closed implicitly, e.g. when a surrounding tag is
1610
 
      closed or the HTML document ends.
1611
 
    * Empty tags are equivalent to their self-closing version.
1612
 
    * The ordering of attributes of an HTML element is not significant.
1613
 
    * Attributes without an argument are equal to attributes that equal in
1614
 
      name and value (see the examples).
1615
 
 
1616
 
    The following examples are valid tests and don't raise any
1617
 
    ``AssertionError``::
1618
 
 
1619
 
        self.assertHTMLEqual('<p>Hello <b>world!</p>',
1620
 
            '''<p>
1621
 
                Hello   <b>world! <b/>
1622
 
            </p>''')
1623
 
        self.assertHTMLEqual(
1624
 
            '<input type="checkbox" checked="checked" id="id_accept_terms" />',
1625
 
            '<input id="id_accept_terms" type='checkbox' checked>')
1626
 
 
1627
 
    ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
1628
 
    raised if one of them cannot be parsed.
1629
 
 
1630
 
    Output in case of error can be customized with the ``msg`` argument.
1631
 
 
1632
 
.. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
1633
 
 
1634
 
    Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
1635
 
    comparison is based on HTML semantics. See
1636
 
    :meth:`~SimpleTestCase.assertHTMLEqual` for details.
1637
 
 
1638
 
    ``html1`` and ``html2`` must be valid HTML. An ``AssertionError`` will be
1639
 
    raised if one of them cannot be parsed.
1640
 
 
1641
 
    Output in case of error can be customized with the ``msg`` argument.
1642
 
 
1643
 
.. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
1644
 
 
1645
 
    .. versionadded:: 1.5
1646
 
 
1647
 
    Asserts that the strings ``xml1`` and ``xml2`` are equal. The
1648
 
    comparison is based on XML semantics. Similarily to
1649
 
    :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
1650
 
    made on parsed content, hence only semantic differences are considered, not
1651
 
    syntax differences. When unvalid XML is passed in any parameter, an
1652
 
    ``AssertionError`` is always raised, even if both string are identical.
1653
 
 
1654
 
    Output in case of error can be customized with the ``msg`` argument.
1655
 
 
1656
 
.. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
1657
 
 
1658
 
    .. versionadded:: 1.5
1659
 
 
1660
 
    Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
1661
 
    comparison is based on XML semantics. See
1662
 
    :meth:`~SimpleTestCase.assertXMLEqual` for details.
1663
 
 
1664
 
    Output in case of error can be customized with the ``msg`` argument.
1665
 
 
1666
 
.. method:: SimpleTestCase.assertInHTML(needle, haystack, count=None, msg_prefix='')
1667
 
 
1668
 
    .. versionadded:: 1.5
1669
 
 
1670
 
    Asserts that the HTML fragment ``needle`` is contained in the ``haystack`` one.
1671
 
 
1672
 
    If the ``count`` integer argument is specified, then additionally the number
1673
 
    of ``needle`` occurrences will be strictly verified.
1674
 
 
1675
 
    Whitespace in most cases is ignored, and attribute ordering is not
1676
 
    significant. The passed-in arguments must be valid HTML.
1677
 
 
1678
 
.. method:: SimpleTestCase.assertJSONEqual(raw, expected_data, msg=None)
1679
 
 
1680
 
    .. versionadded:: 1.5
1681
 
 
1682
 
    Asserts that the JSON fragments ``raw`` and ``expected_data`` are equal.
1683
 
    Usual JSON non-significant whitespace rules apply as the heavyweight is
1684
 
    delegated to the :mod:`json` library.
1685
 
 
1686
 
    Output in case of error can be customized with the ``msg`` argument.
1687
 
 
1688
 
.. method:: TransactionTestCase.assertQuerysetEqual(qs, values, transform=repr, ordered=True)
1689
 
 
1690
 
    Asserts that a queryset ``qs`` returns a particular list of values ``values``.
1691
 
 
1692
 
    The comparison of the contents of ``qs`` and ``values`` is performed using
1693
 
    the function ``transform``; by default, this means that the ``repr()`` of
1694
 
    each value is compared. Any other callable can be used if ``repr()`` doesn't
1695
 
    provide a unique or helpful comparison.
1696
 
 
1697
 
    By default, the comparison is also ordering dependent. If ``qs`` doesn't
1698
 
    provide an implicit ordering, you can set the ``ordered`` parameter to
1699
 
    ``False``, which turns the comparison into a Python set comparison.
1700
 
 
1701
 
    .. versionchanged:: 1.6
1702
 
 
1703
 
        The method now checks for undefined order and raises ``ValueError``
1704
 
        if undefined order is spotted. The ordering is seen as undefined if
1705
 
        the given ``qs`` isn't ordered and the comparison is against more
1706
 
        than one ordered values.
1707
 
 
1708
 
.. method:: TransactionTestCase.assertNumQueries(num, func, *args, **kwargs)
1709
 
 
1710
 
    Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
1711
 
    ``num`` database queries are executed.
1712
 
 
1713
 
    If a ``"using"`` key is present in ``kwargs`` it is used as the database
1714
 
    alias for which to check the number of queries.  If you wish to call a
1715
 
    function with a ``using`` parameter you can do it by wrapping the call with
1716
 
    a ``lambda`` to add an extra parameter::
1717
 
 
1718
 
        self.assertNumQueries(7, lambda: my_function(using=7))
1719
 
 
1720
 
    You can also use this as a context manager::
1721
 
 
1722
 
        with self.assertNumQueries(2):
1723
 
            Person.objects.create(name="Aaron")
1724
 
            Person.objects.create(name="Daniel")
1725
 
 
1726
 
.. _topics-testing-email:
1727
 
 
1728
 
Email services
1729
 
--------------
1730
 
 
1731
 
If any of your Django views send email using :doc:`Django's email
1732
 
functionality </topics/email>`, you probably don't want to send email each time
1733
 
you run a test using that view. For this reason, Django's test runner
1734
 
automatically redirects all Django-sent email to a dummy outbox. This lets you
1735
 
test every aspect of sending email -- from the number of messages sent to the
1736
 
contents of each message -- without actually sending the messages.
1737
 
 
1738
 
The test runner accomplishes this by transparently replacing the normal
1739
 
email backend with a testing backend.
1740
 
(Don't worry -- this has no effect on any other email senders outside of
1741
 
Django, such as your machine's mail server, if you're running one.)
1742
 
 
1743
 
.. currentmodule:: django.core.mail
1744
 
 
1745
 
.. data:: django.core.mail.outbox
1746
 
 
1747
 
During test running, each outgoing email is saved in
1748
 
``django.core.mail.outbox``. This is a simple list of all
1749
 
:class:`~django.core.mail.EmailMessage` instances that have been sent.
1750
 
The ``outbox`` attribute is a special attribute that is created *only* when
1751
 
the ``locmem`` email backend is used. It doesn't normally exist as part of the
1752
 
:mod:`django.core.mail` module and you can't import it directly. The code
1753
 
below shows how to access this attribute correctly.
1754
 
 
1755
 
Here's an example test that examines ``django.core.mail.outbox`` for length
1756
 
and contents::
1757
 
 
1758
 
    from django.core import mail
1759
 
    from django.test import TestCase
1760
 
 
1761
 
    class EmailTest(TestCase):
1762
 
        def test_send_email(self):
1763
 
            # Send message.
1764
 
            mail.send_mail('Subject here', 'Here is the message.',
1765
 
                'from@example.com', ['to@example.com'],
1766
 
                fail_silently=False)
1767
 
 
1768
 
            # Test that one message has been sent.
1769
 
            self.assertEqual(len(mail.outbox), 1)
1770
 
 
1771
 
            # Verify that the subject of the first message is correct.
1772
 
            self.assertEqual(mail.outbox[0].subject, 'Subject here')
1773
 
 
1774
 
As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
1775
 
at the start of every test in a Django ``*TestCase``. To empty the outbox
1776
 
manually, assign the empty list to ``mail.outbox``::
1777
 
 
1778
 
    from django.core import mail
1779
 
 
1780
 
    # Empty the test outbox
1781
 
    mail.outbox = []
1782
 
 
1783
 
.. _skipping-tests:
1784
 
 
1785
 
Skipping tests
1786
 
--------------
1787
 
 
1788
 
.. currentmodule:: django.test
1789
 
 
1790
 
The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
1791
 
:func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
1792
 
if you know ahead of time that those tests are going to fail under certain
1793
 
conditions.
1794
 
 
1795
 
For example, if your test requires a particular optional library in order to
1796
 
succeed, you could decorate the test case with :func:`@skipIf
1797
 
<unittest.skipIf>`. Then, the test runner will report that the test wasn't
1798
 
executed and why, instead of failing the test or omitting the test altogether.
1799
 
 
1800
 
To supplement these test skipping behaviors, Django provides two
1801
 
additional skip decorators. Instead of testing a generic boolean,
1802
 
these decorators check the capabilities of the database, and skip the
1803
 
test if the database doesn't support a specific named feature.
1804
 
 
1805
 
The decorators use a string identifier to describe database features.
1806
 
This string corresponds to attributes of the database connection
1807
 
features class. See ``django.db.backends.BaseDatabaseFeatures``
1808
 
class for a full list of database features that can be used as a basis
1809
 
for skipping tests.
1810
 
 
1811
 
.. function:: skipIfDBFeature(feature_name_string)
1812
 
 
1813
 
Skip the decorated test if the named database feature is supported.
1814
 
 
1815
 
For example, the following test will not be executed if the database
1816
 
supports transactions (e.g., it would *not* run under PostgreSQL, but
1817
 
it would under MySQL with MyISAM tables)::
1818
 
 
1819
 
    class MyTests(TestCase):
1820
 
        @skipIfDBFeature('supports_transactions')
1821
 
        def test_transaction_behavior(self):
1822
 
            # ... conditional test code
1823
 
 
1824
 
.. function:: skipUnlessDBFeature(feature_name_string)
1825
 
 
1826
 
Skip the decorated test if the named database feature is *not*
1827
 
supported.
1828
 
 
1829
 
For example, the following test will only be executed if the database
1830
 
supports transactions (e.g., it would run under PostgreSQL, but *not*
1831
 
under MySQL with MyISAM tables)::
1832
 
 
1833
 
    class MyTests(TestCase):
1834
 
        @skipUnlessDBFeature('supports_transactions')
1835
 
        def test_transaction_behavior(self):
1836
 
            # ... conditional test code