Skip to Content
Pythonによるテスト駆動開発, 3rd Edition
book

Pythonによるテスト駆動開発, 3rd Edition

by Harry Percival
October 2025
Intermediate to advanced
712 pages
9h 46m
Japanese
O'Reilly Media, Inc.
Content preview from Pythonによるテスト駆動開発, 3rd Edition

第15章 シンプルなフォーム

この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com

前章の終わりで、 ビューの検証処理部分に重複が多すぎると指摘した。 Djangoはユーザ入力の検証やエラーメッセージの表示をフォームクラスで行うよう推奨している。

テストを使ってDjangoフォームの仕組みを探り、 その後ビューをリファクタリングしてフォームを活用する。 この過程で、単体テストと機能テストを組み合わせることで、 回帰から守られることを確認していこう。

検証ロジックをフォームに移す

ヒント

Djangoでは複雑なビューはコードの臭いである。 そのロジックの一部はフォームに移せないか? あるいはモデルクラスのカスタムメソッドに移せないか? あるいは(おそらく最善策として)ビジネスロジックを表すDjango以外のモジュールに移せないか?

Djangoではフォームにはいくつかの強力な機能がある:

  • これらはユーザ入力をプロセスし、エラーの有無を検証できる。

  • テンプレート内で HTML 入力要素やエラーメッセージのレンダリングに使える。

  • また、後で見るように、一部のフォームはデータをデータベースに保存することもできる。

全てのフォームでこれら3つの超能力を全て使う必要はない。独自のHTMLを記述したり、独自の保存処理を行ったりする方が好ましい場合もある。しかし検証ロジックを保持する場所としては最適だ。

単体テストでフォーム API を探る

単体テストを使ってフォームを少し試してみよう。完全な解決策に向けて段階的に進め、フォームを初めて見る人にも理解できる速度で導入していくつもりだ。

まずフォームの単体テスト用ファイルを追加し、フォームのHTMLを確認するだけのテストから始める:

src/リスト/テスト/テスト_フォーム.py (ch15l001)

from django.test import TestCase

from lists.forms import ItemForm


class ItemFormTest(TestCase):
    def test_form_renders_item_text_input(self):
        form = ItemForm()
        self.fail(form.as_p())

form.as_p() フォームをHTMLとしてレンダリングする。この単体テストでは、探索的なコーディングのためにself.failを使用している。manage.py shellセッションを使うことも可能だが、変更のたびにコードを再読み込みする必要がある。

最小限のフォームを作成しよう。これは基本クラスForm を継承し、item_text という単一のフィールドを持つ:

src/リスト/forms.py (ch15l002)

from django import forms


class ItemForm(forms.Form):
    item_text = forms.CharField()

これで自動生成されるフォームHTMLの 外観を示すエラーメッセージが表示される:

AssertionError: <p>
    <label for="id_item_text">Item text:</label>
    <input type="text" name="item_text" required id="id_item_text">
[...]
  </p>
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

イーサリアムをマスターする, 2nd Edition

イーサリアムをマスターする, 2nd Edition

Carlo Parisi, Alessandro Mazza, Niccolo Pozzolini, Gavin Wood, Andreas M. Antonopoulos
Excel用Python

Excel用Python

Felix Zumstein

Publisher Resources

ISBN: 0642572274771