자동화된 테스트는 앞서서 shell 을 사용해 메소드의 동작을 검사하거나 데이터를 입력해서 테스트 한것과 다르지 않다. 차이점은 테스트 작업이 시스템에서 수행된다는 점이다. 한번 테스트 세트를 작성한 후에는 앱을 변경할 때 수동 테스트를 수행하지 않아도 원래 의도대로 코드가 작동하는지 확인할 수 있다.
자동화된 테스트를 통해 시간을 절약할 수 있다. 테스트를 작성하는 작업은 어플리케이션을 수동으로 테스트하거나 새로 발견된 문제의 원인을 확인하는 데 많은 시간을 투자하는 것보다 훨씬 더 효과적입니다.
문제를 식별하는 것이 아니라 예방할 수 있다.
애플리케이션 테스트는 일반적으로 <app_name>/tests.py 파일에 있다. 테스트 시스템은 test로 시작하는 메소드를 자동으로 찾는다.
$ python manage.py test polls
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMdoelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/jeongdaye/Documents/study/test_app/mysite2/polls/tests.py", line 13, in test_was_published_recently_with_future_question
self.assertIs(future_question.was_published_recently(),False)
AssertionError: True is not False
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return '%s >> %s' % (self.question_text, self.pub_date)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Destroying test database for alias 'default'...
$ python manage.py shell
Python 3.7.2 (default, Mar 5 2019, 16:08:31)
[Clang 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> 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/2/">Are you happy?</a></li>\n \n <li><a href="/polls/1/">What's your name?</a></li>\n \n </ul>\n'
>>> response.context['latest_question_list']
<QuerySet [<Question: Are you happy? >> 2019-04-05 05:54:39>, <Question: What's your name? >> 2019-04-04 06:21:55.323284>]>
>>>