{"title":"テストを書いて実行する","version":"4.2","locale":"ja","docname":"topics/testing/overview","url":"/ja/4.2/topics/testing/overview/","canonical":"https://djangodocs.dev/ja/4.2/topics/testing/overview/","summary":"ドキュメントは2つの大きなセクションに分けられます。前半のパートでは、Django でのテストの書き方を説明します。後半では、テストの実行の仕方について説明します。","html":"<span id=\"writing-and-running-tests\"></span><h1>テストを書いて実行する<a class=\"heading-anchor\" href=\"#module-django.test\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">参考</p>\n<p><a class=\"reference internal\" href=\"/ja/4.2/intro/tutorial05/\"><span class=\"doc\">テストチュートリアル</span></a>、 <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/\"><span class=\"doc\">テストツールリファレンス</span></a>、 <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/advanced/\"><span class=\"doc\">テストに関する応用的なトピック</span></a> も読んでください。</p>\n</aside>\n<p>ドキュメントは2つの大きなセクションに分けられます。前半のパートでは、Django でのテストの書き方を説明します。後半では、テストの実行の仕方について説明します。</p>\n<section id=\"writing-tests\">\n<h2>テストを書く<a class=\"heading-anchor\" href=\"#writing-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django のユニットテストには、Python スタンダードライブラリのモジュール、<a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#module-unittest\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">unittest</code></a> を使用します。このモジュールは、テストをクラスベースのアプローチで定義します。</p>\n<p>次の例では、 <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> のサブクラスである <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">django.test.TestCase</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.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\n<span class=\"k\">class</span> <span class=\"nc\">AnimalTestCase</span><span class=\"p\">(</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        Animal<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;lion&quot;</span><span class=\"p\">,</span> sound<span class=\"o\">=</span><span class=\"s2\">&quot;roar&quot;</span><span class=\"p\">)</span>\n        Animal<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;cat&quot;</span><span class=\"p\">,</span> sound<span class=\"o\">=</span><span class=\"s2\">&quot;meow&quot;</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">test_animals_can_speak</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"sd\">&quot;&quot;&quot;Animals that can speak are correctly identified&quot;&quot;&quot;</span>\n        lion <span class=\"o\">=</span> Animal<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;lion&quot;</span><span class=\"p\">)</span>\n        cat <span class=\"o\">=</span> Animal<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;cat&quot;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>lion<span class=\"o\">.</span>speak<span class=\"p\">(),</span> <span class=\"s1\">&#39;The lion says &quot;roar&quot;&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>cat<span class=\"o\">.</span>speak<span class=\"p\">(),</span> <span class=\"s1\">&#39;The cat says &quot;meow&quot;&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"#running-tests\"><span class=\"std std-ref\">自分で描いたテストを実行する</span></a> とき、テストユーティリティのデフォルトの動作は次のようなものです。まず、 <code class=\"docutils literal notranslate\">test</code> で始まる名前を持つファイルからすべてのテストケース (つまり <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> のすべてのサブクラス) を見つけ出します。次に、それらテストケースのテストスイートを自動的にビルドします。そして、ビルドしたテストスイートを実行します。</p>\n<p><a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#module-unittest\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">unittest</code></a> の詳細については、Python のドキュメントを読んでください。</p>\n<aside class=\"admonition-where-should-the-tests-live admonition\" role=\"note\">\n<p class=\"admonition-title\">どこにテストを書くべき？</p>\n<p>デフォルトの <a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#django-admin-startapp\"><code class=\"xref std std-djadmin docutils literal notranslate\">startapp</code></a> テンプレートは、新しいアプリケーション内に <code class=\"docutils literal notranslate\">tests.py</code> ファイルを作成します。テストの数が少ないうちは、ここに書くのがいいかもしれません。しかし、テストスイートが大きくなってきたら、テストを複数のパッケージに再構成して、<code class=\"docutils literal notranslate\">test_models.py</code> 、 <code class=\"docutils literal notranslate\">test_views.py</code> 、 <code class=\"docutils literal notranslate\">test_forms.py</code> などの異なるサブモジュールに分離すると良いでしょう。ファイル名には、ちゃんと組織的な命名規則になっていれば、自由に好きな名前をつけて構いません。</p>\n<p><a class=\"reference internal\" href=\"/ja/4.2/topics/testing/advanced/#testing-reusable-applications\"><span class=\"std std-ref\">Using the Django test runner to test reusable applications</span></a> も参照してください。</p>\n</aside>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>作成したテストが、データの新規作成やモデルのクエリなどのデータベースアクセスを必要とするときは、<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> ではなく、 <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">django.test.TestCase</code></a> のサブクラスを作るようにしてください。</p>\n<p><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> を使えば、各テストでデータベースのトランザクションとフラッシュに必要な実行コストを避けることができます。しかし、データベースと相互作用するテストの場合、テストランナーがテストを実行する順番によっては、異なる動作をすることがあります。そのため、孤立した環境では成功するテストユニットでも、一連のテストスイートの中で実行した時には失敗してしまうという状況が発生することがあります。</p>\n</aside>\n</section>\n<section id=\"running-tests\">\n<span id=\"id1\"></span><h2>テストの実行<a class=\"heading-anchor\" href=\"#running-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>テストが書けたら、プロジェクトの <code class=\"docutils literal notranslate\">manage.py</code> ユーティリティの <a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#django-admin-test\"><code class=\"xref std std-djadmin docutils literal notranslate\">test</code></a> コマンドでテストが実行できます。</p>\n<div class=\"code-block\" data-language=\"shell\"><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>$ ./manage.py <span class=\"nb\">test</span>\n</code></pre></div>\n<p>テストの探索方法は、unittest モジュールの <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#unittest-test-discovery\" title=\"(in Python v3.14)\"><span class=\"xref std std-ref\">ビルトインのテスト探索</span></a> にもとづきます。デフォルトでは、カレントディレクトリにある <code class=\"docutils literal notranslate\">test*.py</code> という名前の全てのファイルからテストを探し出します。</p>\n<p><code class=\"docutils literal notranslate\">/manage.py test</code> に好きな数の「テストラベル」を与えることで、特定のテストを指定することもできます。各テストラベルには、パッケージ、モジュール、 <code class=\"docutils literal notranslate\">TestCase</code> サブクラス、テストメソッドへのドット区切りの Python パスを指定します。たとえば、以下のように指定します。</p>\n<div class=\"code-block\" data-language=\"shell\"><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=\"c1\"># Run all the tests in the animals.tests module</span>\n$ ./manage.py <span class=\"nb\">test</span> animals.tests\n\n<span class=\"c1\"># Run all the tests found within the &#39;animals&#39; package</span>\n$ ./manage.py <span class=\"nb\">test</span> animals\n\n<span class=\"c1\"># Run just one test case</span>\n$ ./manage.py <span class=\"nb\">test</span> animals.tests.AnimalTestCase\n\n<span class=\"c1\"># Run just one test method</span>\n$ ./manage.py <span class=\"nb\">test</span> animals.tests.AnimalTestCase.test_animals_can_speak\n</code></pre></div>\n<p>ディレクトリ下に置かれたテストを探索するために、ディレクトリのパスを指定することもできます。</p>\n<div class=\"code-block\" data-language=\"shell\"><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>$ ./manage.py <span class=\"nb\">test</span> animals/\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">-p</code> (または <code class=\"docutils literal notranslate\">--pattern</code>) オプションを使って、カスタムのファイル名のパターンマッチを指定すれば、テストファイルの名前が <code class=\"docutils literal notranslate\">test*.py</code> というパターンとは違っていても実行することができます。</p>\n<div class=\"code-block\" data-language=\"shell\"><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>$ ./manage.py <span class=\"nb\">test</span> --pattern<span class=\"o\">=</span><span class=\"s2\">&quot;tests_*.py&quot;</span>\n</code></pre></div>\n<p>テストの実行中に <code class=\"docutils literal notranslate\">Ctrl-C</code> を押すと、テストランナーは現在実行中のテストが完了するのを待って、gracefully にテストを終了します。graceful な終了では、テストランナーは失敗したテストの詳細を出力し、実行したテストの数と、エラーおよび失敗したテストの数をレポートし、通常通りにテストデータベースを破棄します。そのため、 <code class=\"docutils literal notranslate\">Ctrl-C</code> を押すのは、たとえば、 <code class=\"xref std std-option docutils literal notranslate\">--failfast</code> オプションを付けるのを忘れて、一部のテストが予期せず失敗して、すべてのテストが終わるのを待たずにすぐにその失敗の詳細を知りたいような場合に大変役に立ちます。</p>\n<p>現在実行中のテストの終了も待ちたくないときは、もう一度 <code class=\"docutils literal notranslate\">Ctrl-C</code> を押すことで、テストを graceful ではなく、すぐに強制終了することができます。その場合、強制終了前に実行していたテストの詳細はリポートされず、実行中に作られたテストデータベースも破棄されません。</p>\n<aside class=\"admonition-test-with-warnings-enabled admonition\" role=\"note\">\n<p class=\"admonition-title\">警告を有効にしてテストする</p>\n<p><code class=\"docutils literal notranslate\">python -Wa manage.py test</code> というように、Python の警告表示を有効にしてテストを実行するのは良い考えです。<code class=\"docutils literal notranslate\">-Wa</code> フラグをセットすると、Python に deprecation 警告を表示するように伝えます。Django などの Python ライブラリは、機能の廃止を知らせるフラグとして、この警告を利用しています。また、この機能は、厳密には間違いではないがあまり良くないコードを知らせてくれることがあるので、実装を改善できることがあります。</p>\n</aside>\n<section id=\"the-test-database\">\n<span id=\"id2\"></span><h3>test データベース<a class=\"heading-anchor\" href=\"#the-test-database\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>データベースを必要とするテスト (すなわち、モデルテスト) には、&quot;実際の&quot; (production) 環境のデータベースは使用しません。代わりに、テスト用の空のデータベースを用意します。</p>\n<p>テストが成功したかどうかにかかわらず、すべてのテストの実行が終わった時点で、テストデータベースは破棄されます。</p>\n<p><a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-keepdb\"><code class=\"xref std std-option docutils literal notranslate\">test --keepdb</code></a> オプションを指定すれば、テストデータベースの破棄を防ぐことができます。これにより、複数回テストを実行しても、テストデータベースを保存することができます。データベースが存在しないときは、最初に新しく作成され、そしてデータベースが最新の状態になるように、マイグレーションが順番に実行されます。</p>\n<p>前のセクションで説明したように、テストの実行が強制的に中断された場合、テストデータベースが破棄されない可能性があります。次の実行では、データベースを再利用するか破棄するかを尋ねられるでしょう。<a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-noinput\"><code class=\"xref std std-option docutils literal notranslate\">test --noinput</code></a> オプションを使用すると、プロンプトを抑制し、データベースを自動的に破棄できます。このオプションは、たとえばタイムアウトでテスト中断される可能性がある継続的インテグレーションサーバー上でのテストの実行時などに役に立ちます。</p>\n<p>テストデータベースのデフォルトの名前は、 <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> 設定内の各 <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a> の値の前に <code class=\"docutils literal notranslate\">test_</code> を付けたものになります。SQLite を使っているときは、デフォルトでは、テストにはインメモリのデータベースを使います (つまり、データベースはメモリ内に作成されるため、ファイルシステムへのアクセスを完全になくすことができるのです！)。設定の <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> 内の <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-TEST\"><code class=\"xref std std-setting docutils literal notranslate\">TEST</code></a> ディクショナリには、テストデータベースに対するいろいろな設定を書くことができます。例えば、別のデータベース名を指定したければ、 <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-TEST\"><code class=\"xref std std-setting docutils literal notranslate\">TEST</code></a> ディクショナリの <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-TEST_NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a> に、 <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> の中から好きなデータベースを選んで指定することができます。</p>\n<p>PostgreSQL では、 <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-USER\"><code class=\"xref std std-setting docutils literal notranslate\">USER</code></a> が、ビルトインの <code class=\"docutils literal notranslate\">postgres</code> データベースへの読み取りアクセス権も持っている必要があります。</p>\n<p>テストランナーの使うデータベースは、独立したデータベースだけでなく、設定ファイルで指定した通りのデータベースを使用させることもできます: <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-ENGINE\"><code class=\"xref std std-setting docutils literal notranslate\">ENGINE</code></a>, <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-USER\"><code class=\"xref std std-setting docutils literal notranslate\">USER</code></a>, <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-HOST\"><code class=\"xref std std-setting docutils literal notranslate\">HOST</code></a>, などです。テストデータベースは、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-USER\"><code class=\"xref std std-setting docutils literal notranslate\">USER</code></a> で指定されたユーザによって作成されるため、そのユーザアカウントがシステム上で新しくデータベースを作成できる権限を持っている必要があります。</p>\n<p>テストデータベースの文字エンコーディングに対するきめ細かい対応をするために、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-TEST_CHARSET\"><code class=\"xref std std-setting docutils literal notranslate\">CHARSET</code></a> TEST オプションを使用してください。MySQL を使用している場合は、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-TEST_COLLATION\"><code class=\"xref std std-setting docutils literal notranslate\">COLLATION</code></a> オプションを使用してテストデータベースが使用する特別な照合をコントロールすることができます。 これらおよびより進歩的な設定の詳細については、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/\"><span class=\"doc\">設定のドキュメント</span></a> を参照してください。</p>\n<p>SQLite で SQLite インメモリデータベースを使用する場合、<a class=\"reference external\" href=\"https://www.sqlite.org/sharedcache.html\">shared cache</a> が有効になるため、スレッド間でデータベースを共有することが可能なテストを書くことができます。</p>\n<aside class=\"admonition-finding-data-from-your-production-database-when-running-tests admonition\" role=\"note\">\n<p class=\"admonition-title\">テストの実行中に本番データベースからデータを見つけるには？</p>\n<p>If your code attempts to access the database when its modules are compiled,\nthis will occur <em>before</em> the test database is set up, with potentially\nunexpected results. For example, if you have a database query in\nmodule-level code and a real database exists, production data could pollute\nyour tests. <em>It is a bad idea to have such import-time database queries in\nyour code</em> anyway - rewrite your code so that it doesn't do this.</p>\n<p>This also applies to customized implementations of\n<a class=\"reference internal\" href=\"/ja/4.2/ref/applications/#django.apps.AppConfig.ready\" title=\"django.apps.AppConfig.ready\"><code class=\"xref py py-meth docutils literal notranslate\">ready()</code></a>.</p>\n</aside>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">参考</p>\n<p>The <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/advanced/#topics-testing-advanced-multidb\"><span class=\"std std-ref\">advanced multi-db testing topics</span></a>.</p>\n</aside>\n</section>\n<section id=\"order-in-which-tests-are-executed\">\n<span id=\"order-of-tests\"></span><h3>テストの実行順序<a class=\"heading-anchor\" href=\"#order-in-which-tests-are-executed\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>すべての <code class=\"docutils literal notranslate\">TestCase</code> コードがクリーンなデータベースで実行されることを保証するために、Django のテストランナーは次の方法でテストの実行順序を決定します。</p>\n<ul class=\"simple\">\n<li><p>すべての <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\">TestCase</code></a> サブクラスが最初に実行されます。</p></li>\n<li><p>つぎに、すべての Django ベースのテスト (<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a> を含む <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.SimpleTestCase\" title=\"django.test.SimpleTestCase\"><code class=\"xref py py-class docutils literal notranslate\">SimpleTestCase</code></a> から作ったテストケース) を、実行順序が保証されず、また強制もされないような適当な順番で実行します。</p></li>\n<li><p>最後に、その他の <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> テスト (doctests を含む) が実行されます。このテストの中には、データベースを変更し、そのまま元の状態に戻さないようなテストがあることもあります。</p></li>\n</ul>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>この新しいテスト順序は、テストケース順序の予期しない依存関係を明らかにするかもしれません。これは、<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\">TransactionTestCase</code></a> によってデータベース内に記述された宣言に依存する doctests のケースで、これらは独立的に実行できるように修正する必要があります。</p>\n</aside>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>Failures detected when loading tests are ordered before all of the above\nfor quicker feedback. This includes things like test modules that couldn't\nbe found or that couldn't be loaded due to syntax errors.</p>\n</aside>\n<p>You may randomize and/or reverse the execution order inside groups using the\n<a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-shuffle\"><code class=\"xref std std-option docutils literal notranslate\">test --shuffle</code></a> and <a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-reverse\"><code class=\"xref std std-option docutils literal notranslate\">--reverse</code></a> options. This\ncan help with ensuring your tests are independent from each other.</p>\n</section>\n<section id=\"rollback-emulation\">\n<span id=\"test-case-serialized-rollback\"></span><h3>ロールバックのエミュレーション<a class=\"heading-anchor\" href=\"#rollback-emulation\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>マイグレーションで呼び出されるあらゆる初期データは、<code class=\"docutils literal notranslate\">TestCase</code> テスト内のみで有効で、 <code class=\"docutils literal notranslate\">TransactionTestCase</code> 内では無効です。加えて、トランザクションがサポートされるバックエンドのみで有効です (最も重要な例外は MyISAM です)。これは、<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.LiveServerTestCase\" title=\"django.test.LiveServerTestCase\"><code class=\"xref py py-class docutils literal notranslate\">LiveServerTestCase</code></a> や <a class=\"reference internal\" href=\"/ja/4.2/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> といった <code class=\"docutils literal notranslate\">TransactionTestCase</code> に依存するテストに関しても同様です。</p>\n<p>Django can reload that data for you on a per-testcase basis by\nsetting the <code class=\"docutils literal notranslate\">serialized_rollback</code> option to <code class=\"docutils literal notranslate\">True</code> in the body of the\n<code class=\"docutils literal notranslate\">TestCase</code> or <code class=\"docutils literal notranslate\">TransactionTestCase</code>, but note that this will slow down\nthat test suite by approximately 3x.</p>\n<p>Third-party apps or those developing against MyISAM will need to set this;\nin general, however, you should be developing your own projects against a\ntransactional database and be using <code class=\"docutils literal notranslate\">TestCase</code> for most tests, and thus\nnot need this setting.</p>\n<p>The initial serialization is usually very quick, but if you wish to exclude\nsome apps from this process (and speed up test runs slightly), you may add\nthose apps to <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-TEST_NON_SERIALIZED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">TEST_NON_SERIALIZED_APPS</code></a>.</p>\n<p>To prevent serialized data from being loaded twice, setting\n<code class=\"docutils literal notranslate\">serialized_rollback=True</code> disables the\n<a class=\"reference internal\" href=\"/ja/4.2/ref/signals/#django.db.models.signals.post_migrate\" title=\"django.db.models.signals.post_migrate\"><code class=\"xref py py-data docutils literal notranslate\">post_migrate</code></a> signal when flushing the test\ndatabase.</p>\n</section>\n<section id=\"other-test-conditions\">\n<h3>その他のテストに関する条件<a class=\"heading-anchor\" href=\"#other-test-conditions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>設定ファイルで指定した <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DEBUG\"><code class=\"xref std std-setting docutils literal notranslate\">DEBUG</code></a> の値にかかわらず、Django のテストは <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DEBUG\"><code class=\"xref std std-setting docutils literal notranslate\">DEBUG</code></a>=False を指定したものとして実行されます。これは、表示されるコードの出力が、実際の環境設定で見られるものと同じになるようにするためです。</p>\n<p>各テスト後にキャッシュはクリアされません。そのため、<code class=\"docutils literal notranslate\">manage.py test fooapp</code> を実行すると、テストで挿入されたデータが実働環境のシステムのキャッシュに残り続ける可能性があります。データベースの場合と違い、別の「テスト用のキャッシュ」が使われないためです。ただし、この動作は将来:ticket:変更される可能性があります &lt;11505&gt; 。</p>\n</section>\n<section id=\"understanding-the-test-output\">\n<h3>テストの出力を理解する<a class=\"heading-anchor\" href=\"#understanding-the-test-output\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>テストを実行すると、テストランナーが用意したたくさんのメッセージが表示されます。表示するメッセージの詳細レベルは、コマンドラインで <code class=\"docutils literal notranslate\">verbosity</code> オプションを指定することで、自由にコントロールできます。</p>\n<div class=\"code-block\" data-language=\"shell\"><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>Creating <span class=\"nb\">test</span> database...\nCreating table myapp_animal\nCreating table myapp_mineral\n</code></pre></div>\n<p>このメッセージは、テストランナーが前のセクションで説明したテスト用のデータベースを作成していることを表しています。</p>\n<p>テスト用データベースが作成されると、Django はテストを実行します。すべてのテストが成功すれば、次のようなメッセージが表示されるはずです。</p>\n<div class=\"code-block\" data-language=\"shell\"><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>----------------------------------------------------------------------\nRan <span class=\"m\">22</span> tests <span class=\"k\">in</span> <span class=\"m\">0</span>.221s\n\nOK\n</code></pre></div>\n<p>しかし、もしテストが失敗した場合には、失敗したテストとその詳細が表示されます。</p>\n<div class=\"code-block\" data-language=\"shell\"><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=\"o\">======================================================================</span>\nFAIL: test_was_published_recently_with_future_poll <span class=\"o\">(</span>polls.tests.PollMethodTests<span class=\"o\">)</span>\n----------------------------------------------------------------------\nTraceback <span class=\"o\">(</span>most recent call last<span class=\"o\">)</span>:\n  File <span class=\"s2\">&quot;/dev/mysite/polls/tests.py&quot;</span>, line <span class=\"m\">16</span>, <span class=\"k\">in</span> test_was_published_recently_with_future_poll\n    self.assertIs<span class=\"o\">(</span>future_poll.was_published_recently<span class=\"o\">()</span>, False<span class=\"o\">)</span>\nAssertionError: True is not False\n\n----------------------------------------------------------------------\nRan <span class=\"m\">1</span> <span class=\"nb\">test</span> <span class=\"k\">in</span> <span class=\"m\">0</span>.003s\n\nFAILED <span class=\"o\">(</span><span class=\"nv\">failures</span><span class=\"o\">=</span><span class=\"m\">1</span><span class=\"o\">)</span>\n</code></pre></div>\n<p>このエラー出力の詳しい説明は、このドキュメントの範囲外ですが、極めて直感的に理解できるものです。詳しく知りたければ、Python の <a class=\"reference external\" href=\"https://docs.python.org/3/library/unittest.html#module-unittest\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">unittest</code></a> ライブラリのドキュメントを読んでみてください。</p>\n<p>失敗したテストの数に関わらず（失敗の原因がエラー、アサーションの失敗、予期しない成功のいずれであっても）、テストランナーのスクリプトから返ってくる終了コードは 1 であることに注意してください。すべてのテストが成功すれば、0 が返ります。この特徴は、別のシェルスクリプトの中でテストランナースクリプトを実行するときに、成功したかどうかの情報が必要な時に役に立ちます。</p>\n<aside class=\"version-note version-changed\" data-version=\"4.1\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 4.1</p><p>古いバージョンでは、予期しない成功に対する返り値が 0 でした。</p>\n</aside>\n</section>\n<section id=\"speeding-up-the-tests\">\n<span id=\"speeding-up-tests-auth-hashers\"></span><h3>テストのスピードアップ<a class=\"heading-anchor\" href=\"#speeding-up-the-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<section id=\"running-tests-in-parallel\">\n<h4>テストの並列実行<a class=\"heading-anchor\" href=\"#running-tests-in-parallel\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>各テストが適切に独立性を保ったものであれば、マルチコアのハードウェア上でテストを並列実行することでスピートアップさせることができます。詳しくは <a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-parallel\"><code class=\"xref std std-option docutils literal notranslate\">test --parallel</code></a> を読んでください。</p>\n</section>\n<section id=\"password-hashing\">\n<h4>パスワードのハッシュ生成<a class=\"heading-anchor\" href=\"#password-hashing\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>デフォルトのパスワードのハッシュ生成器は、設計上、時間のかかるものになっています。テストの中で多数のユーザーを認証する必要がある場合、カスタムの設定ファイルを用意して、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-PASSWORD_HASHERS\"><code class=\"xref std std-setting docutils literal notranslate\">PASSWORD_HASHERS</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>PASSWORD_HASHERS <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"s2\">&quot;django.contrib.auth.hashers.MD5PasswordHasher&quot;</span><span class=\"p\">,</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-PASSWORD_HASHERS\"><code class=\"xref std std-setting docutils literal notranslate\">PASSWORD_HASHERS</code></a> には、必要なハッシュアルゴリズムが複数あっても、追加しておくことを忘れないようにしてください。</p>\n</section>\n<section id=\"preserving-the-test-database\">\n<h4>テストデータベースを保存する<a class=\"heading-anchor\" href=\"#preserving-the-test-database\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference internal\" href=\"/ja/4.2/ref/django-admin/#cmdoption-test-keepdb\"><code class=\"xref std std-option docutils literal notranslate\">test --keepdb</code></a> オプションで、テスト間でテストデータベースを保存することができます。テスト実行の際、データベース作成および破棄にかかる時間を大幅に短縮できます。</p>\n</section>\n<section id=\"avoiding-disk-access-for-media-files\">\n<h4>メディアファイルに対するディスクアクセスを回避する<a class=\"heading-anchor\" href=\"#avoiding-disk-access-for-media-files\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<aside class=\"version-note version-added\" data-version=\"4.2\" role=\"note\">\n<p class=\"version-note-title\">New in Django 4.2</p></aside>\n<p><a class=\"reference internal\" href=\"/ja/4.2/ref/files/storage/#django.core.files.storage.InMemoryStorage\" title=\"django.core.files.storage.InMemoryStorage\"><code class=\"xref py py-class docutils literal notranslate\">InMemoryStorage</code></a> は、メディアファイルに対するディスクアクセスを避けるための便利な手段です。すべてのデータはメモリ内にとどまり、テスト実行の後に破棄されます。</p>\n</section>\n</section>\n</section>","rootId":"module-django.test","toc":[{"title":"テストを書く","anchor":"writing-tests","children":[]},{"title":"テストの実行","anchor":"running-tests","children":[{"title":"test データベース","anchor":"the-test-database","children":[]},{"title":"テストの実行順序","anchor":"order-in-which-tests-are-executed","children":[]},{"title":"ロールバックのエミュレーション","anchor":"rollback-emulation","children":[]},{"title":"その他のテストに関する条件","anchor":"other-test-conditions","children":[]},{"title":"テストの出力を理解する","anchor":"understanding-the-test-output","children":[]},{"title":"テストのスピードアップ","anchor":"speeding-up-the-tests","children":[{"title":"テストの並列実行","anchor":"running-tests-in-parallel","children":[]},{"title":"パスワードのハッシュ生成","anchor":"password-hashing","children":[]},{"title":"テストデータベースを保存する","anchor":"preserving-the-test-database","children":[]},{"title":"メディアファイルに対するディスクアクセスを回避する","anchor":"avoiding-disk-access-for-media-files","children":[]}]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/4.2/topics/"},{"docname":"topics/testing/index","title":"Django におけるテスト","url":"/ja/4.2/topics/testing/"}],"prev":{"docname":"topics/testing/index","title":"Django におけるテスト","url":"/ja/4.2/topics/testing/"},"next":{"docname":"topics/testing/tools","title":"テストツール","url":"/ja/4.2/topics/testing/tools/"},"formats":{"html":"/ja/4.2/topics/testing/overview/","markdown":"/ja/4.2/topics/testing/overview.md","json":"/ja/4.2/topics/testing/overview.json"},"source":"https://github.com/django/django/blob/stable/4.2.x/docs/topics/testing/overview.txt","official":"https://docs.djangoproject.com/ja/4.2/topics/testing/overview/","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","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}