[Django][The Polls][Chap 3] Test 환경 구축하기(CLI, test.py)

Info Notice:
안녕하세요. HwanSeok입니다. The Polls 프로젝트는 docs.djangoproject.com를 참조하여 진행됩니다. 본 포스팅은 전체적인 개발 흐름과 The Polls 프로젝트를 효과적으로 이해하기 위한 설명이 포함되어 있습니다.

결과

개발 단계에서 Test 코드를 작성하고 실행하는 방법을 추가했습니다.

진행사항

현재 코드의 오류

Question 모델에서 was_published_recently는 어제 날짜보다 큰 경우 True를 return 합니다. 어제~오늘 사이에 이미 발행되었다면 True를 return하려는 의도였습니다.

1
2
3
4
5
6
7
8
9
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

하지만 아래와 같이 현재보다 앞선 미래의 시점에서도 True를 return 하는 문제가 있습니다.

1
2
3
4
5
6
7
8
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

비즈니스 로직을 잘 구성하는 것도 좋지만, test 환경을 잘 구축해야지 개발 과정에서 불필요한 시간 낭비를 많이 줄일 수 있습니다.

테스트 코드 작성

일일이 py mmmanage.py shell에서 테스트하지 않고 아래와 같이 자동화해서 확인해볼 수 있습니다.

아래는 False를 return 하기를 기대하는 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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)
1
2
# 실행
py manage.py test polls

Info Notice:
만약 아래와 같은 오류가 발생한다면

1
2
3
python manage.py test polls    
Creating test database for alias 'default'...  
Got an error creating the test database: 오류:  데이터베이스를 만들 권한이 없음  

postgreSQL에서 다음과 같이 수정해줍니다.

1
ALTER ROLE {username} CREATEDB;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 결과
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\dev\PycharmProjects\ThePolls\polls\tests.py", line 18, 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.004s

FAILED (failures=1)
Destroying test database for alias 'default'...

shell 명령어는 polls app을 찾고, django.test.TestCase를 찾은 뒤 test_로 시작하는 메서드를 찾아서 실행합니다.

1
2
3
def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

코드 개선

아래와 같이 수정하면 문제를 해결할 수 있습니다.

1
2
3
4
5
6
7
8
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.003s

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

테스트 추가

다음 테스트는 30일 후, 1초 전, 하루+1초 전에 생성된 객체에 대한 테스트를 진행합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def test_was_published_recently_with_old_question(self):
    """
    was_published_recently() returns False for questions whose pub_date
    is older than 1 day.
    """
    time = timezone.now() - datetime.timedelta(days=1, seconds=1)
    old_question = Question(pub_date=time)
    self.assertIs(old_question.was_published_recently(), False)

def test_was_published_recently_with_recent_question(self):
    """
    was_published_recently() returns True for questions whose pub_date
    is within the last day.
    """
    time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
    recent_question = Question(pub_date=time)
    self.assertIs(recent_question.was_published_recently(), True)
1
2
3
4
5
6
7
8
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.006s

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

CLI에서 client test 진행하기

다음과 같이 따라하면 됩니다. 다만 setup_test_environment를 사용하면 test database를 따로 설정하지 않고 client test를 진행합니다. 기존에 실행한 명령에 따라서 결과가 다르게 보일 수 있습니다.

1
py manage.py shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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&#x27;s up?</a></li>\n    \n    </ul>\n\n'
response.context['latest_question_list'] # <QuerySet [<Question: What's up?>]>

Editor에서 client test 진행하기

CLI에서 client test 진행하기 와 다르게 test.py를 사용해서 테스트를 진행하면 test database가 생성되고 매번 test_로 시작하는 method 마다 초기화가 일어납니다.

1
The database is reset for each test method, so the first question is no longer there, and so again the index shouldn’t have any questions in it.

create_question는 Class 밖에서 존재하는 객체를 생성해주는 기능을 수행합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
################TEST 2#################

def create_question(question_text, days):
    """
    Create a question with the given `question_text` and published the
    given number of `days` offset to now (negative for questions published
    in the past, positive for questions that have yet to be published).
    """
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)


class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        """
        If no questions exist, an appropriate message is displayed.
        """
        response = self.client.get(reverse('ns_polls:index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No polls are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_past_question(self):
        """
        Questions with a pub_date in the past are displayed on the
        index page.
        """
        create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse('ns_polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question.>']
        )

    def test_future_question(self):
        """
        Questions with a pub_date in the future aren't displayed on
        the index page.
        """
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('ns_polls:index'))
        self.assertContains(response, "No polls are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_future_question_and_past_question(self):
        """
        Even if both past and future questions exist, only past questions
        are displayed.
        """
        create_question(question_text="Past question.", days=-30)
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('ns_polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question.>']
        )

    def test_two_past_questions(self):
        """
        The questions index page may display multiple questions.
        """
        create_question(question_text="Past question 1.", days=-30)
        create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse('ns_polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question 2.>', '<Question: Past question 1.>']
        )

미래 시점의 객체 제외하기

미래 시점의 객체는 해당 객체가 생성되도록 설정된 시간이 지난 후에 화면에 보이도록 view를 수정해야 합니다. 객체를 조회할 때 filter()를 적용합니다.

1
2
3
4
5
6
7
8
9
10
from django.utils import timezone

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        # return Question.objects.order_by('-pub_date')[:5]
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

DetailView 수정하기

DetailView에도 get_queryset를 추가해줍니다.

1
2
3
4
5
6
7
8
9
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

Success Notice: 위와 같은 과정을 거쳐 처음에 보았던 결과 페이지를 생성하였습니다. 수고하셨습니다. :+1:

개발환경

  • window 10
  • python 3.6.8
  • django 3.1.5

Leave a comment