pyhaya’s diary

機械学習系の記事をメインで書きます

Djangoで家計簿のWebアプリケーションを作る 5 テストを書く

DjangoでWebアプリケーションを作る解説記事です。今回のトピックはテストです。今更感がすごいですが、だいぶコードが増えてきたのでテストを書いてくさびを打っておきます。

前回の記事
pyhaya.hatenablog.com

モデルのテスト

from django.test import TestCase
from money.models import Money

# Create your tests here.
class TestMoneyModel(TestCase):
    def test_db_is_empty(self):
        money = Money.objects.all()
        self.assertEqual(money.count(), 0)

これをコマンドラインから実行します。

python manage.py test

すると次のように表示されます。

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

テスト用にデータベースが作られ、テストが終わったら消されていることがわかります。

一つデータを作ってみたときのテストケースも追加します。

import datetime
from django.utils import timezone
from django.test import TestCase

from money.models import Money

# Create your tests here.
class TestMoneyModel(TestCase):
    def test_db_is_empty(self):
        money = Money.objects.all()
        self.assertEqual(money.count(), 0)

    def test_save_data(self):
        use_date = timezone.now()
        detail = "テスト"
        cost = 100
        category = "食費"

        Money.objects.create(
                use_date = use_date,
                detail = detail,
                cost = cost,
                category = category,
                )
        obj = Money.objects.all()
        self.assertEqual(obj.count(), 1)
        self.assertEqual(obj[0].use_date, datetime.date.today())
        self.assertEqual(obj[0].detail, detail)
        self.assertEqual(obj[0].cost, cost)
        self.assertEqual(obj[0].category, category)

これでテストが通ることを確認します。

URLのテスト

URLを指定したときに正しいビューが返ってくることを確認します。

import datetime  
from django.urls import resolve
from django.utils import timezone
from django.test import TestCase

from money.models import Money
from money.views import index

#...

class TestURL(TestCase):
    def test_URL_resolve(self):
        url = resolve('/money/')
        self.assertEqual(url.func, index)    #上のURLでindexが呼ばれるか

        url = resolve('/money/2018/11')
        self.assertEqual(url.func, index)    #上のURLでindexが呼ばれるか

このようにテストを書いておくことで、後でコードを変更したときにアプリケーションが壊れていないかをすぐに検証することができます。

次回記事はこちら
pyhaya.hatenablog.com