mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-15 22:26:57 +03:00
909 lines
42 KiB
HTML
909 lines
42 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
|
<meta charset="utf-8">
|
|
<title>Testing - Django REST framework</title>
|
|
<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>
|
|
#sidebarInclude img {
|
|
margin-bottom: 10px;
|
|
}
|
|
#sidebarInclude a.promo {
|
|
color: black;
|
|
}
|
|
@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/encode/django-rest-framework/tree/master">GitHub</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../settings/">
|
|
Next <i class="icon-arrow-right icon-white"></i>
|
|
</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../status-codes/">
|
|
<i class="icon-arrow-left icon-white"></i> Previous
|
|
</a>
|
|
<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>
|
|
<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">
|
|
|
|
<li >
|
|
<a href="../..">Home</a>
|
|
</li>
|
|
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../../tutorial/quickstart/">Quickstart</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/7-schemas-and-client-libraries/">7 - Schemas and client libraries</a>
|
|
</li>
|
|
|
|
</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 >
|
|
<a href="../requests/">Requests</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../responses/">Responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../views/">Views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../generic-views/">Generic views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../viewsets/">Viewsets</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../routers/">Routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../parsers/">Parsers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../renderers/">Renderers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../serializers/">Serializers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../fields/">Serializer fields</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../relations/">Serializer relations</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../validators/">Validators</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../authentication/">Authentication</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../permissions/">Permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../throttling/">Throttling</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../filtering/">Filtering</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../pagination/">Pagination</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../versioning/">Versioning</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../content-negotiation/">Content negotiation</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../metadata/">Metadata</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../schemas/">Schemas</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../format-suffixes/">Format suffixes</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../reverse/">Returning URLs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../exceptions/">Exceptions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../status-codes/">Status codes</a>
|
|
</li>
|
|
|
|
<li class="active" >
|
|
<a href="./">Testing</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../settings/">Settings</a>
|
|
</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 >
|
|
<a href="../../topics/documenting-your-api/">Documenting your API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/api-clients/">API Clients</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/internationalization/">Internationalization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/html-and-forms/">HTML & Forms</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browsable-api/">The Browsable API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/third-party-packages/">Third Party Packages</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/tutorials-and-resources/">Tutorials and Resources</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/contributing/">Contributing to REST framework</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/project-management/">Project management</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/jobs/">Jobs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.0-announcement/">3.0 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.1-announcement/">3.1 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.2-announcement/">3.2 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.3-announcement/">3.3 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.4-announcement/">3.4 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.5-announcement/">3.5 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.6-announcement/">3.6 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.7-announcement/">3.7 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.8-announcement/">3.8 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/kickstarter-announcement/">Kickstarter Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/mozilla-grant/">Mozilla Grant</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/funding/">Funding</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/release-notes/">Release Notes</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
|
|
</ul>
|
|
|
|
</div>
|
|
<!--/.nav-collapse -->
|
|
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="body-content">
|
|
<div class="container-fluid">
|
|
<!-- Search Modal -->
|
|
<div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
|
<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">
|
|
<form role="form" autocomplete="off">
|
|
<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>
|
|
</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>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#requestsclient">RequestsClient</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#requestsclient-and-working-with-the-database">RequestsClient and working with the database</a>
|
|
</li>
|
|
|
|
<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>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#api-test-cases">API Test cases</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#example">Example</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#urlpatternstestcase">URLPatternsTestCase</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#example_1">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>
|
|
|
|
|
|
|
|
<div class="promo">
|
|
<hr/>
|
|
<div id="sidebarInclude">
|
|
</div>
|
|
</ul>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<div id="main-content" class="span9">
|
|
|
|
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/t">
|
|
<span class="label label-info">t</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/e">
|
|
<span class="label label-info">e</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/s">
|
|
<span class="label label-info">s</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/t">
|
|
<span class="label label-info">t</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/.">
|
|
<span class="label label-info">.</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/p">
|
|
<span class="label label-info">p</span>
|
|
</a>
|
|
|
|
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/y">
|
|
<span class="label label-info">y</span>
|
|
</a>
|
|
|
|
|
|
|
|
<h1 id="testing"><a class="toclink" href="#testing">Testing</a></h1>
|
|
<blockquote>
|
|
<p>Code without tests is broken as designed.</p>
|
|
<p>— <a href="https://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>
|
|
<h1 id="apirequestfactory"><a class="toclink" href="#apirequestfactory">APIRequestFactory</a></h1>
|
|
<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>
|
|
<h2 id="creating-test-requests"><a class="toclink" href="#creating-test-requests">Creating test requests</a></h2>
|
|
<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>
|
|
<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>
|
|
<h4 id="using-the-format-argument"><a class="toclink" href="#using-the-format-argument">Using the <code>format</code> argument</a></h4>
|
|
<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>
|
|
<h4 id="explicitly-encoding-the-request-body"><a class="toclink" href="#explicitly-encoding-the-request-body">Explicitly encoding the request body</a></h4>
|
|
<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>
|
|
<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>
|
|
<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>
|
|
<h2 id="forcing-authentication"><a class="toclink" href="#forcing-authentication">Forcing authentication</a></h2>
|
|
<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>
|
|
<pre><code>from rest_framework.test import force_authenticate
|
|
|
|
factory = APIRequestFactory()
|
|
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.auth_token)
|
|
</code></pre>
|
|
<hr />
|
|
<p><strong>Note</strong>: <code>force_authenticate</code> directly sets <code>request.user</code> to the in-memory <code>user</code> instance. If you are re-using the same <code>user</code> instance across multiple tests that update the saved <code>user</code> state, you may need to call <a href="https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db"><code>refresh_from_db()</code></a> between tests.</p>
|
|
<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 />
|
|
<h2 id="forcing-csrf-validation"><a class="toclink" href="#forcing-csrf-validation">Forcing CSRF validation</a></h2>
|
|
<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 />
|
|
<h1 id="apiclient"><a class="toclink" href="#apiclient">APIClient</a></h1>
|
|
<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>
|
|
<h2 id="making-requests"><a class="toclink" href="#making-requests">Making requests</a></h2>
|
|
<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>
|
|
<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>
|
|
<h2 id="authenticating"><a class="toclink" href="#authenticating">Authenticating</a></h2>
|
|
<h4 id="loginkwargs"><a class="toclink" href="#loginkwargs">.login(**kwargs)</a></h4>
|
|
<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>
|
|
<h4 id="credentialskwargs"><a class="toclink" href="#credentialskwargs">.credentials(**kwargs)</a></h4>
|
|
<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>
|
|
<h4 id="force_authenticateusernone-tokennone"><a class="toclink" href="#force_authenticateusernone-tokennone">.force_authenticate(user=None, token=None)</a></h4>
|
|
<p>Sometimes you may want to bypass authentication entirely and 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>
|
|
<h2 id="csrf-validation"><a class="toclink" href="#csrf-validation">CSRF validation</a></h2>
|
|
<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 />
|
|
<h1 id="requestsclient"><a class="toclink" href="#requestsclient">RequestsClient</a></h1>
|
|
<p>REST framework also includes a client for interacting with your application
|
|
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>
|
|
<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/')
|
|
assert response.status_code == 200
|
|
</code></pre>
|
|
<p>Note that the requests client requires you to pass fully qualified URLs.</p>
|
|
<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>
|
|
<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>
|
|
<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()
|
|
schema = client.get('http://testserver/schema/')
|
|
|
|
# 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 />
|
|
<h1 id="api-test-cases"><a class="toclink" href="#api-test-cases">API Test cases</a></h1>
|
|
<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>
|
|
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
|
|
<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>
|
|
<pre><code>from django.urls import reverse
|
|
from rest_framework import status
|
|
from rest_framework.test import APITestCase
|
|
from myproject.apps.core.models import Account
|
|
|
|
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)
|
|
self.assertEqual(Account.objects.count(), 1)
|
|
self.assertEqual(Account.objects.get().name, 'DabApps')
|
|
</code></pre>
|
|
<hr />
|
|
<h1 id="urlpatternstestcase"><a class="toclink" href="#urlpatternstestcase">URLPatternsTestCase</a></h1>
|
|
<p>REST framework also provides a test case class for isolating <code>urlpatterns</code> on a per-class basis. Note that this inherits from Django's <code>SimpleTestCase</code>, and will most likely need to be mixed with another test case class.</p>
|
|
<h2 id="example_1"><a class="toclink" href="#example_1">Example</a></h2>
|
|
<pre><code>from django.urls import include, path, reverse
|
|
from rest_framework.test import APITestCase, URLPatternsTestCase
|
|
|
|
|
|
class AccountTests(APITestCase, URLPatternsTestCase):
|
|
urlpatterns = [
|
|
path('api/', include('api.urls')),
|
|
]
|
|
|
|
def test_create_account(self):
|
|
"""
|
|
Ensure we can create a new account object.
|
|
"""
|
|
url = reverse('account-list')
|
|
response = self.client.get(url, format='json')
|
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
|
self.assertEqual(len(response.data), 1)
|
|
</code></pre>
|
|
<hr />
|
|
<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>
|
|
<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>
|
|
<h2 id="rendering-responses"><a class="toclink" href="#rendering-responses">Rendering responses</a></h2>
|
|
<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 />
|
|
<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>
|
|
<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>
|
|
<h2 id="setting-the-available-formats"><a class="toclink" href="#setting-the-available-formats">Setting the available formats</a></h2>
|
|
<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>
|
|
<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>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
...
|
|
'TEST_REQUEST_RENDERER_CLASSES': (
|
|
'rest_framework.renderers.MultiPartRenderer',
|
|
'rest_framework.renderers.JSONRenderer',
|
|
'rest_framework.renderers.TemplateHTMLRenderer'
|
|
)
|
|
}
|
|
</code></pre>
|
|
|
|
|
|
</div> <!--/span-->
|
|
</div> <!--/row-->
|
|
</div> <!--/.fluid-container-->
|
|
</div> <!--/.body content-->
|
|
<div id="push"></div>
|
|
</div> <!--/.wrapper -->
|
|
|
|
<footer class="span12">
|
|
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
|
|
</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>
|
|
<script src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
|
|
<script>var base_url = '../..';</script>
|
|
<script src="../../mkdocs/js/require.js"></script>
|
|
<script src="../../js/theme.js"></script>
|
|
|
|
<script>
|
|
var shiftWindow = function() {
|
|
scrollBy(0, -50)
|
|
};
|
|
|
|
if (location.hash) shiftWindow();
|
|
window.addEventListener("hashchange", shiftWindow);
|
|
|
|
$('.dropdown-menu').on('click touchstart', function(event) {
|
|
event.stopPropagation();
|
|
});
|
|
|
|
// Dynamically force sidenav/dropdown to no higher than browser window
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
|
|
$(function() {
|
|
$(window).resize(function() {
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
});
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html> |