본문 바로가기
lang/Django

Django 앱 작성하기 part5 [test]

by Wordbe 2019. 7. 12.
728x90

Test

장고는 버그 테스트를 자동으로 해준다.

  • 테스트를 통해 디버깅 시간을 절약할 수 있다.
  • 앞으로의 문제를 예방한다.
  • 신뢰도가 증가한다.
  • 협업 시 일을 돕는 효율적인 툴이 된다.

버그 케이스 만들기

$ python manage.py shell

>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> # create a Question instance with pub_date 30 days in the future
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()
True

버그를 찾아 출력하는 테스트 만들기

assert 함수를 이용합니다.

polls/test.py

import datetime

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

from .models import Question


class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

테스트 실행

$ python manage.py test polls

버그 수정

polls/models.py

    def was_published_recently(self):
        # test, 날짜가 과거에 있을 때에만 True 반환
        now = timezone.now()
        return (now - datetime.timedelta(days=1) <= self.pub_date) and (self.pub_date <= now)

클라이언트로 테스트하기!

$ python manage.py shell

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

>>> from django.test import Client
>>> # create an instance of the client for our use
>>> client = Client()
>>> # get a response from '/'
>>> response = client.get('/')
Not Found: /
>>> # we should expect a 404 from that address; if you instead see an
>>> # "Invalid HTTP_HOST header" error and a 400 response, you probably
>>> # omitted the setup_test_environment() call described earlier.
>>> response.status_code
404
>>> # on the other hand we should expect to find something at '/polls/'
>>> # we'll use 'reverse()' rather than a hardcoded URL
>>> from django.urls import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
200
>>> response.content
b'\n    <ul>\n    \n        <li><a href="/polls/1/">What&#39;s up?</a></li>\n    \n    </ul>\n\n'
>>> response.context['latest_question_list']
<QuerySet [<Question: What's up?>]>

<출처>: https://docs.djangoproject.com/ko/2.2/intro/tutorial05/

728x90

'lang > Django' 카테고리의 다른 글

Pycharm 단축키  (0) 2019.07.12
Django 앱 작성하기 part4 [form]  (0) 2019.07.12
Django 앱 작성하기 part3 [view]  (0) 2019.07.12
Django 앱 작성하기 part2 [model]  (0) 2019.07.11

댓글