2014-11-25 19:04:38 +03:00
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
< meta charset = "utf-8" >
2017-01-08 19:42:48 +03:00
< meta name = "google-site-verification" content = "ZJtyq2wZOXvFw0RJ6rdHV_agvxjc5zkm9QgmdvNZB0s" / >
2015-05-15 11:19:49 +03:00
< title > Testing - Django REST framework< / title >
2014-11-25 19:04:38 +03:00
< link href = "../../img/favicon.ico" rel = "icon" type = "image/x-icon" >
< link rel = "canonical" href = "http://www.django-rest-framework.org/api-guide/testing/" / >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< meta name = "description" content = "Django, API, REST, Testing" >
< meta name = "author" content = "Tom Christie" >
<!-- Le styles -->
< link href = "../../css/prettify.css" rel = "stylesheet" >
< link href = "../../css/bootstrap.css" rel = "stylesheet" >
< link href = "../../css/bootstrap-responsive.css" rel = "stylesheet" >
< link href = "../../css/default.css" rel = "stylesheet" >
<!-- Le HTML5 shim, for IE6 - 8 support of HTML5 elements -->
<!-- [if lt IE 9]>
< script src = "http://html5shim.googlecode.com/svn/trunk/html5.js" > < / script >
<![endif]-->
< script type = "text/javascript" >
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18852272-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
< / script >
< style >
2016-05-26 13:48:39 +03:00
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
2014-11-25 19:04:38 +03:00
color: black;
2016-05-26 13:48:39 +03:00
}
2014-11-25 19:04:38 +03:00
@media (max-width: 767px) {
div.promo {
display: none;
}
}
< / style >
< / head >
< body onload = "prettyPrint()" class = "-page" >
< div class = "wrapper" >
< div class = "navbar navbar-inverse navbar-fixed-top" >
< div class = "navbar-inner" >
< div class = "container-fluid" >
< a class = "repo-link btn btn-primary btn-small" href = "https://github.com/tomchristie/django-rest-framework/tree/master" > GitHub< / a >
2015-06-04 17:37:22 +03:00
< a class = "repo-link btn btn-inverse btn-small " rel = "prev" href = "../settings/" >
2014-11-25 19:04:38 +03:00
Next < i class = "icon-arrow-right icon-white" > < / i >
< / a >
2015-06-04 17:37:22 +03:00
< a class = "repo-link btn btn-inverse btn-small " rel = "next" href = "../status-codes/" >
2014-11-25 19:04:38 +03:00
< i class = "icon-arrow-left icon-white" > < / i > Previous
< / a >
2015-06-04 17:37:22 +03:00
< a id = "search_modal_show" class = "repo-link btn btn-inverse btn-small" href = "#mkdocs_search_modal" data-toggle = "modal" data-target = "#mkdocs_search_modal" > < i class = "icon-search icon-white" > < / i > Search< / a >
2014-11-25 19:04:38 +03:00
< a class = "btn btn-navbar" data-toggle = "collapse" data-target = ".nav-collapse" >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< / a >
< a class = "brand" href = "http://www.django-rest-framework.org" > Django REST framework< / a >
< div class = "nav-collapse collapse" >
<!-- Main navigation -->
< ul class = "nav navbar-nav" >
2015-06-04 17:37:22 +03:00
< li >
< a href = "../.." > Home< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li class = "dropdown" >
2014-11-25 19:31:00 +03:00
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Tutorial < b class = "caret" > < / b > < / a >
2014-11-25 19:04:38 +03:00
< ul class = "dropdown-menu" >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/quickstart/" > Quickstart< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/1-serialization/" > 1 - Serialization< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/2-requests-and-responses/" > 2 - Requests and responses< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/3-class-based-views/" > 3 - Class based views< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/4-authentication-and-permissions/" > 4 - Authentication and permissions< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/5-relationships-and-hyperlinked-apis/" > 5 - Relationships and hyperlinked APIs< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../tutorial/6-viewsets-and-routers/" > 6 - Viewsets and routers< / a >
2014-11-25 19:04:38 +03:00
< / li >
2016-07-14 15:05:57 +03:00
< li >
< a href = "../../tutorial/7-schemas-and-client-libraries/" > 7 - Schemas and client libraries< / a >
< / li >
2014-11-25 19:04:38 +03:00
< / ul >
< / li >
< li class = "dropdown active" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > API Guide < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../requests/" > Requests< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../responses/" > Responses< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../views/" > Views< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../generic-views/" > Generic views< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../viewsets/" > Viewsets< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../routers/" > Routers< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../parsers/" > Parsers< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../renderers/" > Renderers< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../serializers/" > Serializers< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../fields/" > Serializer fields< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../relations/" > Serializer relations< / a >
2014-11-25 19:04:38 +03:00
< / li >
2014-12-01 15:20:07 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../validators/" > Validators< / a >
2014-12-01 15:20:07 +03:00
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../authentication/" > Authentication< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../permissions/" > Permissions< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../throttling/" > Throttling< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../filtering/" > Filtering< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../pagination/" > Pagination< / a >
2014-11-25 19:04:38 +03:00
< / li >
2015-03-06 15:05:16 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../versioning/" > Versioning< / a >
2015-03-06 15:05:16 +03:00
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../content-negotiation/" > Content negotiation< / a >
2014-11-25 19:04:38 +03:00
< / li >
2014-12-18 18:42:42 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../metadata/" > Metadata< / a >
2014-12-18 18:42:42 +03:00
< / li >
2016-07-07 11:41:32 +03:00
< li >
< a href = "../schemas/" > Schemas< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../format-suffixes/" > Format suffixes< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../reverse/" > Returning URLs< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../exceptions/" > Exceptions< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../status-codes/" > Status codes< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li class = "active" >
2015-06-04 17:37:22 +03:00
< a href = "./" > Testing< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../settings/" > Settings< / a >
2014-11-25 19:04:38 +03:00
< / li >
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Topics < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/documenting-your-api/" > Documenting your API< / a >
2014-11-25 19:04:38 +03:00
< / li >
2016-07-07 11:41:32 +03:00
< li >
< a href = "../../topics/api-clients/" > API Clients< / a >
< / li >
2015-03-06 15:05:16 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/internationalization/" > Internationalization< / a >
2015-03-06 15:05:16 +03:00
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/ajax-csrf-cors/" > AJAX, CSRF & CORS< / a >
2014-11-25 19:04:38 +03:00
< / li >
2015-10-28 14:35:39 +03:00
< li >
< a href = "../../topics/html-and-forms/" > HTML & Forms< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/browser-enhancements/" > Browser Enhancements< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/browsable-api/" > The Browsable API< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/rest-hypermedia-hateoas/" > REST, Hypermedia & HATEOAS< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/third-party-resources/" > Third Party Resources< / a >
2014-11-25 19:04:38 +03:00
< / li >
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/contributing/" > Contributing to REST framework< / a >
2014-11-25 19:04:38 +03:00
< / li >
2014-12-18 16:49:50 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/project-management/" > Project management< / a >
2014-12-18 16:49:50 +03:00
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/3.0-announcement/" > 3.0 Announcement< / a >
2014-11-25 19:04:38 +03:00
< / li >
2014-12-01 15:20:07 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/3.1-announcement/" > 3.1 Announcement< / a >
2014-12-01 15:20:07 +03:00
< / li >
2015-08-06 16:31:52 +03:00
< li >
< a href = "../../topics/3.2-announcement/" > 3.2 Announcement< / a >
< / li >
2015-10-28 14:35:39 +03:00
< li >
< a href = "../../topics/3.3-announcement/" > 3.3 Announcement< / a >
< / li >
2016-07-14 15:05:57 +03:00
< li >
< a href = "../../topics/3.4-announcement/" > 3.4 Announcement< / a >
< / li >
2016-10-20 18:31:37 +03:00
< li >
< a href = "../../topics/3.5-announcement/" > 3.5 Announcement< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/kickstarter-announcement/" > Kickstarter Announcement< / a >
2014-11-25 19:04:38 +03:00
< / li >
2016-05-26 13:48:39 +03:00
< li >
< a href = "../../topics/mozilla-grant/" > Mozilla Grant< / a >
< / li >
< li >
< a href = "../../topics/funding/" > Funding< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li >
2015-06-04 17:37:22 +03:00
< a href = "../../topics/release-notes/" > Release Notes< / a >
2014-11-25 19:04:38 +03:00
< / li >
< / ul >
< / li >
< / ul >
< / div >
<!-- /.nav - collapse -->
< / div >
< / div >
< / div >
< div class = "body-content" >
< div class = "container-fluid" >
<!-- Search Modal -->
2015-06-04 17:37:22 +03:00
< div id = "mkdocs_search_modal" class = "modal hide fade" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true" >
2014-11-25 19:04:38 +03:00
< div class = "modal-header" >
< button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true" > × < / button >
< h3 id = "myModalLabel" > Documentation search< / h3 >
< / div >
< div class = "modal-body" >
2015-08-06 16:31:52 +03:00
< form role = "form" autocomplete = "off" >
2015-06-04 17:37:22 +03:00
< div class = "form-group" >
< input type = "text" name = "q" class = "form-control" placeholder = "Search..." id = "mkdocs-search-query" >
< / div >
< / form >
< div id = "mkdocs-search-results" > < / div >
2014-11-25 19:04:38 +03:00
< / div >
< div class = "modal-footer" >
< button class = "btn" data-dismiss = "modal" aria-hidden = "true" > Close< / button >
< / div >
< / div >
< div class = "row-fluid" >
< div class = "span3" >
< div id = "table-of-contents" >
< ul class = "nav nav-list side-nav well sidebar-nav-fixed" >
< li class = "main" >
< a href = "#testing" > Testing< / a >
< / li >
< li class = "main" >
< a href = "#apirequestfactory" > APIRequestFactory< / a >
< / li >
< li >
< a href = "#creating-test-requests" > Creating test requests< / a >
< / li >
< li >
< a href = "#forcing-authentication" > Forcing authentication< / a >
< / li >
< li >
< a href = "#forcing-csrf-validation" > Forcing CSRF validation< / a >
< / li >
< li class = "main" >
< a href = "#apiclient" > APIClient< / a >
< / li >
< li >
< a href = "#making-requests" > Making requests< / a >
< / li >
< li >
< a href = "#authenticating" > Authenticating< / a >
< / li >
< li >
< a href = "#csrf-validation" > CSRF validation< / a >
< / li >
2016-10-14 16:33:49 +03:00
< li class = "main" >
< a href = "#requestsclient" > RequestsClient< / a >
< / li >
2016-12-09 19:07:34 +03:00
< li >
< a href = "#requestsclient-and-working-with-the-database" > RequestsClient and working with the database< / a >
< / li >
2016-10-14 16:33:49 +03:00
< li >
< a href = "#headers-authentication" > Headers & Authentication< / a >
< / li >
< li >
< a href = "#csrf" > CSRF< / a >
< / li >
< li >
< a href = "#live-tests" > Live tests< / a >
< / li >
< li class = "main" >
< a href = "#coreapiclient" > CoreAPIClient< / a >
< / li >
< li >
< a href = "#headers-authentication_1" > Headers & Authentication< / a >
< / li >
2014-11-25 19:04:38 +03:00
< li class = "main" >
< a href = "#test-cases" > Test cases< / a >
< / li >
< li >
< a href = "#example" > Example< / a >
< / li >
< li class = "main" >
< a href = "#testing-responses" > Testing responses< / a >
< / li >
< li >
< a href = "#checking-the-response-data" > Checking the response data< / a >
< / li >
< li >
< a href = "#rendering-responses" > Rendering responses< / a >
< / li >
< li class = "main" >
< a href = "#configuration" > Configuration< / a >
< / li >
< li >
< a href = "#setting-the-default-format" > Setting the default format< / a >
< / li >
< li >
< a href = "#setting-the-available-formats" > Setting the available formats< / a >
< / li >
2016-05-26 13:48:39 +03:00
< div class = "promo" >
< hr / >
< div id = "sidebarInclude" >
< / div >
2014-11-25 19:04:38 +03:00
< / ul >
< / div >
< / div >
< div id = "main-content" class = "span9" >
2015-06-04 17:37:22 +03:00
< a class = "github" href = "https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/test.py" >
< span class = "label label-info" > test.py< / span >
< / a >
2014-11-25 19:04:38 +03:00
2015-11-04 17:59:23 +03:00
< h1 id = "testing" > < a class = "toclink" href = "#testing" > Testing< / a > < / h1 >
2014-11-25 19:04:38 +03:00
< blockquote >
< p > Code without tests is broken as designed.< / p >
< p > — < a href = "http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper" > Jacob Kaplan-Moss< / a > < / p >
< / blockquote >
< p > REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.< / p >
2015-11-04 17:59:23 +03:00
< h1 id = "apirequestfactory" > < a class = "toclink" href = "#apirequestfactory" > APIRequestFactory< / a > < / h1 >
2016-12-09 19:07:34 +03:00
< p > Extends < a href = "https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory" > Django's existing < code > RequestFactory< / code > class< / a > .< / p >
2015-11-04 17:59:23 +03:00
< h2 id = "creating-test-requests" > < a class = "toclink" href = "#creating-test-requests" > Creating test requests< / a > < / h2 >
2015-03-06 15:05:16 +03:00
< p > The < code > APIRequestFactory< / code > class supports an almost identical API to Django's standard < code > RequestFactory< / code > class. This means that the standard < code > .get()< / code > , < code > .post()< / code > , < code > .put()< / code > , < code > .patch()< / code > , < code > .delete()< / code > , < code > .head()< / code > and < code > .options()< / code > methods are all available.< / p >
2014-11-25 19:04:38 +03:00
< pre > < code > from rest_framework.test import APIRequestFactory
# Using the standard RequestFactory API to create a form POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'})
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h4 id = "using-the-format-argument" > < a class = "toclink" href = "#using-the-format-argument" > Using the < code > format< / code > argument< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > Methods which create a request body, such as < code > post< / code > , < code > put< / code > and < code > patch< / code > , include a < code > format< / code > argument, which make it easy to generate requests using a content type other than multipart form data. For example:< / p >
< pre > < code > # Create a JSON POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
< / code > < / pre >
< p > By default the available formats are < code > 'multipart'< / code > and < code > 'json'< / code > . For compatibility with Django's existing < code > RequestFactory< / code > the default format is < code > 'multipart'< / code > .< / p >
< p > To support a wider set of request formats, or change the default format, < a href = "#configuration" > see the configuration section< / a > .< / p >
2015-11-04 17:59:23 +03:00
< h4 id = "explicitly-encoding-the-request-body" > < a class = "toclink" href = "#explicitly-encoding-the-request-body" > Explicitly encoding the request body< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > If you need to explicitly encode the request body, you can do so by setting the < code > content_type< / code > flag. For example:< / p >
< pre > < code > request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h4 id = "put-and-patch-with-form-data" > < a class = "toclink" href = "#put-and-patch-with-form-data" > PUT and PATCH with form data< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > One difference worth noting between Django's < code > RequestFactory< / code > and REST framework's < code > APIRequestFactory< / code > is that multipart form data will be encoded for methods other than just < code > .post()< / code > .< / p >
< p > For example, using < code > APIRequestFactory< / code > , you can make a form PUT request like so:< / p >
< pre > < code > factory = APIRequestFactory()
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
< / code > < / pre >
< p > Using Django's < code > RequestFactory< / code > , you'd need to explicitly encode the data yourself:< / p >
< pre > < code > from django.test.client import encode_multipart, RequestFactory
factory = RequestFactory()
data = {'title': 'remember to email dave'}
content = encode_multipart('BoUnDaRyStRiNg', data)
content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
request = factory.put('/notes/547/', content, content_type=content_type)
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h2 id = "forcing-authentication" > < a class = "toclink" href = "#forcing-authentication" > Forcing authentication< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.< / p >
< p > To forcibly authenticate a request, use the < code > force_authenticate()< / code > method.< / p >
2015-03-16 15:55:10 +03:00
< pre > < code > from rest_framework.test import force_authenticate
2015-03-06 15:05:16 +03:00
factory = APIRequestFactory()
2014-11-25 19:04:38 +03:00
user = User.objects.get(username='olivia')
view = AccountDetail.as_view()
# Make an authenticated request to the view...
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user)
response = view(request)
< / code > < / pre >
< p > The signature for the method is < code > force_authenticate(request, user=None, token=None)< / code > . When making the call, either or both of the user and token may be set.< / p >
< p > For example, when forcibly authenticating using a token, you might do something like the following:< / p >
< pre > < code > user = User.objects.get(username='olivia')
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.token)
< / code > < / pre >
< hr / >
< p > < strong > Note< / strong > : When using < code > APIRequestFactory< / code > , the object that is returned is Django's standard < code > HttpRequest< / code > , and not REST framework's < code > Request< / code > object, which is only generated once the view is called.< / p >
< p > This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting < code > .token< / code > directly will have no effect, and setting < code > .user< / code > directly will only work if session authentication is being used.< / p >
< pre > < code > # Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
request.user = user
response = view(request)
< / code > < / pre >
< hr / >
2015-11-04 17:59:23 +03:00
< h2 id = "forcing-csrf-validation" > < a class = "toclink" href = "#forcing-csrf-validation" > Forcing CSRF validation< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > By default, requests created with < code > APIRequestFactory< / code > will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the < code > enforce_csrf_checks< / code > flag when instantiating the factory.< / p >
< pre > < code > factory = APIRequestFactory(enforce_csrf_checks=True)
< / code > < / pre >
< hr / >
< p > < strong > Note< / strong > : It's worth noting that Django's standard < code > RequestFactory< / code > doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.< / p >
< hr / >
2015-11-04 17:59:23 +03:00
< h1 id = "apiclient" > < a class = "toclink" href = "#apiclient" > APIClient< / a > < / h1 >
2016-12-09 19:07:34 +03:00
< p > Extends < a href = "https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client" > Django's existing < code > Client< / code > class< / a > .< / p >
2015-11-04 17:59:23 +03:00
< h2 id = "making-requests" > < a class = "toclink" href = "#making-requests" > Making requests< / a > < / h2 >
2015-03-06 15:05:16 +03:00
< p > The < code > APIClient< / code > class supports the same request interface as Django's standard < code > Client< / code > class. This means the that standard < code > .get()< / code > , < code > .post()< / code > , < code > .put()< / code > , < code > .patch()< / code > , < code > .delete()< / code > , < code > .head()< / code > and < code > .options()< / code > methods are all available. For example:< / p >
2014-11-25 19:04:38 +03:00
< pre > < code > from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')
< / code > < / pre >
< p > To support a wider set of request formats, or change the default format, < a href = "#configuration" > see the configuration section< / a > .< / p >
2015-11-04 17:59:23 +03:00
< h2 id = "authenticating" > < a class = "toclink" href = "#authenticating" > Authenticating< / a > < / h2 >
< h4 id = "loginkwargs" > < a class = "toclink" href = "#loginkwargs" > .login(**kwargs)< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > The < code > login< / code > method functions exactly as it does with Django's regular < code > Client< / code > class. This allows you to authenticate requests against any views which include < code > SessionAuthentication< / code > .< / p >
< pre > < code > # Make all requests in the context of a logged in session.
client = APIClient()
client.login(username='lauren', password='secret')
< / code > < / pre >
< p > To logout, call the < code > logout< / code > method as usual.< / p >
< pre > < code > # Log out
client.logout()
< / code > < / pre >
< p > The < code > login< / code > method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.< / p >
2015-11-04 17:59:23 +03:00
< h4 id = "credentialskwargs" > < a class = "toclink" href = "#credentialskwargs" > .credentials(**kwargs)< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > The < code > credentials< / code > method can be used to set headers that will then be included on all subsequent requests by the test client.< / p >
< pre > < code > from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
< / code > < / pre >
< p > Note that calling < code > credentials< / code > a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.< / p >
< pre > < code > # Stop including any credentials
client.credentials()
< / code > < / pre >
< p > The < code > credentials< / code > method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.< / p >
2015-11-04 17:59:23 +03:00
< h4 id = "force_authenticateusernone-tokennone" > < a class = "toclink" href = "#force_authenticateusernone-tokennone" > .force_authenticate(user=None, token=None)< / a > < / h4 >
2014-11-25 19:04:38 +03:00
< p > Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.< / p >
< p > This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.< / p >
< pre > < code > user = User.objects.get(username='lauren')
client = APIClient()
client.force_authenticate(user=user)
< / code > < / pre >
< p > To unauthenticate subsequent requests, call < code > force_authenticate< / code > setting the user and/or token to < code > None< / code > .< / p >
< pre > < code > client.force_authenticate(user=None)
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h2 id = "csrf-validation" > < a class = "toclink" href = "#csrf-validation" > CSRF validation< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > By default CSRF validation is not applied when using < code > APIClient< / code > . If you need to explicitly enable CSRF validation, you can do so by setting the < code > enforce_csrf_checks< / code > flag when instantiating the client.< / p >
< pre > < code > client = APIClient(enforce_csrf_checks=True)
< / code > < / pre >
< p > As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling < code > login()< / code > .< / p >
< hr / >
2016-10-14 16:33:49 +03:00
< h1 id = "requestsclient" > < a class = "toclink" href = "#requestsclient" > RequestsClient< / a > < / h1 >
< p > REST framework also includes a client for interacting with your application
2016-12-09 19:07:34 +03:00
using the popular Python library, < code > requests< / code > . This may be useful if:< / p >
< ul >
< li > You are expecting to interface with the API primarily from another Python service,
and want to test the service at the same level as the client will see.< / li >
< li > You want to write tests in such a way that they can also be run against a staging or
live environment. (See "Live tests" below.)< / li >
< / ul >
2016-10-14 16:33:49 +03:00
< p > This exposes exactly the same interface as if you were using a requests session
directly.< / p >
< pre > < code > client = RequestsClient()
response = client.get('http://testserver/users/')
2016-10-20 18:31:37 +03:00
assert response.status_code == 200
2016-10-14 16:33:49 +03:00
< / code > < / pre >
< p > Note that the requests client requires you to pass fully qualified URLs.< / p >
2016-12-09 19:07:34 +03:00
< h2 id = "requestsclient-and-working-with-the-database" > < a class = "toclink" href = "#requestsclient-and-working-with-the-database" > < code > RequestsClient< / code > and working with the database< / a > < / h2 >
2016-12-12 13:09:46 +03:00
< p > The < code > RequestsClient< / code > class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.< / p >
< p > If you're using < code > RequestsClient< / code > you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that < code > Customer.objects.count() == 3< / code > you would list the customers endpoint, and ensure that it contains three records.< / p >
2016-10-14 16:33:49 +03:00
< h2 id = "headers-authentication" > < a class = "toclink" href = "#headers-authentication" > Headers & Authentication< / a > < / h2 >
< p > Custom headers and authentication credentials can be provided in the same way
as < a href = "http://docs.python-requests.org/en/master/user/advanced/#session-objects" > when using a standard < code > requests.Session< / code > instance< / a > .< / p >
< pre > < code > from requests.auth import HTTPBasicAuth
client.auth = HTTPBasicAuth('user', 'pass')
client.headers.update({'x-test': 'true'})
< / code > < / pre >
< h2 id = "csrf" > < a class = "toclink" href = "#csrf" > CSRF< / a > < / h2 >
< p > If you're using < code > SessionAuthentication< / code > then you'll need to include a CSRF token
for any < code > POST< / code > , < code > PUT< / code > , < code > PATCH< / code > or < code > DELETE< / code > requests.< / p >
< p > You can do so by following the same flow that a JavaScript based client would use.
First make a < code > GET< / code > request in order to obtain a CRSF token, then present that
token in the following request.< / p >
< p > For example...< / p >
< pre > < code > client = RequestsClient()
# Obtain a CSRF token.
response = client.get('/homepage/')
assert response.status_code == 200
csrftoken = response.cookies['csrftoken']
# Interact with the API.
response = client.post('/organisations/', json={
'name': 'MegaCorp',
'status': 'active'
}, headers={'X-CSRFToken': csrftoken})
assert response.status_code == 200
< / code > < / pre >
< h2 id = "live-tests" > < a class = "toclink" href = "#live-tests" > Live tests< / a > < / h2 >
< p > With careful usage both the < code > RequestsClient< / code > and the < code > CoreAPIClient< / code > provide
the ability to write test cases that can run either in development, or be run
directly against your staging server or production environment.< / p >
< p > Using this style to create basic tests of a few core piece of functionality is
a powerful way to validate your live service. Doing so may require some careful
attention to setup and teardown to ensure that the tests run in a way that they
do not directly affect customer data.< / p >
< hr / >
< h1 id = "coreapiclient" > < a class = "toclink" href = "#coreapiclient" > CoreAPIClient< / a > < / h1 >
< p > The CoreAPIClient allows you to interact with your API using the Python
< code > coreapi< / code > client library.< / p >
< pre > < code > # Fetch the API schema
client = CoreAPIClient()
2016-10-20 18:31:37 +03:00
schema = client.get('http://testserver/schema/')
2016-10-14 16:33:49 +03:00
# Create a new organisation
params = {'name': 'MegaCorp', 'status': 'active'}
client.action(schema, ['organisations', 'create'], params)
# Ensure that the organisation exists in the listing
data = client.action(schema, ['organisations', 'list'])
assert(len(data) == 1)
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
< / code > < / pre >
< h2 id = "headers-authentication_1" > < a class = "toclink" href = "#headers-authentication_1" > Headers & Authentication< / a > < / h2 >
< p > Custom headers and authentication may be used with < code > CoreAPIClient< / code > in a
similar way as with < code > RequestsClient< / code > .< / p >
< pre > < code > from requests.auth import HTTPBasicAuth
client = CoreAPIClient()
client.session.auth = HTTPBasicAuth('user', 'pass')
client.session.headers.update({'x-test': 'true'})
< / code > < / pre >
< hr / >
2015-11-04 17:59:23 +03:00
< h1 id = "test-cases" > < a class = "toclink" href = "#test-cases" > Test cases< / a > < / h1 >
2014-11-25 19:04:38 +03:00
< p > REST framework includes the following test case classes, that mirror the existing Django test case classes, but use < code > APIClient< / code > instead of Django's default < code > Client< / code > .< / p >
< ul >
< li > < code > APISimpleTestCase< / code > < / li >
< li > < code > APITransactionTestCase< / code > < / li >
< li > < code > APITestCase< / code > < / li >
< li > < code > APILiveServerTestCase< / code > < / li >
< / ul >
2015-11-04 17:59:23 +03:00
< h2 id = "example" > < a class = "toclink" href = "#example" > Example< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > You can use any of REST framework's test case classes as you would for the regular Django test case classes. The < code > self.client< / code > attribute will be an < code > APIClient< / code > instance.< / p >
2016-10-14 16:33:49 +03:00
< pre > < code > from django.urls import reverse
2014-11-25 19:04:38 +03:00
from rest_framework import status
from rest_framework.test import APITestCase
2015-09-11 15:06:48 +03:00
from myproject.apps.core.models import Account
2014-11-25 19:04:38 +03:00
class AccountTests(APITestCase):
def test_create_account(self):
"""
Ensure we can create a new account object.
"""
url = reverse('account-list')
data = {'name': 'DabApps'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
2015-09-11 15:06:48 +03:00
self.assertEqual(Account.objects.count(), 1)
self.assertEqual(Account.objects.get().name, 'DabApps')
2014-11-25 19:04:38 +03:00
< / code > < / pre >
< hr / >
2015-11-04 17:59:23 +03:00
< h1 id = "testing-responses" > < a class = "toclink" href = "#testing-responses" > Testing responses< / a > < / h1 >
< h2 id = "checking-the-response-data" > < a class = "toclink" href = "#checking-the-response-data" > Checking the response data< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.< / p >
< p > For example, it's easier to inspect < code > response.data< / code > :< / p >
< pre > < code > response = self.client.get('/users/4/')
self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
< / code > < / pre >
< p > Instead of inspecting the result of parsing < code > response.content< / code > :< / p >
< pre > < code > response = self.client.get('/users/4/')
self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h2 id = "rendering-responses" > < a class = "toclink" href = "#rendering-responses" > Rendering responses< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > If you're testing views directly using < code > APIRequestFactory< / code > , the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access < code > response.content< / code > , you'll first need to render the response.< / p >
< pre > < code > view = UserDetail.as_view()
request = factory.get('/users/4')
response = view(request, pk='4')
response.render() # Cannot access `response.content` without this.
self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
< / code > < / pre >
< hr / >
2015-11-04 17:59:23 +03:00
< h1 id = "configuration" > < a class = "toclink" href = "#configuration" > Configuration< / a > < / h1 >
< h2 id = "setting-the-default-format" > < a class = "toclink" href = "#setting-the-default-format" > Setting the default format< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > The default format used to make test requests may be set using the < code > TEST_REQUEST_DEFAULT_FORMAT< / code > setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your < code > settings.py< / code > file:< / p >
< pre > < code > REST_FRAMEWORK = {
...
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}
< / code > < / pre >
2015-11-04 17:59:23 +03:00
< h2 id = "setting-the-available-formats" > < a class = "toclink" href = "#setting-the-available-formats" > Setting the available formats< / a > < / h2 >
2014-11-25 19:04:38 +03:00
< p > If you need to test requests using something other than multipart or json requests, you can do so by setting the < code > TEST_REQUEST_RENDERER_CLASSES< / code > setting.< / p >
2015-03-06 15:05:16 +03:00
< p > For example, to add support for using < code > format='html'< / code > in test requests, you might have something like this in your < code > settings.py< / code > file.< / p >
2014-11-25 19:04:38 +03:00
< pre > < code > REST_FRAMEWORK = {
...
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer',
2015-03-06 15:05:16 +03:00
'rest_framework.renderers.TemplateHTMLRenderer'
2014-11-25 19:04:38 +03:00
)
}
< / code > < / pre >
2015-06-04 17:37:22 +03:00
2015-06-23 14:05:53 +03:00
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
< / div > <!-- /.body content -->
2014-11-25 19:04:38 +03:00
< div id = "push" > < / div >
2015-06-23 14:05:53 +03:00
< / div > <!-- /.wrapper -->
2014-11-25 19:04:38 +03:00
< footer class = "span12" >
2015-10-28 14:35:39 +03:00
< p > Documentation built with < a href = "http://www.mkdocs.org/" > MkDocs< / a > .
2014-11-25 19:04:38 +03:00
< / p >
< / footer >
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
< script src = "../../js/jquery-1.8.1-min.js" > < / script >
< script src = "../../js/prettify-1.0.js" > < / script >
< script src = "../../js/bootstrap-2.1.1-min.js" > < / script >
2016-05-26 13:48:39 +03:00
< script src = "https://fund.django-rest-framework.org/sidebar_include.js" > < / script >
2015-06-04 17:37:22 +03:00
< script > var base _url = '../..' ; < / script >
< script src = "../../mkdocs/js/require.js" > < / script >
2014-12-11 12:55:10 +03:00
< script src = "../../js/theme.js" > < / script >
2014-11-25 19:04:38 +03:00
< script >
var shiftWindow = function() {
scrollBy(0, -50)
};
2015-06-23 14:05:53 +03:00
2014-11-25 19:04:38 +03:00
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
$('.dropdown-menu').on('click touchstart', function(event) {
event.stopPropagation();
});
2015-06-23 14:05:53 +03:00
// Dynamically force sidenav/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
2014-11-25 19:04:38 +03:00
$(function() {
$(window).resize(function() {
2015-06-23 14:05:53 +03:00
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
2014-11-25 19:04:38 +03:00
});
});
< / script >
< / body >
< / html >