{"title":"テストツール","version":"1.10","locale":"ja","docname":"topics/testing/tools","url":"/ja/1.10/topics/testing/tools/","canonical":"https://djangodocs.dev/ja/1.10/topics/testing/tools/","summary":"Django は、テストを書くのに便利なツールをいくつか提供しています。テストクライアントは、ダミーのウェブブラウザとして振る舞う Python のクラスです。","html":"<h1>テストツール<a class=\"heading-anchor\" href=\"#testing-tools\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Django は、テストを書くのに便利なツールをいくつか提供しています。</p>\n<section id=\"the-test-client\">\n<span id=\"test-client\"></span><h2>テストクライアント<a class=\"heading-anchor\" href=\"#the-test-client\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>テストクライアントは、ダミーのウェブブラウザとして振る舞う Python のクラスです。これを使えば、ビューと Django で作ったアプリケーションとの関係をプログラムから自動でテストできるようになります。</p>\n<p>テストクライアントでは、次のようなことができます。</p>\n<ul class=\"simple\">\n<li><p>ある URL に対する GET および POST リクエストのシミュレートと、その結果の観察。低レベルの HTTP (レスポンスのヘッダーやステータスコードなど) から、ページのコンテンツまで、あらゆるレスポンスの内容を調査することができます。</p></li>\n<li><p>一連の (好きな数の) リダイレクトを見て、その各ステップごとに URL とステータスコードをチェックする。</p></li>\n<li><p>指定したリクエストが特定の Django テンプレートによってレンダリングされたとき、テンプレートのコンテキストが正しく特定の値を含んでいるかどうかをテストする。</p></li>\n</ul>\n<p>テストクライアントは <a class=\"reference external\" href=\"http://seleniumhq.org/\">Selenium</a> や他の &quot;ブラウザ内 (in-browser)&quot; フレームワークの代替を目指すものではないことに注意してください。Django のテストクライアントの目的は別の点にあります。つまり、</p>\n<ul class=\"simple\">\n<li><p>Django のテストクライアントは、正しいテンプレートがレンダリングされ、そのテンプレートが正しいコンテキストデータをちゃんと渡しているのかをチェックするために使います。</p></li>\n<li><p><a class=\"reference external\" href=\"http://seleniumhq.org/\">Selenium</a> などのブラウザー内フレームワークは、HTML の <em>レンダリング</em> や、Web ページの <em>振る舞い</em> 、つまり JavaScript の機能性をテストするために使います。また、Django はこれらのフレームワーク向けの特別なサポートも提供しています。この詳細については、<a class=\"reference internal\" href=\"#django.test.LiveServerTestCase\" title=\"django.test.LiveServerTestCase\"><code class=\"xref py py-class docutils literal notranslate\">LiveServerTestCase</code></a> のセクションを読んでください。</p></li>\n</ul>\n<p>包括的なテストスイートを実現するには、これら両タイプのテストを組み合わせて行うべきです。</p>\n<section id=\"overview-and-a-quick-example\">\n<h3>概要と簡単な例<a class=\"heading-anchor\" href=\"#overview-and-a-quick-example\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>テストクライアントを使うには、<code class=\"docutils literal notranslate\">django.test.Client</code> からインスタンスを作り、次のように Web ページを取得します。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> Client\n<span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response <span class=\"o\">=</span> c<span class=\"o\">.</span>post<span class=\"p\">(</span><span class=\"s1\">&#39;/login/&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;username&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;john&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;password&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;smith&#39;</span><span class=\"p\">})</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response<span class=\"o\">.</span>status_code\n<span class=\"go\">200</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response <span class=\"o\">=</span> c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/details/&#39;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response<span class=\"o\">.</span>content\n<span class=\"go\">b&#39;&lt;!DOCTYPE html...&#39;</span>\n</code></pre></div>\n<p>この例が示唆しているように、 <code class=\"docutils literal notranslate\">Client</code> のインスタンスは、Python のインタラクティブなインタプリタ上のセッションからでも作ることができます。</p>\n<p>テストクライアントの動作の仕方に関して、いくつか大切な注意点があります。</p>\n<ul>\n<li><p>テストクライアントが動作するために、Web サーバーが動作している必要は <em>ありません</em> 。実際、Web サーバーを一切起動せずに動作するのです！ HTTP のオーバーヘッドを避けて、Django フレームワークと直接やりとりすることで、これを実現しています。このおかげで、高速なユニットテストが可能になっています。</p></li>\n<li><p>ページの取得時には、ドメイン全体ではなく、URL の <em>path</em> だけを指定することを覚えておいてください。たとえば、次は正しいです。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/login/&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>が、これは間違いです。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;https://www.example.com/login/&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>テストクライアントには、自分の Django プロジェクト以外の Web ページを取得する機能はありません。他の Web ページが必要な場合には、 <a class=\"reference external\" href=\"https://docs.python.org/3/library/urllib.html#module-urllib\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">urllib</code></a> などのPython のスタンダードライブラリモジュールを利用してください。</p>\n</li>\n<li><p>URL を解決するとき、テストクライアントは <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-ROOT_URLCONF\"><code class=\"xref std std-setting docutils literal notranslate\">ROOT_URLCONF</code></a> 設定で指定されたすべての URLconf を使用します。</p></li>\n<li><p>上の例では Python のインタラクティブなインタプリタ上でも動作するはずですが、テストクライアントの一部の機能、特にテンプレート関係の機能は、 <em>テストの実行中</em> にしか使えないことがあります。</p>\n<p>というのも、Django のテストランナーは、与えられたビューによって読み込まれるテンプレートを決定する時に、ちょっとした黒魔術を使っています。この黒魔術 (具体的には Django のテンプレートシステムに対してメモリ上でパッチを当てています) は、テストの実行中にだけ使われるのです。</p>\n</li>\n<li><p>デフォルトでは、テストクライアントはサイト上でのすべての CSRF チェックを無効にしています。</p>\n<p>何らかの理由でテストクライアントに CSRF チェックを実行して <em>ほしい</em> ときには、CSRF チェックの実行を強制するテストクライアントのインスタンスを作ることができます。これには、クライアントを作る時に次のように <code class=\"docutils literal notranslate\">enforce_csrf_checks</code> 引数を渡します。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> Client\n<span class=\"gp\">&gt;&gt;&gt; </span>csrf_client <span class=\"o\">=</span> Client<span class=\"p\">(</span>enforce_csrf_checks<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n</code></pre></div>\n</li>\n</ul>\n</section>\n<section id=\"making-requests\">\n<h3>リクエストの作成<a class=\"heading-anchor\" href=\"#making-requests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>リクエストの作成には、<code class=\"docutils literal notranslate\">django.test.Client</code> クラスを使います。</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">Client</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">enforce_csrf_checks<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>defaults</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>インスタンスの作成には、引数は必要ありません。しかし、キーワード引数を使ってデフォルトヘッダーを指定することもできます。たとえば、リクエストごとに <code class=\"docutils literal notranslate\">User-Agent</code> HTTP ヘッダーを送信するには、次のようにします。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">(</span>HTTP_USER_AGENT<span class=\"o\">=</span><span class=\"s1\">&#39;Mozilla/5.0&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">get()</code></a> や <a class=\"reference internal\" href=\"#django.test.Client.post\" title=\"django.test.Client.post\"><code class=\"xref py py-meth docutils literal notranslate\">post()</code></a> などに <code class=\"docutils literal notranslate\">extra</code> キーワード引数で与えられた値は、クラスコンストラクタに渡されたデフォルト値に優先します。</p>\n<p><code class=\"docutils literal notranslate\">enforce_csrf_checks</code> 引数を使うと、CSRF プロテクションのテストが実行できます (上の説明を参照)。</p>\n<p><code class=\"docutils literal notranslate\">Client</code> インスタンスを一度作れば、以下のメソッドを自由に使うことができます。</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.get\">\n<span class=\"sig-name descname\">get</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.get\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して GET リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。<code class=\"docutils literal notranslate\">Response</code> オブジェクトについては、下のセクションにドキュメントされています。</p>\n<p><code class=\"docutils literal notranslate\">data</code> ディクショナリ内の key-value ペアは、GET の URL のデータ部分を構築するのに使われます。例えば、次の例では、</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customers/details/&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;age&#39;</span><span class=\"p\">:</span> <span class=\"mi\">7</span><span class=\"p\">})</span>\n</code></pre></div>\n<p>引数の評価の結果、次の GET リクエストの実行と等価になります。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>/customers/details/?name=fred&amp;age=7\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">extra</code> キーワード引数の値は、リクエスト時に送信されるヘッダーの指定に使われます。たとえば、次のコード</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customers/details/&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;age&#39;</span><span class=\"p\">:</span> <span class=\"mi\">7</span><span class=\"p\">},</span>\n<span class=\"gp\">... </span>      HTTP_X_REQUESTED_WITH<span class=\"o\">=</span><span class=\"s1\">&#39;XMLHttpRequest&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>は、HTTP ヘッダー <code class=\"docutils literal notranslate\">HTTP_X_REQUESTED_WITH</code> を details ビューに送信します。これは、 <a class=\"reference internal\" href=\"/ja/1.10/ref/request-response/#django.http.HttpRequest.is_ajax\" title=\"django.http.HttpRequest.is_ajax\"><code class=\"xref py py-meth docutils literal notranslate\">django.http.HttpRequest.is_ajax()</code></a> メソッドを使ったコードパースのテストのための良い方法です。</p>\n<aside class=\"admonition-cgi-specification admonition\" role=\"note\">\n<p class=\"admonition-title\">CGI の仕様</p>\n<p><code class=\"docutils literal notranslate\">**extra</code> で送信されるヘッダーは、以下の <a class=\"reference external\" href=\"http://www.w3.org/CGI/\">CGI</a> の仕様に従わなければなりません。たとえば、HTTP リクエストの送信時に、ブラウザから異なる &quot;Host&quot; ヘッダーを送信することをエミュレートするためには、<code class=\"docutils literal notranslate\">HTTP_HOST</code> というヘッダを渡さなければなりません。</p>\n</aside>\n<p>GET の引数がすでに URL エンコードされた形式である場合は、data 引数の代わりにエンコード済みの文字列を使うことができます。たとえば、先ほどの GET リクエストは次のようにも書けます。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customers/details/?name=fred&amp;age=7&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>エンコード済みの GET データと data 引数の両方が与えられた場合には、data 引数の方が優先されます。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> を <code class=\"docutils literal notranslate\">True</code> を与えると、クライアントはすべてのリダイレクトを辿り、途中の URL とステータスコードのタプルが、レスポンスオブジェクトの <code class=\"docutils literal notranslate\">redirect_chain</code> 属性に追加されてゆきます。</p>\n<p>たとえば、URL <code class=\"docutils literal notranslate\">/redirect_me/</code> が <code class=\"docutils literal notranslate\">/next/</code> にリダイレクトし、それがさらに <code class=\"docutils literal notranslate\">/final/</code> にリダイレクトするような場合には、<code class=\"docutils literal notranslate\">redirect_chain</code> は次のような値になります。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>response <span class=\"o\">=</span> c<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/redirect_me/&#39;</span><span class=\"p\">,</span> follow<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response<span class=\"o\">.</span>redirect_chain\n<span class=\"go\">[(&#39;http://testserver/next/&#39;, 302), (&#39;http://testserver/final/&#39;, 302)]</span>\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">secure</code> を <code class=\"docutils literal notranslate\">True</code> に設定すると、クライアントは HTTPS リクエストをエミュレートします。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.post\">\n<span class=\"sig-name descname\">post</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">content_type<span class=\"o\">=</span><span class=\"default_value\">MULTIPART_CONTENT</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.post\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して POST リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。<code class=\"docutils literal notranslate\">Response</code> オブジェクトについては、下のセクションにドキュメントされています。</p>\n<p><code class=\"docutils literal notranslate\">data</code> ディクショナリ内の key-value ペアは、POST データを送信するのに使われます。例えば、次の例では、</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>post<span class=\"p\">(</span><span class=\"s1\">&#39;/login/&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;passwd&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;secret&#39;</span><span class=\"p\">})</span>\n</code></pre></div>\n<p>引数の評価の結果、次の URL へ POST リクエストが行われます。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"o\">/</span>login<span class=\"o\">/</span>\n</code></pre></div>\n<p>リクエストで送られる POST データは次のものになります。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>name<span class=\"o\">=</span>fred<span class=\"o\">&amp;</span>passwd<span class=\"o\">=</span>secret\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">content_type</code> (たとえば、XML データの場合は <em class=\"mimetype\">text/xml</em>) を与えると、 <code class=\"docutils literal notranslate\">data</code> のコンテンツは、HTTP の <code class=\"docutils literal notranslate\">Content-Type</code> ヘッダーの中で <code class=\"docutils literal notranslate\">content_type</code> を使ったものとして、POST リクエストで送られます。</p>\n<p><code class=\"docutils literal notranslate\">content_type</code> に値を渡さなかったときは、<code class=\"docutils literal notranslate\">data</code> 内の値を <em class=\"mimetype\">multipart/form-data</em> のコンテンツタイプとして送信します。この場合は、 <code class=\"docutils literal notranslate\">data</code> 内のkey-value ペアが multipart メッセージにえんこーどされ、POST データを生成するのに使われます。</p>\n<p>たとえば <code class=\"docutils literal notranslate\">&lt;select multiple&gt;</code> の複数の選択を指定する場合のように、特定のキーに対して複数の値を送信したいときは、必要なキーに対する値をリストまたはタプルとして与えます。たとえば、 <code class=\"docutils literal notranslate\">data</code> に次の値を与えれば、3つの選択した値を <code class=\"docutils literal notranslate\">choice</code> という名前のフィールドに対して送信できます。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"p\">{</span><span class=\"s1\">&#39;choices&#39;</span><span class=\"p\">:</span> <span class=\"p\">(</span><span class=\"s1\">&#39;a&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;b&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;d&#39;</span><span class=\"p\">)}</span>\n</code></pre></div>\n<p>ファイルの送信には特別なやり方が必要です。ファイルを POST するには、キーにファイルフィールドの名前を、その値にアップロードしたいファイルのハンドラを渡す必要があります。次のようになります。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"k\">with</span> <span class=\"nb\">open</span><span class=\"p\">(</span><span class=\"s1\">&#39;wishlist.doc&#39;</span><span class=\"p\">)</span> <span class=\"k\">as</span> fp<span class=\"p\">:</span>\n<span class=\"gp\">... </span>    c<span class=\"o\">.</span>post<span class=\"p\">(</span><span class=\"s1\">&#39;/customers/wishes/&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;attachment&#39;</span><span class=\"p\">:</span> fp<span class=\"p\">})</span>\n</code></pre></div>\n<p>(ここで指定している <code class=\"docutils literal notranslate\">attachment</code> という名前は、この名前である必要はありません。自分が書いたファイルを処理するコードに対応する適当な名前を使ってください。)</p>\n<p>ファイルハンドラとしては、任意の file-like オブジェクト (たとえば、 <a class=\"reference external\" href=\"https://docs.python.org/3/library/io.html#io.StringIO\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">StringIO</code></a> or <a class=\"reference external\" href=\"https://docs.python.org/3/library/io.html#io.BytesIO\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">BytesIO</code></a> など) を与えることもできます。</p>\n<p>複数の <code class=\"docutils literal notranslate\">post()</code> の呼び出しに対して同じファイルハンドラを使う時には、post 間でファイルポインタを手動でリセットする必要があります。これを一番簡単に扱う方法は、上に示したように、ファイルが <code class=\"docutils literal notranslate\">post()</code> に与えられた後に手動でファイルを close することです。</p>\n<p>データが読み込めるように、正しい方法でファイルを開くようにする必要があります。これはつまり、画像ファイルなどのバイナリデータが含まれている場合には、<code class=\"docutils literal notranslate\">rb</code> (read binary、バイナリ読み込み) モードで開かなければならないということです。</p>\n<p><code class=\"docutils literal notranslate\">extra</code> 引数は <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同じように振る舞います。</p>\n<p>POST でリクエストした URL にエンコード済みパラメータが含まれている場合には、これらのデータは request.GET データから利用できます。たとえば、次のようなリクエストを行った場合、</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>post<span class=\"p\">(</span><span class=\"s1\">&#39;/login/?visitor=true&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;passwd&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;secret&#39;</span><span class=\"p\">})</span>\n</code></pre></div>\n<p>このリクエストをハンドリングするビューでは、request.POST からはユーザー名とパスワードを取得し、request.GET からはユーザーが visitor であるかどうかを特定することができます。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> を <code class=\"docutils literal notranslate\">True</code> を与えると、クライアントはすべてのリダイレクトを辿り、途中の URL とステータスコードのタプルが、レスポンスオブジェクトの <code class=\"docutils literal notranslate\">redirect_chain</code> 属性に追加されてゆきます。</p>\n<p><code class=\"docutils literal notranslate\">secure</code> を <code class=\"docutils literal notranslate\">True</code> に設定すると、クライアントは HTTPS リクエストをエミュレートします。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.head\">\n<span class=\"sig-name descname\">head</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.head\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して HEAD リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。message body を返さない点を除いて、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同じように動作します。 <code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> の引数の動作も同様です。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.options\">\n<span class=\"sig-name descname\">options</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">content_type<span class=\"o\">=</span><span class=\"default_value\">'application/octet-stream'</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.options\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して OPTION リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。RESTful インターフェイスのテスト時に有用です。</p>\n<p><code class=\"docutils literal notranslate\">data</code> が与えられると、request body として使われます。 <code class=\"docutils literal notranslate\">content_type</code> は <code class=\"docutils literal notranslate\">Content-Type</code> ヘッダーに設定されます。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> 引数は、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同様に動作します。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.put\">\n<span class=\"sig-name descname\">put</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">content_type<span class=\"o\">=</span><span class=\"default_value\">'application/octet-stream'</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.put\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して PUT リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。RESTful インターフェイスのテスト時に有用です。</p>\n<p><code class=\"docutils literal notranslate\">data</code> が与えられると、request body として使われます。 <code class=\"docutils literal notranslate\">content_type</code> は <code class=\"docutils literal notranslate\">Content-Type</code> ヘッダーに設定されます。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> 引数は、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同様に動作します。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.patch\">\n<span class=\"sig-name descname\">patch</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">content_type<span class=\"o\">=</span><span class=\"default_value\">'application/octet-stream'</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.patch\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して PATCH リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。RESTful インターフェイスのテスト時に有用です。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> 引数は、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同様に動作します。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.delete\">\n<span class=\"sig-name descname\">delete</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">data<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">content_type<span class=\"o\">=</span><span class=\"default_value\">'application/octet-stream'</span></em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.delete\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して DELETE リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。RESTful インターフェイスのテスト時に有用です。</p>\n<p><code class=\"docutils literal notranslate\">data</code> が与えられると、request body として使われます。 <code class=\"docutils literal notranslate\">content_type</code> は <code class=\"docutils literal notranslate\">Content-Type</code> ヘッダーに設定されます。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> 引数は、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同様に動作します。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.trace\">\n<span class=\"sig-name descname\">trace</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">path</em>, <em class=\"sig-param\">follow<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">secure<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\"><span class=\"o\">**</span>extra</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.trace\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>与えられた <code class=\"docutils literal notranslate\">path</code> に対して TRACE リクエストを作り、<code class=\"docutils literal notranslate\">Response</code> オブジェクトを返します。診断のための調査をシミュレートするときに役に立ちます。</p>\n<p>他のリクエストメソッドとは違い、 <code class=\"docutils literal notranslate\">data</code> がキーワード引数にありません。 <span class=\"target\" id=\"index-4\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.3.8\"><strong>RFC 7231 Section 4.3.8</strong></a> に従うためです。そのため、TRACE リクエストには body を含むことが禁止されています。</p>\n<p><code class=\"docutils literal notranslate\">follow</code> 、 <code class=\"docutils literal notranslate\">secure</code> 、 <code class=\"docutils literal notranslate\">extra</code> 引数は、 <a class=\"reference internal\" href=\"#django.test.Client.get\" title=\"django.test.Client.get\"><code class=\"xref py py-meth docutils literal notranslate\">Client.get()</code></a> と同様に動作します。</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.login\">\n<span class=\"sig-name descname\">login</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">**</span>credentials</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.login\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>あなたのサイトが Django の <a class=\"reference internal\" href=\"/ja/1.10/topics/auth/\"><span class=\"doc\">認証システム</span></a> を使っていて、ユーザーのログインをテストしたければ、テストクライアントの <code class=\"docutils literal notranslate\">login()</code> メソッドを使うことで、ユーザーがサイトにログインしたときの状況をシミュレートできます。</p>\n<p>After you call this method, the test client will have all the cookies\nand session data required to pass any login-based tests that may form\npart of a view.</p>\n<p>The format of the <code class=\"docutils literal notranslate\">credentials</code> argument depends on which\n<a class=\"reference internal\" href=\"/ja/1.10/topics/auth/customizing/#authentication-backends\"><span class=\"std std-ref\">authentication backend</span></a> you're using\n(which is configured by your <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-AUTHENTICATION_BACKENDS\"><code class=\"xref std std-setting docutils literal notranslate\">AUTHENTICATION_BACKENDS</code></a>\nsetting). If you're using the standard authentication backend provided\nby Django (<code class=\"docutils literal notranslate\">ModelBackend</code>), <code class=\"docutils literal notranslate\">credentials</code> should be the user's\nusername and password, provided as keyword arguments:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>login<span class=\"p\">(</span>username<span class=\"o\">=</span><span class=\"s1\">&#39;fred&#39;</span><span class=\"p\">,</span> password<span class=\"o\">=</span><span class=\"s1\">&#39;secret&#39;</span><span class=\"p\">)</span>\n\n<span class=\"go\"># Now you can access a view that&#39;s only available to logged-in users.</span>\n</code></pre></div>\n<p>If you're using a different authentication backend, this method may\nrequire different credentials. It requires whichever credentials are\nrequired by your backend's <code class=\"docutils literal notranslate\">authenticate()</code> method.</p>\n<p><code class=\"docutils literal notranslate\">login()</code> returns <code class=\"docutils literal notranslate\">True</code> if it the credentials were accepted and\nlogin was successful.</p>\n<p>Finally, you'll need to remember to create user accounts before you can\nuse this method. As we explained above, the test runner is executed\nusing a test database, which contains no users by default. As a result,\nuser accounts that are valid on your production site will not work\nunder test conditions. You'll need to create users as part of the test\nsuite -- either manually (using the Django model API) or with a test\nfixture. Remember that if you want your test user to have a password,\nyou can't set the user's password by setting the password attribute\ndirectly -- you must use the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/auth/#django.contrib.auth.models.User.set_password\" title=\"django.contrib.auth.models.User.set_password\"><code class=\"xref py py-meth docutils literal notranslate\">set_password()</code></a> function to\nstore a correctly hashed password. Alternatively, you can use the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user\" title=\"django.contrib.auth.models.UserManager.create_user\"><code class=\"xref py py-meth docutils literal notranslate\">create_user()</code></a> helper\nmethod to create a new user with a correctly hashed password.</p>\n<aside class=\"version-note version-changed\" data-version=\"1.10\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 1.10</p><p>In previous versions, inactive users (<a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_active\" title=\"django.contrib.auth.models.User.is_active\"><code class=\"xref py py-attr docutils literal notranslate\">is_active=False</code></a>) were not permitted\nto login.</p>\n</aside>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.force_login\">\n<span class=\"sig-name descname\">force_login</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">user</em>, <em class=\"sig-param\">backend<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.force_login\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><aside class=\"version-note version-added\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">New in Django 1.9</p></aside>\n<p>If your site uses Django's <a class=\"reference internal\" href=\"/ja/1.10/topics/auth/\"><span class=\"doc\">authentication\nsystem</span></a>, you can use the <code class=\"docutils literal notranslate\">force_login()</code> method\nto simulate the effect of a user logging into the site. Use this method\ninstead of <a class=\"reference internal\" href=\"#django.test.Client.login\" title=\"django.test.Client.login\"><code class=\"xref py py-meth docutils literal notranslate\">login()</code></a> when a test requires a user be logged in and\nthe details of how a user logged in aren't important.</p>\n<p>Unlike <code class=\"docutils literal notranslate\">login()</code>, this method skips the authentication and\nverification steps: inactive users (<a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_active\" title=\"django.contrib.auth.models.User.is_active\"><code class=\"xref py py-attr docutils literal notranslate\">is_active=False</code></a>) are permitted to login\nand the user's credentials don't need to be provided.</p>\n<p>The user will have its <code class=\"docutils literal notranslate\">backend</code> attribute set to the value of the\n<code class=\"docutils literal notranslate\">backend</code> argument (which should be a dotted Python path string), or\nto <code class=\"docutils literal notranslate\">settings.AUTHENTICATION_BACKENDS[0]</code> if a value isn't provided.\nThe <a class=\"reference internal\" href=\"/ja/1.10/topics/auth/default/#django.contrib.auth.authenticate\" title=\"django.contrib.auth.authenticate\"><code class=\"xref py py-func docutils literal notranslate\">authenticate()</code></a> function called by\n<a class=\"reference internal\" href=\"#django.test.Client.login\" title=\"django.test.Client.login\"><code class=\"xref py py-meth docutils literal notranslate\">login()</code></a> normally annotates the user like this.</p>\n<p>This method is faster than <code class=\"docutils literal notranslate\">login()</code> since the expensive\npassword hashing algorithms are bypassed. Also, you can speed up\n<code class=\"docutils literal notranslate\">login()</code> by <a class=\"reference internal\" href=\"/ja/1.10/topics/testing/overview/#speeding-up-tests-auth-hashers\"><span class=\"std std-ref\">using a weaker hasher while testing</span></a>.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.logout\">\n<span class=\"sig-name descname\">logout</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Client.logout\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>If your site uses Django's <a class=\"reference internal\" href=\"/ja/1.10/topics/auth/\"><span class=\"doc\">authentication system</span></a>,\nthe <code class=\"docutils literal notranslate\">logout()</code> method can be used to simulate the effect of a user\nlogging out of your site.</p>\n<p>After you call this method, the test client will have all the cookies\nand session data cleared to defaults. Subsequent requests will appear\nto come from an <a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser\" title=\"django.contrib.auth.models.AnonymousUser\"><code class=\"xref py py-class docutils literal notranslate\">AnonymousUser</code></a>.</p>\n</dd></dl>\n\n</dd></dl>\n\n</section>\n<section id=\"testing-responses\">\n<h3>Testing responses<a class=\"heading-anchor\" href=\"#testing-responses\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The <code class=\"docutils literal notranslate\">get()</code> and <code class=\"docutils literal notranslate\">post()</code> methods both return a <code class=\"docutils literal notranslate\">Response</code> object. This\n<code class=\"docutils literal notranslate\">Response</code> object is <em>not</em> the same as the <code class=\"docutils literal notranslate\">HttpResponse</code> object returned\nby Django views; the test response object has some additional data useful for\ntest code to verify.</p>\n<p>Specifically, a <code class=\"docutils literal notranslate\">Response</code> object has the following attributes:</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">Response</span><a class=\"heading-anchor\" href=\"#django.test.Response\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.client\">\n<span class=\"sig-name descname\">client</span><a class=\"heading-anchor\" href=\"#django.test.Response.client\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The test client that was used to make the request that resulted in the\nresponse.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.content\">\n<span class=\"sig-name descname\">content</span><a class=\"heading-anchor\" href=\"#django.test.Response.content\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The body of the response, as a bytestring. This is the final page\ncontent as rendered by the view, or any error message.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.context\">\n<span class=\"sig-name descname\">context</span><a class=\"heading-anchor\" href=\"#django.test.Response.context\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The template <code class=\"docutils literal notranslate\">Context</code> instance that was used to render the template that\nproduced the response content.</p>\n<p>If the rendered page used multiple templates, then <code class=\"docutils literal notranslate\">context</code> will be a\nlist of <code class=\"docutils literal notranslate\">Context</code> objects, in the order in which they were rendered.</p>\n<p>Regardless of the number of templates used during rendering, you can\nretrieve context values using the <code class=\"docutils literal notranslate\">[]</code> operator. For example, the\ncontext variable <code class=\"docutils literal notranslate\">name</code> could be retrieved using:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>response <span class=\"o\">=</span> client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/foo/&#39;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response<span class=\"o\">.</span>context<span class=\"p\">[</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">]</span>\n<span class=\"go\">&#39;Arthur&#39;</span>\n</code></pre></div>\n<aside class=\"admonition-not-using-django-templates admonition\" role=\"note\">\n<p class=\"admonition-title\">Not using Django templates?</p>\n<p>This attribute is only populated when using the\n<a class=\"reference internal\" href=\"/ja/1.10/topics/templates/#django.template.backends.django.DjangoTemplates\" title=\"django.template.backends.django.DjangoTemplates\"><code class=\"xref py py-class docutils literal notranslate\">DjangoTemplates</code></a> backend.\nIf you're using another template engine,\n<a class=\"reference internal\" href=\"/ja/1.10/ref/template-response/#django.template.response.SimpleTemplateResponse.context_data\" title=\"django.template.response.SimpleTemplateResponse.context_data\"><code class=\"xref py py-attr docutils literal notranslate\">context_data</code></a>\nmay be a suitable alternative on responses with that attribute.</p>\n</aside>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.json\">\n<span class=\"sig-name descname\">json</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.Response.json\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><aside class=\"version-note version-added\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">New in Django 1.9</p></aside>\n<p>The body of the response, parsed as JSON. Extra keyword arguments are\npassed to <a class=\"reference external\" href=\"https://docs.python.org/3/library/json.html#json.loads\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\">json.loads()</code></a>. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>response <span class=\"o\">=</span> client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/foo/&#39;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>response<span class=\"o\">.</span>json<span class=\"p\">()[</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">]</span>\n<span class=\"go\">&#39;Arthur&#39;</span>\n</code></pre></div>\n<p>If the <code class=\"docutils literal notranslate\">Content-Type</code> header is not <code class=\"docutils literal notranslate\">&quot;application/json&quot;</code>, then a\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/exceptions.html#ValueError\" title=\"(in Python v3.14)\"><code class=\"xref py py-exc docutils literal notranslate\">ValueError</code></a> will be raised when trying to parse the response.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.request\">\n<span class=\"sig-name descname\">request</span><a class=\"heading-anchor\" href=\"#django.test.Response.request\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The request data that stimulated the response.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.wsgi_request\">\n<span class=\"sig-name descname\">wsgi_request</span><a class=\"heading-anchor\" href=\"#django.test.Response.wsgi_request\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The <code class=\"docutils literal notranslate\">WSGIRequest</code> instance generated by the test handler that\ngenerated the response.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.status_code\">\n<span class=\"sig-name descname\">status_code</span><a class=\"heading-anchor\" href=\"#django.test.Response.status_code\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The HTTP status of the response, as an integer. For a full list\nof defined codes, see the <a class=\"reference external\" href=\"https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml\">IANA status code registry</a>.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.templates\">\n<span class=\"sig-name descname\">templates</span><a class=\"heading-anchor\" href=\"#django.test.Response.templates\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>A list of <code class=\"docutils literal notranslate\">Template</code> instances used to render the final content, in\nthe order they were rendered. For each template in the list, use\n<code class=\"docutils literal notranslate\">template.name</code> to get the template's file name, if the template was\nloaded from a file. (The name is a string such as\n<code class=\"docutils literal notranslate\">'admin/index.html'</code>.)</p>\n<aside class=\"admonition-not-using-django-templates admonition\" role=\"note\">\n<p class=\"admonition-title\">Not using Django templates?</p>\n<p>This attribute is only populated when using the\n<a class=\"reference internal\" href=\"/ja/1.10/topics/templates/#django.template.backends.django.DjangoTemplates\" title=\"django.template.backends.django.DjangoTemplates\"><code class=\"xref py py-class docutils literal notranslate\">DjangoTemplates</code></a> backend.\nIf you're using another template engine,\n<a class=\"reference internal\" href=\"/ja/1.10/ref/template-response/#django.template.response.SimpleTemplateResponse.template_name\" title=\"django.template.response.SimpleTemplateResponse.template_name\"><code class=\"xref py py-attr docutils literal notranslate\">template_name</code></a>\nmay be a suitable alternative if you only need the name of the\ntemplate used for rendering.</p>\n</aside>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Response.resolver_match\">\n<span class=\"sig-name descname\">resolver_match</span><a class=\"heading-anchor\" href=\"#django.test.Response.resolver_match\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>An instance of <a class=\"reference internal\" href=\"/ja/1.10/ref/urlresolvers/#django.urls.ResolverMatch\" title=\"django.urls.ResolverMatch\"><code class=\"xref py py-class docutils literal notranslate\">ResolverMatch</code></a> for the response.\nYou can use the <a class=\"reference internal\" href=\"/ja/1.10/ref/urlresolvers/#django.urls.ResolverMatch.func\" title=\"django.urls.ResolverMatch.func\"><code class=\"xref py py-attr docutils literal notranslate\">func</code></a> attribute, for\nexample, to verify the view that served the response:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># my_view here is a function based view</span>\n<span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>resolver_match<span class=\"o\">.</span>func<span class=\"p\">,</span> my_view<span class=\"p\">)</span>\n\n<span class=\"c1\"># class-based views need to be compared by name, as the functions</span>\n<span class=\"c1\"># generated by as_view() won&#39;t be equal</span>\n<span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>resolver_match<span class=\"o\">.</span>func<span class=\"o\">.</span><span class=\"vm\">__name__</span><span class=\"p\">,</span> MyView<span class=\"o\">.</span>as_view<span class=\"p\">()</span><span class=\"o\">.</span><span class=\"vm\">__name__</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>If the given URL is not found, accessing this attribute will raise a\n<a class=\"reference internal\" href=\"/ja/1.10/ref/exceptions/#django.urls.Resolver404\" title=\"django.urls.Resolver404\"><code class=\"xref py py-exc docutils literal notranslate\">Resolver404</code></a> exception.</p>\n</dd></dl>\n\n</dd></dl>\n\n<p>You can also use dictionary syntax on the response object to query the value\nof any settings in the HTTP headers. For example, you could determine the\ncontent type of a response using <code class=\"docutils literal notranslate\">response['Content-Type']</code>.</p>\n</section>\n<section id=\"exceptions\">\n<h3>例外<a class=\"heading-anchor\" href=\"#exceptions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you point the test client at a view that raises an exception, that exception\nwill be visible in the test case. You can then use a standard <code class=\"docutils literal notranslate\">try ... except</code>\nblock or <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises\" title=\"(in Python v3.14)\"><code class=\"xref py py-meth docutils literal notranslate\">assertRaises()</code></a> to test for exceptions.</p>\n<p>The only exceptions that are not visible to the test client are\n<a class=\"reference internal\" href=\"/ja/1.10/topics/http/views/#django.http.Http404\" title=\"django.http.Http404\"><code class=\"xref py py-class docutils literal notranslate\">Http404</code></a>,\n<a class=\"reference internal\" href=\"/ja/1.10/ref/exceptions/#django.core.exceptions.PermissionDenied\" title=\"django.core.exceptions.PermissionDenied\"><code class=\"xref py py-class docutils literal notranslate\">PermissionDenied</code></a>, <a class=\"reference external\" href=\"https://docs.python.org/3/library/exceptions.html#SystemExit\" title=\"(in Python v3.14)\"><code class=\"xref py py-exc docutils literal notranslate\">SystemExit</code></a>, and\n<a class=\"reference internal\" href=\"/ja/1.10/ref/exceptions/#django.core.exceptions.SuspiciousOperation\" title=\"django.core.exceptions.SuspiciousOperation\"><code class=\"xref py py-class docutils literal notranslate\">SuspiciousOperation</code></a>. Django catches these\nexceptions internally and converts them into the appropriate HTTP response\ncodes. In these cases, you can check <code class=\"docutils literal notranslate\">response.status_code</code> in your test.</p>\n</section>\n<section id=\"persistent-state\">\n<h3>Persistent state<a class=\"heading-anchor\" href=\"#persistent-state\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The test client is stateful. If a response returns a cookie, then that cookie\nwill be stored in the test client and sent with all subsequent <code class=\"docutils literal notranslate\">get()</code> and\n<code class=\"docutils literal notranslate\">post()</code> requests.</p>\n<p>Expiration policies for these cookies are not followed. If you want a cookie\nto expire, either delete it manually or create a new <code class=\"docutils literal notranslate\">Client</code> instance (which\nwill effectively delete all cookies).</p>\n<p>A test client has two attributes that store persistent state information. You\ncan access these properties as part of a test condition.</p>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.cookies\">\n<span class=\"sig-prename descclassname\">Client.</span><span class=\"sig-name descname\">cookies</span><a class=\"heading-anchor\" href=\"#django.test.Client.cookies\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>A Python <a class=\"reference external\" href=\"https://docs.python.org/3/library/http.cookies.html#http.cookies.SimpleCookie\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">SimpleCookie</code></a> object, containing the current\nvalues of all the client cookies. See the documentation of the\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/http.cookies.html#module-http.cookies\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">http.cookies</code></a> module for more.</p>\n</dd></dl>\n\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.Client.session\">\n<span class=\"sig-prename descclassname\">Client.</span><span class=\"sig-name descname\">session</span><a class=\"heading-anchor\" href=\"#django.test.Client.session\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>A dictionary-like object containing session information. See the\n<a class=\"reference internal\" href=\"/ja/1.10/topics/http/sessions/\"><span class=\"doc\">session documentation</span></a> for full details.</p>\n<p>To modify the session and then save it, it must be stored in a variable\nfirst (because a new <code class=\"docutils literal notranslate\">SessionStore</code> is created every time this property\nis accessed):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">test_something</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    session <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>session\n    session<span class=\"p\">[</span><span class=\"s1\">&#39;somekey&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"s1\">&#39;test&#39;</span>\n    session<span class=\"o\">.</span>save<span class=\"p\">()</span>\n</code></pre></div>\n</dd></dl>\n\n</section>\n<section id=\"setting-the-language\">\n<h3>Setting the language<a class=\"heading-anchor\" href=\"#setting-the-language\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When testing applications that support internationalization and localization,\nyou might want to set the language for a test client request. The method for\ndoing so depends on whether or not the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/middleware/#django.middleware.locale.LocaleMiddleware\" title=\"django.middleware.locale.LocaleMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">LocaleMiddleware</code></a> is enabled.</p>\n<p>If the middleware is enabled, the language can be set by creating a cookie with\na name of <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-LANGUAGE_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\">LANGUAGE_COOKIE_NAME</code></a> and a value of the language code:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.conf</span> <span class=\"kn\">import</span> settings\n\n<span class=\"k\">def</span> <span class=\"nf\">test_language_using_cookie</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>cookies<span class=\"o\">.</span>load<span class=\"p\">({</span>settings<span class=\"o\">.</span>LANGUAGE_COOKIE_NAME<span class=\"p\">:</span> <span class=\"s1\">&#39;fr&#39;</span><span class=\"p\">})</span>\n    response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">)</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>content<span class=\"p\">,</span> <span class=\"sa\">b</span><span class=\"s2\">&quot;Bienvenue sur mon site.&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>or by including the <code class=\"docutils literal notranslate\">Accept-Language</code> HTTP header in the request:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">test_language_using_header</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">,</span> HTTP_ACCEPT_LANGUAGE<span class=\"o\">=</span><span class=\"s1\">&#39;fr&#39;</span><span class=\"p\">)</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>content<span class=\"p\">,</span> <span class=\"sa\">b</span><span class=\"s2\">&quot;Bienvenue sur mon site.&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>More details are in <a class=\"reference internal\" href=\"/ja/1.10/topics/i18n/translation/#how-django-discovers-language-preference\"><span class=\"std std-ref\">How Django discovers language preference</span></a>.</p>\n<p>If the middleware isn't enabled, the active language may be set using\n<a class=\"reference internal\" href=\"/ja/1.10/ref/utils/#django.utils.translation.override\" title=\"django.utils.translation.override\"><code class=\"xref py py-func docutils literal notranslate\">translation.override()</code></a>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.utils</span> <span class=\"kn\">import</span> translation\n\n<span class=\"k\">def</span> <span class=\"nf\">test_language_using_override</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"k\">with</span> translation<span class=\"o\">.</span>override<span class=\"p\">(</span><span class=\"s1\">&#39;fr&#39;</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">)</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>content<span class=\"p\">,</span> <span class=\"sa\">b</span><span class=\"s2\">&quot;Bienvenue sur mon site.&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>More details are in <a class=\"reference internal\" href=\"/ja/1.10/topics/i18n/translation/#explicitly-setting-the-active-language\"><span class=\"std std-ref\">明示的にアクティブな言語をセットする</span></a>.</p>\n</section>\n<section id=\"example\">\n<h3>カスタマイズ例<a class=\"heading-anchor\" href=\"#example\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The following is a simple unit test using the test client:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">import</span> <span class=\"nn\">unittest</span>\n<span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> Client\n\n<span class=\"k\">class</span> <span class=\"nc\">SimpleTest</span><span class=\"p\">(</span>unittest<span class=\"o\">.</span>TestCase<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">setUp</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Every test needs a client.</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>client <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_details</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Issue a GET request.</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/details/&#39;</span><span class=\"p\">)</span>\n\n        <span class=\"c1\"># Check that the response is 200 OK.</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>status_code<span class=\"p\">,</span> <span class=\"mi\">200</span><span class=\"p\">)</span>\n\n        <span class=\"c1\"># Check that the rendered context contains 5 customers.</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span><span class=\"nb\">len</span><span class=\"p\">(</span>response<span class=\"o\">.</span>context<span class=\"p\">[</span><span class=\"s1\">&#39;customers&#39;</span><span class=\"p\">]),</span> <span class=\"mi\">5</span><span class=\"p\">)</span>\n</code></pre></div>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">参考</p>\n<p><a class=\"reference internal\" href=\"/ja/1.10/topics/testing/advanced/#django.test.RequestFactory\" title=\"django.test.RequestFactory\"><code class=\"xref py py-class docutils literal notranslate\">django.test.RequestFactory</code></a></p>\n</aside>\n</section>\n</section>\n<section id=\"provided-test-case-classes\">\n<span id=\"django-testcase-subclasses\"></span><h2>Provided test case classes<a class=\"heading-anchor\" href=\"#provided-test-case-classes\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Normal Python unit test classes extend a base class of\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">unittest.TestCase</code></a>. Django provides a few extensions of this base class:</p>\n<figure class=\"align-default\" id=\"id4\">\n<span id=\"testcase-hierarchy-diagram\"></span><a class=\"reference internal image-reference\" href=\"../../../../../../_images/django_unittest_classes_hierarchy.svg\"><img alt=\"Hierarchy of Django unit testing classes (TestCase subclasses)\" src=\"/ja/1.10/_images/django_unittest_classes_hierarchy.svg\" style=\"width: 508px; height: 328px;\" />\n</a>\n<figcaption>\n<p><span class=\"caption-text\">Hierarchy of Django unit testing classes</span><a class=\"heading-anchor\" href=\"#id4\"><span class=\"visually-hidden\">Link to this image</span><span aria-hidden=\"true\">#</span></a></p>\n</figcaption>\n</figure>\n<p>Converting a normal <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">unittest.TestCase</code></a> to any of the subclasses is\neasy: change the base class of your test from <code class=\"docutils literal notranslate\">unittest.TestCase</code> to the\nsubclass. All of the standard Python unit test functionality will be available,\nand it will be augmented with some useful additions as described in each\nsection below.</p>\n<section id=\"simpletestcase\">\n<h3><code class=\"docutils literal notranslate\">SimpleTestCase</code><a class=\"heading-anchor\" href=\"#simpletestcase\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">SimpleTestCase</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>A subclass of <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">unittest.TestCase</code></a> that adds this functionality:</p>\n<ul class=\"simple\">\n<li><p>Some useful assertions like:</p>\n<ul>\n<li><p>Checking that a callable <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertRaisesMessage\" title=\"django.test.SimpleTestCase.assertRaisesMessage\"><code class=\"xref py py-meth docutils literal notranslate\">raises a certain exception</code></a>.</p></li>\n<li><p>Testing form field <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertFieldOutput\" title=\"django.test.SimpleTestCase.assertFieldOutput\"><code class=\"xref py py-meth docutils literal notranslate\">rendering and error treatment</code></a>.</p></li>\n<li><p>Testing <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertContains\" title=\"django.test.SimpleTestCase.assertContains\"><code class=\"xref py py-meth docutils literal notranslate\">HTML responses for the presence/lack of a given fragment</code></a>.</p></li>\n<li><p>Verifying that a template <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertTemplateUsed\" title=\"django.test.SimpleTestCase.assertTemplateUsed\"><code class=\"xref py py-meth docutils literal notranslate\">has/hasn't been used to generate a given\nresponse content</code></a>.</p></li>\n<li><p>Verifying a HTTP <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertRedirects\" title=\"django.test.SimpleTestCase.assertRedirects\"><code class=\"xref py py-meth docutils literal notranslate\">redirect</code></a> is\nperformed by the app.</p></li>\n<li><p>Robustly testing two <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\" title=\"django.test.SimpleTestCase.assertHTMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">HTML fragments</code></a>\nfor equality/inequality or <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertInHTML\" title=\"django.test.SimpleTestCase.assertInHTML\"><code class=\"xref py py-meth docutils literal notranslate\">containment</code></a>.</p></li>\n<li><p>Robustly testing two <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertXMLEqual\" title=\"django.test.SimpleTestCase.assertXMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">XML fragments</code></a>\nfor equality/inequality.</p></li>\n<li><p>Robustly testing two <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertJSONEqual\" title=\"django.test.SimpleTestCase.assertJSONEqual\"><code class=\"xref py py-meth docutils literal notranslate\">JSON fragments</code></a>\nfor equality.</p></li>\n</ul>\n</li>\n<li><p>The ability to run tests with <a class=\"reference internal\" href=\"#overriding-settings\"><span class=\"std std-ref\">modified settings</span></a>.</p></li>\n<li><p>Using the <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.client\" title=\"django.test.SimpleTestCase.client\"><code class=\"xref py py-attr docutils literal notranslate\">client</code></a> <a class=\"reference internal\" href=\"#django.test.Client\" title=\"django.test.Client\"><code class=\"xref py py-class docutils literal notranslate\">Client</code></a>.</p></li>\n</ul>\n<p>If your tests make any database queries, use subclasses\n<a class=\"reference internal\" href=\"#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a> or <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a>.</p>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.allow_database_queries\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">allow_database_queries</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.allow_database_queries\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><aside class=\"version-note version-added\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">New in Django 1.9</p></aside>\n<p><a class=\"reference internal\" href=\"#django.test.SimpleTestCase\" title=\"django.test.SimpleTestCase\"><code class=\"xref py py-class docutils literal notranslate\">SimpleTestCase</code></a> disallows database queries by default. This\nhelps to avoid executing write queries which will affect other tests\nsince each <code class=\"docutils literal notranslate\">SimpleTestCase</code> test isn't run in a transaction. If you\naren't concerned about this problem, you can disable this behavior by\nsetting the <code class=\"docutils literal notranslate\">allow_database_queries</code> class attribute to <code class=\"docutils literal notranslate\">True</code> on\nyour test class.</p>\n</dd></dl>\n\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p><code class=\"docutils literal notranslate\">SimpleTestCase</code> and its subclasses (e.g. <code class=\"docutils literal notranslate\">TestCase</code>, ...) rely on\n<code class=\"docutils literal notranslate\">setUpClass()</code> and <code class=\"docutils literal notranslate\">tearDownClass()</code> to perform some class-wide\ninitialization (e.g. overriding settings). If you need to override those\nmethods, don't forget to call the <code class=\"docutils literal notranslate\">super</code> implementation:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">MyTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">setUpClass</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">):</span>\n        <span class=\"nb\">super</span><span class=\"p\">(</span>MyTestCase<span class=\"p\">,</span> <span class=\"bp\">cls</span><span class=\"p\">)</span><span class=\"o\">.</span>setUpClass<span class=\"p\">()</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">tearDownClass</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">):</span>\n        <span class=\"o\">...</span>\n        <span class=\"nb\">super</span><span class=\"p\">(</span>MyTestCase<span class=\"p\">,</span> <span class=\"bp\">cls</span><span class=\"p\">)</span><span class=\"o\">.</span>tearDownClass<span class=\"p\">()</span>\n</code></pre></div>\n<p>Be sure to account for Python's behavior if an exception is raised during\n<code class=\"docutils literal notranslate\">setUpClass()</code>. If that happens, neither the tests in the class nor\n<code class=\"docutils literal notranslate\">tearDownClass()</code> are run. In the case of <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">django.test.TestCase</code></a>,\nthis will leak the transaction created in <code class=\"docutils literal notranslate\">super()</code>  which results in\nvarious symptoms including a segmentation fault on some platforms (reported\non OS X). If you want to intentionally raise an exception such as\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.SkipTest\" title=\"(in Python v3.14)\"><code class=\"xref py py-exc docutils literal notranslate\">unittest.SkipTest</code></a> in <code class=\"docutils literal notranslate\">setUpClass()</code>, be sure to do it before\ncalling <code class=\"docutils literal notranslate\">super()</code> to avoid this.</p>\n</aside>\n</section>\n<section id=\"transactiontestcase\">\n<h3><code class=\"docutils literal notranslate\">TransactionTestCase</code><a class=\"heading-anchor\" href=\"#transactiontestcase\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.TransactionTestCase\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">TransactionTestCase</span><a class=\"heading-anchor\" href=\"#django.test.TransactionTestCase\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">TransactionTestCase</code> inherits from <a class=\"reference internal\" href=\"#django.test.SimpleTestCase\" title=\"django.test.SimpleTestCase\"><code class=\"xref py py-class docutils literal notranslate\">SimpleTestCase</code></a> to\nadd some database-specific features:</p>\n<ul class=\"simple\">\n<li><p>Resetting the database to a known state at the beginning of each test to\nease testing and using the ORM.</p></li>\n<li><p>Database <a class=\"reference internal\" href=\"#django.test.TransactionTestCase.fixtures\" title=\"django.test.TransactionTestCase.fixtures\"><code class=\"xref py py-attr docutils literal notranslate\">fixtures</code></a>.</p></li>\n<li><p>Test <a class=\"reference internal\" href=\"#skipping-tests\"><span class=\"std std-ref\">skipping based on database backend features</span></a>.</p></li>\n<li><p>The remaining specialized <a class=\"reference internal\" href=\"#django.test.TransactionTestCase.assertQuerysetEqual\" title=\"django.test.TransactionTestCase.assertQuerysetEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assert*</code></a> methods.</p></li>\n</ul>\n<p>Django's <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a> class is a more commonly used subclass of\n<code class=\"docutils literal notranslate\">TransactionTestCase</code> that makes use of database transaction facilities\nto speed up the process of resetting the database to a known state at the\nbeginning of each test. A consequence of this, however, is that some database\nbehaviors cannot be tested within a Django <code class=\"docutils literal notranslate\">TestCase</code> class. For instance,\nyou cannot test that a block of code is executing within a transaction, as is\nrequired when using\n<a class=\"reference internal\" href=\"/ja/1.10/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update\" title=\"django.db.models.query.QuerySet.select_for_update\"><code class=\"xref py py-meth docutils literal notranslate\">select_for_update()</code></a>. In those cases,\nyou should use <code class=\"docutils literal notranslate\">TransactionTestCase</code>.</p>\n<p><code class=\"docutils literal notranslate\">TransactionTestCase</code> and <code class=\"docutils literal notranslate\">TestCase</code> are identical except for the manner\nin which the database is reset to a known state and the ability for test code\nto test the effects of commit and rollback:</p>\n<ul class=\"simple\">\n<li><p>A <code class=\"docutils literal notranslate\">TransactionTestCase</code> resets the database after the test runs by\ntruncating all tables. A <code class=\"docutils literal notranslate\">TransactionTestCase</code> may call commit and rollback\nand observe the effects of these calls on the database.</p></li>\n<li><p>A <code class=\"docutils literal notranslate\">TestCase</code>, on the other hand, does not truncate tables after a test.\nInstead, it encloses the test code in a database transaction that is rolled\nback at the end of the test. This guarantees that the rollback at the end of\nthe test restores the database to its initial state.</p></li>\n</ul>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p><code class=\"docutils literal notranslate\">TestCase</code> running on a database that does not support rollback (e.g. MySQL\nwith the MyISAM storage engine), and all instances of <code class=\"docutils literal notranslate\">TransactionTestCase</code>,\nwill roll back at the end of the test by deleting all data from the test\ndatabase.</p>\n<p>Apps <a class=\"reference internal\" href=\"/ja/1.10/topics/testing/overview/#test-case-serialized-rollback\"><span class=\"std std-ref\">will not see their data reloaded</span></a>;\nif you need this functionality (for example, third-party apps should enable\nthis) you can set <code class=\"docutils literal notranslate\">serialized_rollback = True</code> inside the\n<code class=\"docutils literal notranslate\">TestCase</code> body.</p>\n</aside>\n</section>\n<section id=\"testcase\">\n<h3><code class=\"docutils literal notranslate\">TestCase</code><a class=\"heading-anchor\" href=\"#testcase\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.TestCase\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">TestCase</span><a class=\"heading-anchor\" href=\"#django.test.TestCase\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This is the most common class to use for writing tests in Django. It inherits\nfrom <a class=\"reference internal\" href=\"#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a> (and by extension <a class=\"reference internal\" href=\"#django.test.SimpleTestCase\" title=\"django.test.SimpleTestCase\"><code class=\"xref py py-class docutils literal notranslate\">SimpleTestCase</code></a>).\nIf your Django application doesn't use a database, use <a class=\"reference internal\" href=\"#django.test.SimpleTestCase\" title=\"django.test.SimpleTestCase\"><code class=\"xref py py-class docutils literal notranslate\">SimpleTestCase</code></a>.</p>\n<p>The class:</p>\n<ul class=\"simple\">\n<li><p>Wraps the tests within two nested <a class=\"reference internal\" href=\"/ja/1.10/topics/db/transactions/#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\">atomic()</code></a>\nblocks: one for the whole class and one for each test. Therefore, if you want\nto test some specific database transaction behavior, use\n<a class=\"reference internal\" href=\"#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a>.</p></li>\n<li><p>Checks deferrable database constraints at the end of each test.</p></li>\n</ul>\n<aside class=\"version-note version-changed\" data-version=\"1.10\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 1.10</p><p>The check for deferrable database constraints at the end of each test was\nadded.</p>\n</aside>\n<p>It also provides an additional method:</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.TestCase.setUpTestData\">\n<em class=\"property\"><span class=\"k\">classmethod</span> </em><span class=\"sig-prename descclassname\">TestCase.</span><span class=\"sig-name descname\">setUpTestData</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.TestCase.setUpTestData\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The class-level <code class=\"docutils literal notranslate\">atomic</code> block described above allows the creation of\ninitial data at the class level, once for the whole <code class=\"docutils literal notranslate\">TestCase</code>. This\ntechnique allows for faster tests as compared to using <code class=\"docutils literal notranslate\">setUp()</code>.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n\n<span class=\"k\">class</span> <span class=\"nc\">MyTests</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">setUpTestData</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Set up data for the whole TestCase</span>\n        <span class=\"bp\">cls</span><span class=\"o\">.</span>foo <span class=\"o\">=</span> Foo<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>bar<span class=\"o\">=</span><span class=\"s2\">&quot;Test&quot;</span><span class=\"p\">)</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test1</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Some test using self.foo</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test2</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Some other test using self.foo</span>\n        <span class=\"o\">...</span>\n</code></pre></div>\n<p>Note that if the tests are run on a database with no transaction support\n(for instance, MySQL with the MyISAM engine), <code class=\"docutils literal notranslate\">setUpTestData()</code> will be\ncalled before each test, negating the speed benefits.</p>\n<p>Be careful not to modify any objects created in <code class=\"docutils literal notranslate\">setUpTestData()</code> in\nyour test methods. Modifications to in-memory objects from setup work done\nat the class level will persist between test methods. If you do need to\nmodify them, you could reload them in the <code class=\"docutils literal notranslate\">setUp()</code> method with\n<a class=\"reference internal\" href=\"/ja/1.10/ref/models/instances/#django.db.models.Model.refresh_from_db\" title=\"django.db.models.Model.refresh_from_db\"><code class=\"xref py py-meth docutils literal notranslate\">refresh_from_db()</code></a>, for example.</p>\n</dd></dl>\n\n</section>\n<section id=\"liveservertestcase\">\n<span id=\"live-test-server\"></span><h3><code class=\"docutils literal notranslate\">LiveServerTestCase</code><a class=\"heading-anchor\" href=\"#liveservertestcase\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.test.LiveServerTestCase\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">LiveServerTestCase</span><a class=\"heading-anchor\" href=\"#django.test.LiveServerTestCase\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">LiveServerTestCase</code> does basically the same as\n<a class=\"reference internal\" href=\"#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a> with one extra feature: it launches a\nlive Django server in the background on setup, and shuts it down on teardown.\nThis allows the use of automated test clients other than the\n<a class=\"reference internal\" href=\"#test-client\"><span class=\"std std-ref\">Django dummy client</span></a> such as, for example, the <a class=\"reference external\" href=\"http://seleniumhq.org/\">Selenium</a>\nclient, to execute a series of functional tests inside a browser and simulate a\nreal user's actions.</p>\n<p>By default the live server listens on <code class=\"docutils literal notranslate\">localhost</code> and picks the first\navailable port in the <code class=\"docutils literal notranslate\">8081-8179</code> range. Its full URL can be accessed with\n<code class=\"docutils literal notranslate\">self.live_server_url</code> during the tests.</p>\n<aside class=\"version-note version-changed\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 1.9</p><p>In earlier versions, the live server's default address was always\n<code class=\"docutils literal notranslate\">'localhost:8081'</code>.</p>\n</aside>\n<p>If you'd like to select another address, you may pass a different one using the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#cmdoption-test-liveserver\"><code class=\"xref std std-option docutils literal notranslate\">test --liveserver</code></a> option, for example:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> --liveserver<span class=\"o\">=</span>localhost:8082\n</code></pre></div>\n<aside class=\"version-note version-changed\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 1.9</p><p>In older versions <code class=\"docutils literal notranslate\">live_server_url</code> could only be accessed from an\ninstance. It now is a class property and can be accessed from class methods\nlike <code class=\"docutils literal notranslate\">setUpClass()</code>.</p>\n</aside>\n<p>Another way of changing the default server address is by setting the\nDJANGO_LIVE_TEST_SERVER_ADDRESS environment variable somewhere in your\ncode (for example, in a <a class=\"reference internal\" href=\"/ja/1.10/topics/testing/advanced/#topics-testing-test-runner\"><span class=\"std std-ref\">custom test runner</span></a>):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">import</span> <span class=\"nn\">os</span>\nos<span class=\"o\">.</span>environ<span class=\"p\">[</span><span class=\"s1\">&#39;DJANGO_LIVE_TEST_SERVER_ADDRESS&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"s1\">&#39;localhost:8082&#39;</span>\n</code></pre></div>\n<p>In the case where the tests are run by multiple processes in parallel (for\nexample, in the context of several simultaneous <a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Continuous_integration\">continuous integration</a>\nbuilds), the processes will compete for the same address, and therefore your\ntests might randomly fail with an &quot;Address already in use&quot; error. To avoid this\nproblem, you can pass a comma-separated list of ports or ranges of ports (at\nleast as many as the number of potential parallel processes). For example:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> --liveserver<span class=\"o\">=</span>localhost:8082,8090-8100,9000-9200,7041\n</code></pre></div>\n<p>Then, during test execution, each new live test server will try every specified\nport until it finds one that is free and takes it.</p>\n<p>To demonstrate how to use <code class=\"docutils literal notranslate\">LiveServerTestCase</code>, let's write a simple Selenium\ntest. First of all, you need to install the <a class=\"reference external\" href=\"https://pypi.python.org/pypi/selenium\">selenium package</a> into your\nPython path:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>pip install selenium\n</code></pre></div>\n<p>Then, add a <code class=\"docutils literal notranslate\">LiveServerTestCase</code>-based test to your app's tests module\n(for example: <code class=\"docutils literal notranslate\">myapp/tests.py</code>). For this example, we'll assume you're using\nthe <a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/staticfiles/#module-django.contrib.staticfiles\" title=\"django.contrib.staticfiles: An app for handling static files.\"><code class=\"xref py py-mod docutils literal notranslate\">staticfiles</code></a> app and want to have static files served\nduring the execution of your tests similar to what we get at development time\nwith <code class=\"docutils literal notranslate\">DEBUG=True</code>, i.e. without having to collect them using\n<a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/staticfiles/#django-admin-collectstatic\"><code class=\"xref std std-djadmin docutils literal notranslate\">collectstatic</code></a>. We'll use\nthe  <a class=\"reference internal\" href=\"/ja/1.10/ref/contrib/staticfiles/#django.contrib.staticfiles.testing.StaticLiveServerTestCase\" title=\"django.contrib.staticfiles.testing.StaticLiveServerTestCase\"><code class=\"xref py py-class docutils literal notranslate\">StaticLiveServerTestCase</code></a>\nsubclass which provides that functionality. Replace it with\n<code class=\"docutils literal notranslate\">django.test.LiveServerTestCase</code> if you don't need that.</p>\n<p>The code for this test may look as follows:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.contrib.staticfiles.testing</span> <span class=\"kn\">import</span> StaticLiveServerTestCase\n<span class=\"kn\">from</span> <span class=\"nn\">selenium.webdriver.firefox.webdriver</span> <span class=\"kn\">import</span> WebDriver\n\n<span class=\"k\">class</span> <span class=\"nc\">MySeleniumTests</span><span class=\"p\">(</span>StaticLiveServerTestCase<span class=\"p\">):</span>\n    fixtures <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"s1\">&#39;user-data.json&#39;</span><span class=\"p\">]</span>\n\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">setUpClass</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">):</span>\n        <span class=\"nb\">super</span><span class=\"p\">(</span>MySeleniumTests<span class=\"p\">,</span> <span class=\"bp\">cls</span><span class=\"p\">)</span><span class=\"o\">.</span>setUpClass<span class=\"p\">()</span>\n        <span class=\"bp\">cls</span><span class=\"o\">.</span>selenium <span class=\"o\">=</span> WebDriver<span class=\"p\">()</span>\n        <span class=\"bp\">cls</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>implicitly_wait<span class=\"p\">(</span><span class=\"mi\">10</span><span class=\"p\">)</span>\n\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">tearDownClass</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">):</span>\n        <span class=\"bp\">cls</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>quit<span class=\"p\">()</span>\n        <span class=\"nb\">super</span><span class=\"p\">(</span>MySeleniumTests<span class=\"p\">,</span> <span class=\"bp\">cls</span><span class=\"p\">)</span><span class=\"o\">.</span>tearDownClass<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_login</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;</span><span class=\"si\">%s%s</span><span class=\"s1\">&#39;</span> <span class=\"o\">%</span> <span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span>live_server_url<span class=\"p\">,</span> <span class=\"s1\">&#39;/login/&#39;</span><span class=\"p\">))</span>\n        username_input <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>find_element_by_name<span class=\"p\">(</span><span class=\"s2\">&quot;username&quot;</span><span class=\"p\">)</span>\n        username_input<span class=\"o\">.</span>send_keys<span class=\"p\">(</span><span class=\"s1\">&#39;myuser&#39;</span><span class=\"p\">)</span>\n        password_input <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>find_element_by_name<span class=\"p\">(</span><span class=\"s2\">&quot;password&quot;</span><span class=\"p\">)</span>\n        password_input<span class=\"o\">.</span>send_keys<span class=\"p\">(</span><span class=\"s1\">&#39;secret&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>find_element_by_xpath<span class=\"p\">(</span><span class=\"s1\">&#39;//input[@value=&quot;Log in&quot;]&#39;</span><span class=\"p\">)</span><span class=\"o\">.</span>click<span class=\"p\">()</span>\n</code></pre></div>\n<p>Finally, you may run the test as follows:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> myapp.tests.MySeleniumTests.test_login\n</code></pre></div>\n<p>This example will automatically open Firefox then go to the login page, enter\nthe credentials and press the &quot;Log in&quot; button. Selenium offers other drivers in\ncase you do not have Firefox installed or wish to use another browser. The\nexample above is just a tiny fraction of what the Selenium client can do; check\nout the <a class=\"reference external\" href=\"https://selenium-python.readthedocs.io/api.html\">full reference</a> for more details.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>When using an in-memory SQLite database to run the tests, the same database\nconnection will be shared by two threads in parallel: the thread in which\nthe live server is run and the thread in which the test case is run. It's\nimportant to prevent simultaneous database queries via this shared\nconnection by the two threads, as that may sometimes randomly cause the\ntests to fail. So you need to ensure that the two threads don't access the\ndatabase at the same time. In particular, this means that in some cases\n(for example, just after clicking a link or submitting a form), you might\nneed to check that a response is received by Selenium and that the next\npage is loaded before proceeding with further test execution.\nDo this, for example, by making Selenium wait until the <code class=\"docutils literal notranslate\">&lt;body&gt;</code> HTML tag\nis found in the response (requires Selenium &gt; 2.13):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">test_login</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"kn\">from</span> <span class=\"nn\">selenium.webdriver.support.wait</span> <span class=\"kn\">import</span> WebDriverWait\n    timeout <span class=\"o\">=</span> <span class=\"mi\">2</span>\n    <span class=\"o\">...</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"o\">.</span>find_element_by_xpath<span class=\"p\">(</span><span class=\"s1\">&#39;//input[@value=&quot;Log in&quot;]&#39;</span><span class=\"p\">)</span><span class=\"o\">.</span>click<span class=\"p\">()</span>\n    <span class=\"c1\"># Wait until the response is received</span>\n    WebDriverWait<span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span>selenium<span class=\"p\">,</span> timeout<span class=\"p\">)</span><span class=\"o\">.</span>until<span class=\"p\">(</span>\n        <span class=\"k\">lambda</span> driver<span class=\"p\">:</span> driver<span class=\"o\">.</span>find_element_by_tag_name<span class=\"p\">(</span><span class=\"s1\">&#39;body&#39;</span><span class=\"p\">))</span>\n</code></pre></div>\n<p>The tricky thing here is that there's really no such thing as a &quot;page load,&quot;\nespecially in modern Web apps that generate HTML dynamically after the\nserver generates the initial document. So, simply checking for the presence\nof <code class=\"docutils literal notranslate\">&lt;body&gt;</code> in the response might not necessarily be appropriate for all\nuse cases. Please refer to the <a class=\"reference external\" href=\"https://web.archive.org/web/20160129132110/http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa\">Selenium FAQ</a> and\n<a class=\"reference external\" href=\"http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-waits\">Selenium documentation</a> for more information.</p>\n</aside>\n</section>\n</section>\n<section id=\"test-cases-features\">\n<h2>Test cases features<a class=\"heading-anchor\" href=\"#test-cases-features\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"default-test-client\">\n<h3>Default test client<a class=\"heading-anchor\" href=\"#default-test-client\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.client\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">client</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.client\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Every test case in a <code class=\"docutils literal notranslate\">django.test.*TestCase</code> instance has access to an\ninstance of a Django test client. This client can be accessed as\n<code class=\"docutils literal notranslate\">self.client</code>. This client is recreated for each test, so you don't have to\nworry about state (such as cookies) carrying over from one test to another.</p>\n<p>This means, instead of instantiating a <code class=\"docutils literal notranslate\">Client</code> in each test:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">import</span> <span class=\"nn\">unittest</span>\n<span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> Client\n\n<span class=\"k\">class</span> <span class=\"nc\">SimpleTest</span><span class=\"p\">(</span>unittest<span class=\"o\">.</span>TestCase<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_details</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        client <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n        response <span class=\"o\">=</span> client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/details/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>status_code<span class=\"p\">,</span> <span class=\"mi\">200</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_index</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        client <span class=\"o\">=</span> Client<span class=\"p\">()</span>\n        response <span class=\"o\">=</span> client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/index/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>status_code<span class=\"p\">,</span> <span class=\"mi\">200</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>...you can just refer to <code class=\"docutils literal notranslate\">self.client</code>, like so:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n\n<span class=\"k\">class</span> <span class=\"nc\">SimpleTest</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_details</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/details/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>status_code<span class=\"p\">,</span> <span class=\"mi\">200</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_index</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/customer/index/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>response<span class=\"o\">.</span>status_code<span class=\"p\">,</span> <span class=\"mi\">200</span><span class=\"p\">)</span>\n</code></pre></div>\n</section>\n<section id=\"customizing-the-test-client\">\n<h3>Customizing the test client<a class=\"heading-anchor\" href=\"#customizing-the-test-client\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.client_class\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">client_class</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.client_class\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>If you want to use a different <code class=\"docutils literal notranslate\">Client</code> class (for example, a subclass\nwith customized behavior), use the <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.client_class\" title=\"django.test.SimpleTestCase.client_class\"><code class=\"xref py py-attr docutils literal notranslate\">client_class</code></a> class\nattribute:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase<span class=\"p\">,</span> Client\n\n<span class=\"k\">class</span> <span class=\"nc\">MyTestClient</span><span class=\"p\">(</span>Client<span class=\"p\">):</span>\n    <span class=\"c1\"># Specialized methods for your environment</span>\n    <span class=\"o\">...</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">MyTest</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    client_class <span class=\"o\">=</span> MyTestClient\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_my_stuff</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Here self.client is an instance of MyTestClient...</span>\n        call_some_test_code<span class=\"p\">()</span>\n</code></pre></div>\n</section>\n<section id=\"fixture-loading\">\n<span id=\"topics-testing-fixtures\"></span><h3>Fixture loading<a class=\"heading-anchor\" href=\"#fixture-loading\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.TransactionTestCase.fixtures\">\n<span class=\"sig-prename descclassname\">TransactionTestCase.</span><span class=\"sig-name descname\">fixtures</span><a class=\"heading-anchor\" href=\"#django.test.TransactionTestCase.fixtures\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>A test case for a database-backed website isn't much use if there isn't any\ndata in the database. Tests are more readable and it's more maintainable to\ncreate objects using the ORM, for example in <a class=\"reference internal\" href=\"#django.test.TestCase.setUpTestData\" title=\"django.test.TestCase.setUpTestData\"><code class=\"xref py py-meth docutils literal notranslate\">TestCase.setUpTestData()</code></a>,\nhowever, you can also use fixtures.</p>\n<p>A fixture is a collection of data that Django knows how to import into a\ndatabase. For example, if your site has user accounts, you might set up a\nfixture of fake user accounts in order to populate your database during tests.</p>\n<p>The most straightforward way of creating a fixture is to use the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#django-admin-dumpdata\"><code class=\"xref std std-djadmin docutils literal notranslate\">manage.py dumpdata</code></a> command. This assumes you\nalready have some data in your database. See the <a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#django-admin-dumpdata\"><code class=\"xref std std-djadmin docutils literal notranslate\">dumpdata\ndocumentation</code></a> for more details.</p>\n<p>Once you've created a fixture and placed it in a <code class=\"docutils literal notranslate\">fixtures</code> directory in one\nof your <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a>, you can use it in your unit tests by\nspecifying a <code class=\"docutils literal notranslate\">fixtures</code> class attribute on your <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">django.test.TestCase</code></a>\nsubclass:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n<span class=\"kn\">from</span> <span class=\"nn\">myapp.models</span> <span class=\"kn\">import</span> Animal\n\n<span class=\"k\">class</span> <span class=\"nc\">AnimalTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    fixtures <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"s1\">&#39;mammals.json&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;birds&#39;</span><span class=\"p\">]</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">setUp</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Test definitions as before.</span>\n        call_setup_methods<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">testFluffyAnimals</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># A test that uses the fixtures.</span>\n        call_some_test_code<span class=\"p\">()</span>\n</code></pre></div>\n<p>Here's specifically what will happen:</p>\n<ul class=\"simple\">\n<li><p>At the start of each test, before <code class=\"docutils literal notranslate\">setUp()</code> is run, Django will flush the\ndatabase, returning the database to the state it was in directly after\n<a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a> was called.</p></li>\n<li><p>Then, all the named fixtures are installed. In this example, Django will\ninstall any JSON fixture named <code class=\"docutils literal notranslate\">mammals</code>, followed by any fixture named\n<code class=\"docutils literal notranslate\">birds</code>. See the <a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#django-admin-loaddata\"><code class=\"xref std std-djadmin docutils literal notranslate\">loaddata</code></a> documentation for more\ndetails on defining and installing fixtures.</p></li>\n</ul>\n<p>For performance reasons, <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a> loads fixtures once for the entire\ntest class, before <a class=\"reference internal\" href=\"#django.test.TestCase.setUpTestData\" title=\"django.test.TestCase.setUpTestData\"><code class=\"xref py py-meth docutils literal notranslate\">setUpTestData()</code></a>, instead of before each\ntest, and it uses transactions to clean the database before each test. In any case,\nyou can be certain that the outcome of a test will not be affected by another\ntest or by the order of test execution.</p>\n<p>By default, fixtures are only loaded into the <code class=\"docutils literal notranslate\">default</code> database. If you are\nusing multiple databases and set <a class=\"reference internal\" href=\"#django.test.TransactionTestCase.multi_db\" title=\"django.test.TransactionTestCase.multi_db\"><code class=\"xref py py-attr docutils literal notranslate\">multi_db=True</code></a>, fixtures will be loaded into all databases.</p>\n</section>\n<section id=\"urlconf-configuration\">\n<h3>URLconf configuration<a class=\"heading-anchor\" href=\"#urlconf-configuration\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If your application provides views, you may want to include tests that use the\ntest client to exercise those views. However, an end user is free to deploy the\nviews in your application at any URL of their choosing. This means that your\ntests can't rely upon the fact that your views will be available at a\nparticular URL. Decorate your test class or test method with\n<code class=\"docutils literal notranslate\">&#64;override_settings(ROOT_URLCONF=...)</code> for URLconf configuration.</p>\n</section>\n<section id=\"multi-database-support\">\n<span id=\"emptying-test-outbox\"></span><h3>Multi-database support<a class=\"heading-anchor\" href=\"#multi-database-support\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.test.TransactionTestCase.multi_db\">\n<span class=\"sig-prename descclassname\">TransactionTestCase.</span><span class=\"sig-name descname\">multi_db</span><a class=\"heading-anchor\" href=\"#django.test.TransactionTestCase.multi_db\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Django sets up a test database corresponding to every database that is\ndefined in the <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> definition in your settings\nfile. However, a big part of the time taken to run a Django TestCase\nis consumed by the call to <code class=\"docutils literal notranslate\">flush</code> that ensures that you have a\nclean database at the start of each test run. If you have multiple\ndatabases, multiple flushes are required (one for each database),\nwhich can be a time consuming activity -- especially if your tests\ndon't need to test multi-database activity.</p>\n<p>As an optimization, Django only flushes the <code class=\"docutils literal notranslate\">default</code> database at\nthe start of each test run. If your setup contains multiple databases,\nand you have a test that requires every database to be clean, you can\nuse the <code class=\"docutils literal notranslate\">multi_db</code> attribute on the test suite to request a full\nflush.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">TestMyViews</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    multi_db <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_index_page_view</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        call_some_test_code<span class=\"p\">()</span>\n</code></pre></div>\n<p>This test case will flush <em>all</em> the test databases before running\n<code class=\"docutils literal notranslate\">test_index_page_view</code>.</p>\n<p>The <code class=\"docutils literal notranslate\">multi_db</code> flag also affects into which databases the\n<a class=\"reference internal\" href=\"#django.test.TransactionTestCase.fixtures\" title=\"django.test.TransactionTestCase.fixtures\"><code class=\"xref py py-attr docutils literal notranslate\">TransactionTestCase.fixtures</code></a> are loaded. By default (when\n<code class=\"docutils literal notranslate\">multi_db=False</code>), fixtures are only loaded into the <code class=\"docutils literal notranslate\">default</code> database.\nIf <code class=\"docutils literal notranslate\">multi_db=True</code>, fixtures are loaded into all databases.</p>\n</section>\n<section id=\"overriding-settings\">\n<span id=\"id1\"></span><h3>Overriding settings<a class=\"heading-anchor\" href=\"#overriding-settings\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>Use the functions below to temporarily alter the value of settings in tests.\nDon't manipulate <code class=\"docutils literal notranslate\">django.conf.settings</code> directly as Django won't restore\nthe original values after such manipulations.</p>\n</aside>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.settings\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">settings</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.settings\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>For testing purposes it's often useful to change a setting temporarily and\nrevert to the original value after running the testing code. For this use case\nDjango provides a standard Python context manager (see <span class=\"target\" id=\"index-1\"></span><a class=\"pep reference external\" href=\"https://peps.python.org/pep-0343/\"><strong>PEP 343</strong></a>) called\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.settings\" title=\"django.test.SimpleTestCase.settings\"><code class=\"xref py py-meth docutils literal notranslate\">settings()</code></a>, which can be used like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n\n<span class=\"k\">class</span> <span class=\"nc\">LoginTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_login</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n\n        <span class=\"c1\"># First check for the default behavior</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/sekrit/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertRedirects<span class=\"p\">(</span>response<span class=\"p\">,</span> <span class=\"s1\">&#39;/accounts/login/?next=/sekrit/&#39;</span><span class=\"p\">)</span>\n\n        <span class=\"c1\"># Then override the LOGIN_URL setting</span>\n        <span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>settings<span class=\"p\">(</span>LOGIN_URL<span class=\"o\">=</span><span class=\"s1\">&#39;/other/login/&#39;</span><span class=\"p\">):</span>\n            response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/sekrit/&#39;</span><span class=\"p\">)</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span>assertRedirects<span class=\"p\">(</span>response<span class=\"p\">,</span> <span class=\"s1\">&#39;/other/login/?next=/sekrit/&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>This example will override the <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-LOGIN_URL\"><code class=\"xref std std-setting docutils literal notranslate\">LOGIN_URL</code></a> setting for the code\nin the <code class=\"docutils literal notranslate\">with</code> block and reset its value to the previous state afterwards.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.modify_settings\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">modify_settings</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.modify_settings\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>It can prove unwieldy to redefine settings that contain a list of values. In\npractice, adding or removing values is often sufficient. The\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.modify_settings\" title=\"django.test.SimpleTestCase.modify_settings\"><code class=\"xref py py-meth docutils literal notranslate\">modify_settings()</code></a> context manager makes it\neasy:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n\n<span class=\"k\">class</span> <span class=\"nc\">MiddlewareTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_cache_middleware</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>modify_settings<span class=\"p\">(</span>MIDDLEWARE<span class=\"o\">=</span><span class=\"p\">{</span>\n            <span class=\"s1\">&#39;append&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class=\"p\">,</span>\n            <span class=\"s1\">&#39;prepend&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class=\"p\">,</span>\n            <span class=\"s1\">&#39;remove&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span>\n                <span class=\"s1\">&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;</span><span class=\"p\">,</span>\n                <span class=\"s1\">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class=\"p\">,</span>\n                <span class=\"s1\">&#39;django.contrib.messages.middleware.MessageMiddleware&#39;</span><span class=\"p\">,</span>\n            <span class=\"p\">],</span>\n        <span class=\"p\">}):</span>\n            response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">)</span>\n            <span class=\"c1\"># ...</span>\n</code></pre></div>\n<p>For each action, you can supply either a list of values or a string. When the\nvalue already exists in the list, <code class=\"docutils literal notranslate\">append</code> and <code class=\"docutils literal notranslate\">prepend</code> have no effect;\nneither does <code class=\"docutils literal notranslate\">remove</code> when the value doesn't exist.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.test.override_settings\">\n<span class=\"sig-name descname\">override_settings</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.override_settings\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>In case you want to override a setting for a test method, Django provides the\n<a class=\"reference internal\" href=\"#django.test.override_settings\" title=\"django.test.override_settings\"><code class=\"xref py py-func docutils literal notranslate\">override_settings()</code></a> decorator (see <span class=\"target\" id=\"index-2\"></span><a class=\"pep reference external\" href=\"https://peps.python.org/pep-0318/\"><strong>PEP 318</strong></a>). It's used\nlike this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase<span class=\"p\">,</span> override_settings\n\n<span class=\"k\">class</span> <span class=\"nc\">LoginTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"nd\">@override_settings</span><span class=\"p\">(</span>LOGIN_URL<span class=\"o\">=</span><span class=\"s1\">&#39;/other/login/&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_login</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/sekrit/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertRedirects<span class=\"p\">(</span>response<span class=\"p\">,</span> <span class=\"s1\">&#39;/other/login/?next=/sekrit/&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>The decorator can also be applied to <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a> classes:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase<span class=\"p\">,</span> override_settings\n\n<span class=\"nd\">@override_settings</span><span class=\"p\">(</span>LOGIN_URL<span class=\"o\">=</span><span class=\"s1\">&#39;/other/login/&#39;</span><span class=\"p\">)</span>\n<span class=\"k\">class</span> <span class=\"nc\">LoginTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_login</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/sekrit/&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertRedirects<span class=\"p\">(</span>response<span class=\"p\">,</span> <span class=\"s1\">&#39;/other/login/?next=/sekrit/&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.test.modify_settings\">\n<span class=\"sig-name descname\">modify_settings</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.modify_settings\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Likewise, Django provides the <a class=\"reference internal\" href=\"#django.test.modify_settings\" title=\"django.test.modify_settings\"><code class=\"xref py py-func docutils literal notranslate\">modify_settings()</code></a>\ndecorator:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase<span class=\"p\">,</span> modify_settings\n\n<span class=\"k\">class</span> <span class=\"nc\">MiddlewareTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"nd\">@modify_settings</span><span class=\"p\">(</span>MIDDLEWARE<span class=\"o\">=</span><span class=\"p\">{</span>\n        <span class=\"s1\">&#39;append&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;prepend&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"p\">})</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_cache_middleware</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">)</span>\n        <span class=\"c1\"># ...</span>\n</code></pre></div>\n<p>The decorator can also be applied to test case classes:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase<span class=\"p\">,</span> modify_settings\n\n<span class=\"nd\">@modify_settings</span><span class=\"p\">(</span>MIDDLEWARE<span class=\"o\">=</span><span class=\"p\">{</span>\n    <span class=\"s1\">&#39;append&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;prepend&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class=\"p\">,</span>\n<span class=\"p\">})</span>\n<span class=\"k\">class</span> <span class=\"nc\">MiddlewareTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_cache_middleware</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        response <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>client<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s1\">&#39;/&#39;</span><span class=\"p\">)</span>\n        <span class=\"c1\"># ...</span>\n</code></pre></div>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>When given a class, these decorators modify the class directly and return\nit; they don't create and return a modified copy of it. So if you try to\ntweak the above examples to assign the return value to a different name\nthan <code class=\"docutils literal notranslate\">LoginTestCase</code> or <code class=\"docutils literal notranslate\">MiddlewareTestCase</code>, you may be surprised to\nfind that the original test case classes are still equally affected by the\ndecorator. For a given class, <a class=\"reference internal\" href=\"#django.test.modify_settings\" title=\"django.test.modify_settings\"><code class=\"xref py py-func docutils literal notranslate\">modify_settings()</code></a> is\nalways applied after <a class=\"reference internal\" href=\"#django.test.override_settings\" title=\"django.test.override_settings\"><code class=\"xref py py-func docutils literal notranslate\">override_settings()</code></a>.</p>\n</aside>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>The settings file contains some settings that are only consulted during\ninitialization of Django internals. If you change them with\n<code class=\"docutils literal notranslate\">override_settings</code>, the setting is changed if you access it via the\n<code class=\"docutils literal notranslate\">django.conf.settings</code> module, however, Django's internals access it\ndifferently. Effectively, using <a class=\"reference internal\" href=\"#django.test.override_settings\" title=\"django.test.override_settings\"><code class=\"xref py py-func docutils literal notranslate\">override_settings()</code></a> or\n<a class=\"reference internal\" href=\"#django.test.modify_settings\" title=\"django.test.modify_settings\"><code class=\"xref py py-func docutils literal notranslate\">modify_settings()</code></a> with these settings is probably not\ngoing to do what you expect it to do.</p>\n<p>We do not recommend altering the <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> setting. Altering\nthe <a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-CACHES\"><code class=\"xref std std-setting docutils literal notranslate\">CACHES</code></a> setting is possible, but a bit tricky if you are\nusing internals that make using of caching, like\n<a class=\"reference internal\" href=\"/ja/1.10/topics/http/sessions/#module-django.contrib.sessions\" title=\"django.contrib.sessions: Provides session management for Django projects.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.sessions</code></a>. For example, you will have to reinitialize\nthe session backend in a test that uses cached sessions and overrides\n<a class=\"reference internal\" href=\"/ja/1.10/ref/settings/#std-setting-CACHES\"><code class=\"xref std std-setting docutils literal notranslate\">CACHES</code></a>.</p>\n<p>Finally, avoid aliasing your settings as module-level constants as\n<code class=\"docutils literal notranslate\">override_settings()</code> won't work on such values since they are\nonly evaluated the first time the module is imported.</p>\n</aside>\n<p>You can also simulate the absence of a setting by deleting it after settings\nhave been overridden, like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"nd\">@override_settings</span><span class=\"p\">()</span>\n<span class=\"k\">def</span> <span class=\"nf\">test_something</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"k\">del</span> settings<span class=\"o\">.</span>LOGIN_URL\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>When overriding settings, make sure to handle the cases in which your app's\ncode uses a cache or similar feature that retains state even if the setting is\nchanged. Django provides the <a class=\"reference internal\" href=\"/ja/1.10/ref/signals/#django.test.signals.setting_changed\" title=\"django.test.signals.setting_changed\"><code class=\"xref py py-data docutils literal notranslate\">django.test.signals.setting_changed</code></a>\nsignal that lets you register callbacks to clean up and otherwise reset state\nwhen settings are changed.</p>\n<p>Django itself uses this signal to reset various data:</p>\n<div class=\"table-scroll\" role=\"region\" tabindex=\"0\" aria-label=\"Table\"><table class=\"docutils align-default\">\n<thead>\n<tr class=\"row-odd\"><th class=\"head\"><p>Overridden settings</p></th>\n<th class=\"head\"><p>Data reset</p></th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"row-even\"><td><p>USE_TZ, TIME_ZONE</p></td>\n<td><p>Databases timezone</p></td>\n</tr>\n<tr class=\"row-odd\"><td><p>TEMPLATES</p></td>\n<td><p>Template engines</p></td>\n</tr>\n<tr class=\"row-even\"><td><p>SERIALIZATION_MODULES</p></td>\n<td><p>Serializers cache</p></td>\n</tr>\n<tr class=\"row-odd\"><td><p>LOCALE_PATHS, LANGUAGE_CODE</p></td>\n<td><p>Default translation and loaded translations</p></td>\n</tr>\n<tr class=\"row-even\"><td><p>MEDIA_ROOT, DEFAULT_FILE_STORAGE</p></td>\n<td><p>Default file storage</p></td>\n</tr>\n</tbody>\n</table>\n</div>\n</section>\n<section id=\"emptying-the-test-outbox\">\n<h3>Emptying the test outbox<a class=\"heading-anchor\" href=\"#emptying-the-test-outbox\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you use any of Django's custom <code class=\"docutils literal notranslate\">TestCase</code> classes, the test runner will\nclear the contents of the test email outbox at the start of each test case.</p>\n<p>For more detail on email services during tests, see <a class=\"reference internal\" href=\"#email-services\">Email services</a> below.</p>\n</section>\n<section id=\"assertions\">\n<span id=\"id2\"></span><h3>Assertions<a class=\"heading-anchor\" href=\"#assertions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>As Python's normal <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">unittest.TestCase</code></a> class implements assertion methods\nsuch as <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue\" title=\"(in Python v3.14)\"><code class=\"xref py py-meth docutils literal notranslate\">assertTrue()</code></a> and\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual\" title=\"(in Python v3.14)\"><code class=\"xref py py-meth docutils literal notranslate\">assertEqual()</code></a>, Django's custom <a class=\"reference internal\" href=\"#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a> class\nprovides a number of custom assertion methods that are useful for testing Web\napplications:</p>\n<p>The failure messages given by most of these assertion methods can be customized\nwith the <code class=\"docutils literal notranslate\">msg_prefix</code> argument. This string will be prefixed to any failure\nmessage generated by the assertion. This allows you to provide additional\ndetails that may help you to identify the location and cause of a failure in\nyour test suite.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertRaisesMessage\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertRaisesMessage</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">expected_exception</em>, <em class=\"sig-param\">expected_message</em>, <em class=\"sig-param\">callable</em>, <em class=\"sig-param\"><span class=\"o\">*</span>args</em>, <em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertRaisesMessage\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dt class=\"sig sig-object py\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertRaisesMessage</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">expected_exception</em>, <em class=\"sig-param\">expected_message</em><span class=\"sig-paren\">)</span></dt>\n<dd><p>Asserts that execution of <code class=\"docutils literal notranslate\">callable</code> raises <code class=\"docutils literal notranslate\">expected_exception</code> and\nthat <code class=\"docutils literal notranslate\">expected_message</code> is found in the exception's message. Any other\noutcome is reported as a failure. It's a simpler version of\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex\" title=\"(in Python v3.14)\"><code class=\"xref py py-meth docutils literal notranslate\">unittest.TestCase.assertRaisesRegex()</code></a> with the difference that\n<code class=\"docutils literal notranslate\">expected_message</code> isn't treated as a regular expression.</p>\n<p>If only the <code class=\"docutils literal notranslate\">expected_exception</code> and <code class=\"docutils literal notranslate\">expected_message</code> parameters are\ngiven, returns a context manager so that the code being tested can be\nwritten inline rather than as a function:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>assertRaisesMessage<span class=\"p\">(</span><span class=\"ne\">ValueError</span><span class=\"p\">,</span> <span class=\"s1\">&#39;invalid literal for int()&#39;</span><span class=\"p\">):</span>\n    <span class=\"nb\">int</span><span class=\"p\">(</span><span class=\"s1\">&#39;a&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<aside class=\"version-note version-deprecated\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">Deprecated since Django 1.9</p><p><span class=\"versionmodified deprecated\">バージョン 1.9 で非推奨: </span>Passing <code class=\"docutils literal notranslate\">callable</code> as a keyword argument called <code class=\"docutils literal notranslate\">callable_obj</code> is\ndeprecated. Pass the callable as a positional argument instead.</p>\n</aside>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertFieldOutput\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertFieldOutput</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">fieldclass</em>, <em class=\"sig-param\">valid</em>, <em class=\"sig-param\">invalid</em>, <em class=\"sig-param\">field_args<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">field_kwargs<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">empty_value<span class=\"o\">=</span><span class=\"default_value\">''</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertFieldOutput\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that a form field behaves correctly with various inputs.</p>\n<dl class=\"field-list simple\">\n<dt class=\"field-odd\">パラメータ<span class=\"colon\">:</span></dt>\n<dd class=\"field-odd\"><ul class=\"simple\">\n<li><p><strong>fieldclass</strong> -- the class of the field to be tested.</p></li>\n<li><p><strong>valid</strong> -- a dictionary mapping valid inputs to their expected cleaned\nvalues.</p></li>\n<li><p><strong>invalid</strong> -- a dictionary mapping invalid inputs to one or more raised\nerror messages.</p></li>\n<li><p><strong>field_args</strong> -- the args passed to instantiate the field.</p></li>\n<li><p><strong>field_kwargs</strong> -- the kwargs passed to instantiate the field.</p></li>\n<li><p><strong>empty_value</strong> -- the expected clean output for inputs in <code class=\"docutils literal notranslate\">empty_values</code>.</p></li>\n</ul>\n</dd>\n</dl>\n<p>For example, the following code tests that an <code class=\"docutils literal notranslate\">EmailField</code> accepts\n<code class=\"docutils literal notranslate\">a&#64;a.com</code> as a valid email address, but rejects <code class=\"docutils literal notranslate\">aaa</code> with a reasonable\nerror message:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"bp\">self</span><span class=\"o\">.</span>assertFieldOutput<span class=\"p\">(</span>EmailField<span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;a@a.com&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;a@a.com&#39;</span><span class=\"p\">},</span> <span class=\"p\">{</span><span class=\"s1\">&#39;aaa&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span><span class=\"s1\">&#39;Enter a valid email address.&#39;</span><span class=\"p\">]})</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertFormError\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertFormError</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">form</em>, <em class=\"sig-param\">field</em>, <em class=\"sig-param\">errors</em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertFormError\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that a field on a form raises the provided list of errors when\nrendered on the form.</p>\n<p><code class=\"docutils literal notranslate\">form</code> is the name the <code class=\"docutils literal notranslate\">Form</code> instance was given in the template\ncontext.</p>\n<p><code class=\"docutils literal notranslate\">field</code> is the name of the field on the form to check. If <code class=\"docutils literal notranslate\">field</code>\nhas a value of <code class=\"docutils literal notranslate\">None</code>, non-field errors (errors you can access via\n<a class=\"reference internal\" href=\"/ja/1.10/ref/forms/api/#django.forms.Form.non_field_errors\" title=\"django.forms.Form.non_field_errors\"><code class=\"xref py py-meth docutils literal notranslate\">form.non_field_errors()</code></a>) will\nbe checked.</p>\n<p><code class=\"docutils literal notranslate\">errors</code> is an error string, or a list of error strings, that are\nexpected as a result of form validation.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertFormsetError\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertFormsetError</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">formset</em>, <em class=\"sig-param\">form_index</em>, <em class=\"sig-param\">field</em>, <em class=\"sig-param\">errors</em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertFormsetError\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the <code class=\"docutils literal notranslate\">formset</code> raises the provided list of errors when\nrendered.</p>\n<p><code class=\"docutils literal notranslate\">formset</code> is the name the <code class=\"docutils literal notranslate\">Formset</code> instance was given in the template\ncontext.</p>\n<p><code class=\"docutils literal notranslate\">form_index</code> is the number of the form within the <code class=\"docutils literal notranslate\">Formset</code>.  If\n<code class=\"docutils literal notranslate\">form_index</code> has a value of <code class=\"docutils literal notranslate\">None</code>, non-form errors (errors you can\naccess via <code class=\"docutils literal notranslate\">formset.non_form_errors()</code>) will be checked.</p>\n<p><code class=\"docutils literal notranslate\">field</code> is the name of the field on the form to check. If <code class=\"docutils literal notranslate\">field</code>\nhas a value of <code class=\"docutils literal notranslate\">None</code>, non-field errors (errors you can access via\n<a class=\"reference internal\" href=\"/ja/1.10/ref/forms/api/#django.forms.Form.non_field_errors\" title=\"django.forms.Form.non_field_errors\"><code class=\"xref py py-meth docutils literal notranslate\">form.non_field_errors()</code></a>) will\nbe checked.</p>\n<p><code class=\"docutils literal notranslate\">errors</code> is an error string, or a list of error strings, that are\nexpected as a result of form validation.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertContains\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertContains</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">text</em>, <em class=\"sig-param\">count<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">status_code<span class=\"o\">=</span><span class=\"default_value\">200</span></em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">html<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertContains\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that a <code class=\"docutils literal notranslate\">Response</code> instance produced the given <code class=\"docutils literal notranslate\">status_code</code> and\nthat <code class=\"docutils literal notranslate\">text</code> appears in the content of the response. If <code class=\"docutils literal notranslate\">count</code> is\nprovided, <code class=\"docutils literal notranslate\">text</code> must occur exactly <code class=\"docutils literal notranslate\">count</code> times in the response.</p>\n<p>Set <code class=\"docutils literal notranslate\">html</code> to <code class=\"docutils literal notranslate\">True</code> to handle <code class=\"docutils literal notranslate\">text</code> as HTML. The comparison with\nthe response content will be based on HTML semantics instead of\ncharacter-by-character equality. Whitespace is ignored in most cases,\nattribute ordering is not significant. See\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\" title=\"django.test.SimpleTestCase.assertHTMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertHTMLEqual()</code></a> for more details.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertNotContains\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertNotContains</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">text</em>, <em class=\"sig-param\">status_code<span class=\"o\">=</span><span class=\"default_value\">200</span></em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">html<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertNotContains\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that a <code class=\"docutils literal notranslate\">Response</code> instance produced the given <code class=\"docutils literal notranslate\">status_code</code> and\nthat <code class=\"docutils literal notranslate\">text</code> does <em>not</em> appear in the content of the response.</p>\n<p>Set <code class=\"docutils literal notranslate\">html</code> to <code class=\"docutils literal notranslate\">True</code> to handle <code class=\"docutils literal notranslate\">text</code> as HTML. The comparison with\nthe response content will be based on HTML semantics instead of\ncharacter-by-character equality. Whitespace is ignored in most cases,\nattribute ordering is not significant. See\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\" title=\"django.test.SimpleTestCase.assertHTMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertHTMLEqual()</code></a> for more details.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertTemplateUsed\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertTemplateUsed</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">template_name</em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">count<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertTemplateUsed\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the template with the given name was used in rendering the\nresponse.</p>\n<p>The name is a string such as <code class=\"docutils literal notranslate\">'admin/index.html'</code>.</p>\n<p>The count argument is an integer indicating the number of times the\ntemplate should be rendered. Default is <code class=\"docutils literal notranslate\">None</code>, meaning that the template\nshould be rendered one or more times.</p>\n<p>You can use this as a context manager, like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>assertTemplateUsed<span class=\"p\">(</span><span class=\"s1\">&#39;index.html&#39;</span><span class=\"p\">):</span>\n    render_to_string<span class=\"p\">(</span><span class=\"s1\">&#39;index.html&#39;</span><span class=\"p\">)</span>\n<span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>assertTemplateUsed<span class=\"p\">(</span>template_name<span class=\"o\">=</span><span class=\"s1\">&#39;index.html&#39;</span><span class=\"p\">):</span>\n    render_to_string<span class=\"p\">(</span><span class=\"s1\">&#39;index.html&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertTemplateNotUsed\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertTemplateNotUsed</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">template_name</em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertTemplateNotUsed\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the template with the given name was <em>not</em> used in rendering\nthe response.</p>\n<p>You can use this as a context manager in the same way as\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertTemplateUsed\" title=\"django.test.SimpleTestCase.assertTemplateUsed\"><code class=\"xref py py-meth docutils literal notranslate\">assertTemplateUsed()</code></a>.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertRedirects\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertRedirects</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">response</em>, <em class=\"sig-param\">expected_url</em>, <em class=\"sig-param\">status_code<span class=\"o\">=</span><span class=\"default_value\">302</span></em>, <em class=\"sig-param\">target_status_code<span class=\"o\">=</span><span class=\"default_value\">200</span></em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em>, <em class=\"sig-param\">fetch_redirect_response<span class=\"o\">=</span><span class=\"default_value\">True</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertRedirects\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the response returned a <code class=\"docutils literal notranslate\">status_code</code> redirect status,\nredirected to <code class=\"docutils literal notranslate\">expected_url</code> (including any <code class=\"docutils literal notranslate\">GET</code> data), and that the\nfinal page was received with <code class=\"docutils literal notranslate\">target_status_code</code>.</p>\n<p>If your request used the <code class=\"docutils literal notranslate\">follow</code> argument, the <code class=\"docutils literal notranslate\">expected_url</code> and\n<code class=\"docutils literal notranslate\">target_status_code</code> will be the url and status code for the final\npoint of the redirect chain.</p>\n<p>If <code class=\"docutils literal notranslate\">fetch_redirect_response</code> is <code class=\"docutils literal notranslate\">False</code>, the final page won't be\nloaded. Since the test client can't fetch external URLs, this is\nparticularly useful if <code class=\"docutils literal notranslate\">expected_url</code> isn't part of your Django app.</p>\n<p>Scheme is handled correctly when making comparisons between two URLs. If\nthere isn't any scheme specified in the location where we are redirected to,\nthe original request's scheme is used. If present, the scheme in\n<code class=\"docutils literal notranslate\">expected_url</code> is the one used to make the comparisons to.</p>\n<aside class=\"version-note version-deprecated\" data-version=\"1.9\" role=\"note\">\n<p class=\"version-note-title\">Deprecated since Django 1.9</p><p><span class=\"versionmodified deprecated\">バージョン 1.9 で非推奨: </span>The <code class=\"docutils literal notranslate\">host</code> argument is deprecated, as redirections are no longer\nforced to be absolute URLs.</p>\n</aside>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertHTMLEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertHTMLEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">html1</em>, <em class=\"sig-param\">html2</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the strings <code class=\"docutils literal notranslate\">html1</code> and <code class=\"docutils literal notranslate\">html2</code> are equal. The comparison\nis based on HTML semantics. The comparison takes following things into\naccount:</p>\n<ul class=\"simple\">\n<li><p>Whitespace before and after HTML tags is ignored.</p></li>\n<li><p>All types of whitespace are considered equivalent.</p></li>\n<li><p>All open tags are closed implicitly, e.g. when a surrounding tag is\nclosed or the HTML document ends.</p></li>\n<li><p>Empty tags are equivalent to their self-closing version.</p></li>\n<li><p>The ordering of attributes of an HTML element is not significant.</p></li>\n<li><p>Attributes without an argument are equal to attributes that equal in\nname and value (see the examples).</p></li>\n</ul>\n<p>The following examples are valid tests and don't raise any\n<code class=\"docutils literal notranslate\">AssertionError</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"bp\">self</span><span class=\"o\">.</span>assertHTMLEqual<span class=\"p\">(</span>\n    <span class=\"s1\">&#39;&lt;p&gt;Hello &lt;b&gt;world!&lt;/p&gt;&#39;</span><span class=\"p\">,</span>\n    <span class=\"sd\">&#39;&#39;&#39;&lt;p&gt;</span>\n<span class=\"sd\">        Hello   &lt;b&gt;world! &lt;b/&gt;</span>\n<span class=\"sd\">    &lt;/p&gt;&#39;&#39;&#39;</span>\n<span class=\"p\">)</span>\n<span class=\"bp\">self</span><span class=\"o\">.</span>assertHTMLEqual<span class=\"p\">(</span>\n    <span class=\"s1\">&#39;&lt;input type=&quot;checkbox&quot; checked=&quot;checked&quot; id=&quot;id_accept_terms&quot; /&gt;&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;&lt;input id=&quot;id_accept_terms&quot; type=&quot;checkbox&quot; checked&gt;&#39;</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">html1</code> and <code class=\"docutils literal notranslate\">html2</code> must be valid HTML. An <code class=\"docutils literal notranslate\">AssertionError</code> will be\nraised if one of them cannot be parsed.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertHTMLNotEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertHTMLNotEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">html1</em>, <em class=\"sig-param\">html2</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertHTMLNotEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the strings <code class=\"docutils literal notranslate\">html1</code> and <code class=\"docutils literal notranslate\">html2</code> are <em>not</em> equal. The\ncomparison is based on HTML semantics. See\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\" title=\"django.test.SimpleTestCase.assertHTMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertHTMLEqual()</code></a> for details.</p>\n<p><code class=\"docutils literal notranslate\">html1</code> and <code class=\"docutils literal notranslate\">html2</code> must be valid HTML. An <code class=\"docutils literal notranslate\">AssertionError</code> will be\nraised if one of them cannot be parsed.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertXMLEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertXMLEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">xml1</em>, <em class=\"sig-param\">xml2</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertXMLEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the strings <code class=\"docutils literal notranslate\">xml1</code> and <code class=\"docutils literal notranslate\">xml2</code> are equal. The\ncomparison is based on XML semantics. Similarly to\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertHTMLEqual\" title=\"django.test.SimpleTestCase.assertHTMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertHTMLEqual()</code></a>, the comparison is\nmade on parsed content, hence only semantic differences are considered, not\nsyntax differences. When invalid XML is passed in any parameter, an\n<code class=\"docutils literal notranslate\">AssertionError</code> is always raised, even if both string are identical.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertXMLNotEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertXMLNotEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">xml1</em>, <em class=\"sig-param\">xml2</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertXMLNotEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the strings <code class=\"docutils literal notranslate\">xml1</code> and <code class=\"docutils literal notranslate\">xml2</code> are <em>not</em> equal. The\ncomparison is based on XML semantics. See\n<a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertXMLEqual\" title=\"django.test.SimpleTestCase.assertXMLEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertXMLEqual()</code></a> for details.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertInHTML\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertInHTML</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">needle</em>, <em class=\"sig-param\">haystack</em>, <em class=\"sig-param\">count<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">msg_prefix<span class=\"o\">=</span><span class=\"default_value\">''</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertInHTML\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the HTML fragment <code class=\"docutils literal notranslate\">needle</code> is contained in the <code class=\"docutils literal notranslate\">haystack</code> one.</p>\n<p>If the <code class=\"docutils literal notranslate\">count</code> integer argument is specified, then additionally the number\nof <code class=\"docutils literal notranslate\">needle</code> occurrences will be strictly verified.</p>\n<p>Whitespace in most cases is ignored, and attribute ordering is not\nsignificant. The passed-in arguments must be valid HTML.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertJSONEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertJSONEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">raw</em>, <em class=\"sig-param\">expected_data</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertJSONEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the JSON fragments <code class=\"docutils literal notranslate\">raw</code> and <code class=\"docutils literal notranslate\">expected_data</code> are equal.\nUsual JSON non-significant whitespace rules apply as the heavyweight is\ndelegated to the <a class=\"reference external\" href=\"https://docs.python.org/3/library/json.html#module-json\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">json</code></a> library.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.SimpleTestCase.assertJSONNotEqual\">\n<span class=\"sig-prename descclassname\">SimpleTestCase.</span><span class=\"sig-name descname\">assertJSONNotEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">raw</em>, <em class=\"sig-param\">expected_data</em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.SimpleTestCase.assertJSONNotEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that the JSON fragments <code class=\"docutils literal notranslate\">raw</code> and <code class=\"docutils literal notranslate\">expected_data</code> are <em>not</em> equal.\nSee <a class=\"reference internal\" href=\"#django.test.SimpleTestCase.assertJSONEqual\" title=\"django.test.SimpleTestCase.assertJSONEqual\"><code class=\"xref py py-meth docutils literal notranslate\">assertJSONEqual()</code></a> for further details.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.TransactionTestCase.assertQuerysetEqual\">\n<span class=\"sig-prename descclassname\">TransactionTestCase.</span><span class=\"sig-name descname\">assertQuerysetEqual</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">qs</em>, <em class=\"sig-param\">values</em>, <em class=\"sig-param\">transform<span class=\"o\">=</span><span class=\"default_value\">repr</span></em>, <em class=\"sig-param\">ordered<span class=\"o\">=</span><span class=\"default_value\">True</span></em>, <em class=\"sig-param\">msg<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.TransactionTestCase.assertQuerysetEqual\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that a queryset <code class=\"docutils literal notranslate\">qs</code> returns a particular list of values <code class=\"docutils literal notranslate\">values</code>.</p>\n<p>The comparison of the contents of <code class=\"docutils literal notranslate\">qs</code> and <code class=\"docutils literal notranslate\">values</code> is performed using\nthe function <code class=\"docutils literal notranslate\">transform</code>; by default, this means that the <code class=\"docutils literal notranslate\">repr()</code> of\neach value is compared. Any other callable can be used if <code class=\"docutils literal notranslate\">repr()</code> doesn't\nprovide a unique or helpful comparison.</p>\n<p>By default, the comparison is also ordering dependent. If <code class=\"docutils literal notranslate\">qs</code> doesn't\nprovide an implicit ordering, you can set the <code class=\"docutils literal notranslate\">ordered</code> parameter to\n<code class=\"docutils literal notranslate\">False</code>, which turns the comparison into a <code class=\"docutils literal notranslate\">collections.Counter</code> comparison.\nIf the order is undefined (if the given <code class=\"docutils literal notranslate\">qs</code> isn't ordered and the\ncomparison is against more than one ordered values), a <code class=\"docutils literal notranslate\">ValueError</code> is\nraised.</p>\n<p>Output in case of error can be customized with the <code class=\"docutils literal notranslate\">msg</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.test.TransactionTestCase.assertNumQueries\">\n<span class=\"sig-prename descclassname\">TransactionTestCase.</span><span class=\"sig-name descname\">assertNumQueries</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">num</em>, <em class=\"sig-param\">func</em>, <em class=\"sig-param\"><span class=\"o\">*</span>args</em>, <em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.TransactionTestCase.assertNumQueries\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Asserts that when <code class=\"docutils literal notranslate\">func</code> is called with <code class=\"docutils literal notranslate\">*args</code> and <code class=\"docutils literal notranslate\">**kwargs</code> that\n<code class=\"docutils literal notranslate\">num</code> database queries are executed.</p>\n<p>If a <code class=\"docutils literal notranslate\">&quot;using&quot;</code> key is present in <code class=\"docutils literal notranslate\">kwargs</code> it is used as the database\nalias for which to check the number of queries.  If you wish to call a\nfunction with a <code class=\"docutils literal notranslate\">using</code> parameter you can do it by wrapping the call with\na <code class=\"docutils literal notranslate\">lambda</code> to add an extra parameter:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"bp\">self</span><span class=\"o\">.</span>assertNumQueries<span class=\"p\">(</span><span class=\"mi\">7</span><span class=\"p\">,</span> <span class=\"k\">lambda</span><span class=\"p\">:</span> my_function<span class=\"p\">(</span>using<span class=\"o\">=</span><span class=\"mi\">7</span><span class=\"p\">))</span>\n</code></pre></div>\n<p>You can also use this as a context manager:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">with</span> <span class=\"bp\">self</span><span class=\"o\">.</span>assertNumQueries<span class=\"p\">(</span><span class=\"mi\">2</span><span class=\"p\">):</span>\n    Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Aaron&quot;</span><span class=\"p\">)</span>\n    Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Daniel&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n</section>\n<section id=\"tagging-tests\">\n<span id=\"topics-tagging-tests\"></span><h3>Tagging tests<a class=\"heading-anchor\" href=\"#tagging-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"version-note version-added\" data-version=\"1.10\" role=\"note\">\n<p class=\"version-note-title\">New in Django 1.10</p></aside>\n<p>You can tag your tests so you can easily run a particular subset. For example,\nyou might label fast or slow tests:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> tag\n\n<span class=\"k\">class</span> <span class=\"nc\">SampleTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n\n    <span class=\"nd\">@tag</span><span class=\"p\">(</span><span class=\"s1\">&#39;fast&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_fast</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"nd\">@tag</span><span class=\"p\">(</span><span class=\"s1\">&#39;slow&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_slow</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"nd\">@tag</span><span class=\"p\">(</span><span class=\"s1\">&#39;slow&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;core&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_slow_but_core</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"o\">...</span>\n</code></pre></div>\n<p>You can also tag a test case:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"nd\">@tag</span><span class=\"p\">(</span><span class=\"s1\">&#39;slow&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;core&#39;</span><span class=\"p\">)</span>\n<span class=\"k\">class</span> <span class=\"nc\">SampleTestCase</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>Then you can choose which tests to run. For example, to run only fast tests:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> --tag<span class=\"o\">=</span>fast\n</code></pre></div>\n<p>Or to run fast tests and the core one (even though it's slow):</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> --tag<span class=\"o\">=</span>fast --tag<span class=\"o\">=</span>core\n</code></pre></div>\n<p>You can also exclude tests by tag. To run core tests if they are not slow:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>./manage.py <span class=\"nb\">test</span> --tag<span class=\"o\">=</span>core --exclude-tag<span class=\"o\">=</span>slow\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#cmdoption-test-exclude-tag\"><code class=\"xref std std-option docutils literal notranslate\">test --exclude-tag</code></a> has precedence over <a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#cmdoption-test-tag\"><code class=\"xref std std-option docutils literal notranslate\">test --tag</code></a>, so if a\ntest has two tags and you select one of them and exclude the other, the test\nwon't be run.</p>\n</section>\n</section>\n<section id=\"email-services\">\n<span id=\"topics-testing-email\"></span><h2>Email services<a class=\"heading-anchor\" href=\"#email-services\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>If any of your Django views send email using <a class=\"reference internal\" href=\"/ja/1.10/topics/email/\"><span class=\"doc\">Django's email\nfunctionality</span></a>, you probably don't want to send email each time\nyou run a test using that view. For this reason, Django's test runner\nautomatically redirects all Django-sent email to a dummy outbox. This lets you\ntest every aspect of sending email -- from the number of messages sent to the\ncontents of each message -- without actually sending the messages.</p>\n<p>The test runner accomplishes this by transparently replacing the normal\nemail backend with a testing backend.\n(Don't worry -- this has no effect on any other email senders outside of\nDjango, such as your machine's mail server, if you're running one.)</p>\n<dl class=\"py data\">\n<dt class=\"sig sig-object py\" id=\"django.core.mail.django.core.mail.outbox\">\n<span class=\"sig-prename descclassname\">django.core.mail.</span><span class=\"sig-name descname\">outbox</span><a class=\"heading-anchor\" href=\"#django.core.mail.django.core.mail.outbox\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>During test running, each outgoing email is saved in\n<code class=\"docutils literal notranslate\">django.core.mail.outbox</code>. This is a simple list of all\n<a class=\"reference internal\" href=\"/ja/1.10/topics/email/#django.core.mail.EmailMessage\" title=\"django.core.mail.EmailMessage\"><code class=\"xref py py-class docutils literal notranslate\">EmailMessage</code></a> instances that have been sent.\nThe <code class=\"docutils literal notranslate\">outbox</code> attribute is a special attribute that is created <em>only</em> when\nthe <code class=\"docutils literal notranslate\">locmem</code> email backend is used. It doesn't normally exist as part of the\n<a class=\"reference internal\" href=\"/ja/1.10/topics/email/#module-django.core.mail\" title=\"django.core.mail: Helpers to easily send email.\"><code class=\"xref py py-mod docutils literal notranslate\">django.core.mail</code></a> module and you can't import it directly. The code\nbelow shows how to access this attribute correctly.</p>\n<p>Here's an example test that examines <code class=\"docutils literal notranslate\">django.core.mail.outbox</code> for length\nand contents:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.core</span> <span class=\"kn\">import</span> mail\n<span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n\n<span class=\"k\">class</span> <span class=\"nc\">EmailTest</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_send_email</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Send message.</span>\n        mail<span class=\"o\">.</span>send_mail<span class=\"p\">(</span>\n            <span class=\"s1\">&#39;Subject here&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Here is the message.&#39;</span><span class=\"p\">,</span>\n            <span class=\"s1\">&#39;from@example.com&#39;</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"s1\">&#39;to@example.com&#39;</span><span class=\"p\">],</span>\n            fail_silently<span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">,</span>\n        <span class=\"p\">)</span>\n\n        <span class=\"c1\"># Test that one message has been sent.</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span><span class=\"nb\">len</span><span class=\"p\">(</span>mail<span class=\"o\">.</span>outbox<span class=\"p\">),</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n\n        <span class=\"c1\"># Verify that the subject of the first message is correct.</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>mail<span class=\"o\">.</span>outbox<span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span><span class=\"o\">.</span>subject<span class=\"p\">,</span> <span class=\"s1\">&#39;Subject here&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>As noted <a class=\"reference internal\" href=\"#emptying-test-outbox\"><span class=\"std std-ref\">previously</span></a>, the test outbox is emptied\nat the start of every test in a Django <code class=\"docutils literal notranslate\">*TestCase</code>. To empty the outbox\nmanually, assign the empty list to <code class=\"docutils literal notranslate\">mail.outbox</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.core</span> <span class=\"kn\">import</span> mail\n\n<span class=\"c1\"># Empty the test outbox</span>\nmail<span class=\"o\">.</span>outbox <span class=\"o\">=</span> <span class=\"p\">[]</span>\n</code></pre></div>\n</section>\n<section id=\"management-commands\">\n<span id=\"topics-testing-management-commands\"></span><h2>管理コマンド<a class=\"heading-anchor\" href=\"#management-commands\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Management commands can be tested with the\n<a class=\"reference internal\" href=\"/ja/1.10/ref/django-admin/#django.core.management.call_command\" title=\"django.core.management.call_command\"><code class=\"xref py py-func docutils literal notranslate\">call_command()</code></a> function. The output can be\nredirected into a <code class=\"docutils literal notranslate\">StringIO</code> instance:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.core.management</span> <span class=\"kn\">import</span> call_command\n<span class=\"kn\">from</span> <span class=\"nn\">django.test</span> <span class=\"kn\">import</span> TestCase\n<span class=\"kn\">from</span> <span class=\"nn\">django.utils.six</span> <span class=\"kn\">import</span> StringIO\n\n<span class=\"k\">class</span> <span class=\"nc\">ClosepollTest</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_command_output</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        out <span class=\"o\">=</span> StringIO<span class=\"p\">()</span>\n        call_command<span class=\"p\">(</span><span class=\"s1\">&#39;closepoll&#39;</span><span class=\"p\">,</span> stdout<span class=\"o\">=</span>out<span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertIn<span class=\"p\">(</span><span class=\"s1\">&#39;Expected output&#39;</span><span class=\"p\">,</span> out<span class=\"o\">.</span>getvalue<span class=\"p\">())</span>\n</code></pre></div>\n</section>\n<section id=\"skipping-tests\">\n<span id=\"id3\"></span><h2>Skipping tests<a class=\"heading-anchor\" href=\"#skipping-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The unittest library provides the <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.skipIf\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\">&#64;skipIf</code></a> and\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.skipUnless\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\">&#64;skipUnless</code></a> decorators to allow you to skip tests\nif you know ahead of time that those tests are going to fail under certain\nconditions.</p>\n<p>For example, if your test requires a particular optional library in order to\nsucceed, you could decorate the test case with <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest.skipIf\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\">&#64;skipIf</code></a>. Then, the test runner will report that the test wasn't\nexecuted and why, instead of failing the test or omitting the test altogether.</p>\n<p>To supplement these test skipping behaviors, Django provides two\nadditional skip decorators. Instead of testing a generic boolean,\nthese decorators check the capabilities of the database, and skip the\ntest if the database doesn't support a specific named feature.</p>\n<p>The decorators use a string identifier to describe database features.\nThis string corresponds to attributes of the database connection\nfeatures class. See <code class=\"docutils literal notranslate\">django.db.backends.BaseDatabaseFeatures</code>\nclass for a full list of database features that can be used as a basis\nfor skipping tests.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.test.skipIfDBFeature\">\n<span class=\"sig-name descname\">skipIfDBFeature</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">*</span>feature_name_strings</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.skipIfDBFeature\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Skip the decorated test or <code class=\"docutils literal notranslate\">TestCase</code> if all of the named database features\nare supported.</p>\n<p>For example, the following test will not be executed if the database\nsupports transactions (e.g., it would <em>not</em> run under PostgreSQL, but\nit would under MySQL with MyISAM tables):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">MyTests</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"nd\">@skipIfDBFeature</span><span class=\"p\">(</span><span class=\"s1\">&#39;supports_transactions&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_transaction_behavior</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># ... conditional test code</span>\n        <span class=\"k\">pass</span>\n</code></pre></div>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.test.skipUnlessDBFeature\">\n<span class=\"sig-name descname\">skipUnlessDBFeature</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">*</span>feature_name_strings</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.test.skipUnlessDBFeature\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Skip the decorated test or <code class=\"docutils literal notranslate\">TestCase</code> if any of the named database features\nare <em>not</em> supported.</p>\n<p>For example, the following test will only be executed if the database\nsupports transactions (e.g., it would run under PostgreSQL, but <em>not</em>\nunder MySQL with MyISAM tables):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">MyTests</span><span class=\"p\">(</span>TestCase<span class=\"p\">):</span>\n    <span class=\"nd\">@skipUnlessDBFeature</span><span class=\"p\">(</span><span class=\"s1\">&#39;supports_transactions&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">def</span> <span class=\"nf\">test_transaction_behavior</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># ... conditional test code</span>\n        <span class=\"k\">pass</span>\n</code></pre></div>\n</section>","rootId":"testing-tools","toc":[{"title":"テストクライアント","anchor":"the-test-client","children":[{"title":"概要と簡単な例","anchor":"overview-and-a-quick-example","children":[]},{"title":"リクエストの作成","anchor":"making-requests","children":[]},{"title":"Testing responses","anchor":"testing-responses","children":[]},{"title":"例外","anchor":"exceptions","children":[]},{"title":"Persistent state","anchor":"persistent-state","children":[]},{"title":"Setting the language","anchor":"setting-the-language","children":[]},{"title":"カスタマイズ例","anchor":"example","children":[]}]},{"title":"Provided test case classes","anchor":"provided-test-case-classes","children":[{"title":"SimpleTestCase","anchor":"simpletestcase","children":[]},{"title":"TransactionTestCase","anchor":"transactiontestcase","children":[]},{"title":"TestCase","anchor":"testcase","children":[]},{"title":"LiveServerTestCase","anchor":"liveservertestcase","children":[]}]},{"title":"Test cases features","anchor":"test-cases-features","children":[{"title":"Default test client","anchor":"default-test-client","children":[]},{"title":"Customizing the test client","anchor":"customizing-the-test-client","children":[]},{"title":"Fixture loading","anchor":"fixture-loading","children":[]},{"title":"URLconf configuration","anchor":"urlconf-configuration","children":[]},{"title":"Multi-database support","anchor":"multi-database-support","children":[]},{"title":"Overriding settings","anchor":"overriding-settings","children":[]},{"title":"Emptying the test outbox","anchor":"emptying-the-test-outbox","children":[]},{"title":"Assertions","anchor":"assertions","children":[]},{"title":"Tagging tests","anchor":"tagging-tests","children":[]}]},{"title":"Email services","anchor":"email-services","children":[]},{"title":"管理コマンド","anchor":"management-commands","children":[]},{"title":"Skipping tests","anchor":"skipping-tests","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/1.10/topics/"},{"docname":"topics/testing/index","title":"Django におけるテスト","url":"/ja/1.10/topics/testing/"}],"prev":{"docname":"topics/testing/overview","title":"テストを書いて実行する","url":"/ja/1.10/topics/testing/overview/"},"next":{"docname":"topics/testing/advanced","title":"Advanced testing topics","url":"/ja/1.10/topics/testing/advanced/"},"formats":{"html":"/ja/1.10/topics/testing/tools/","markdown":"/ja/1.10/topics/testing/tools.md","json":"/ja/1.10/topics/testing/tools.json"},"source":"https://github.com/django/django/blob/stable/1.10.x/docs/topics/testing/tools.txt","official":"https://docs.djangoproject.com/ja/1.10/topics/testing/tools/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","fr","ja","id","pt-br","es","el","pl"]}