170310_TIL

|

오늘 한 일

  • 간단한 알고리즘 문제를 풀었다.
  • 첫 장고 개인프로젝트 메모 사이트 에 좋아요 기능을 추가했다. DB 테이블에 좋아요 필드를 추가하기 위해서 ManyToManyField를 공부하고 적용했다. 그리고 새로고침 없이 좋아요 숫자가 올라가도록 하려고 ajax를 활용했다. 원하는 기능을 추가하면서 새롭게 공부하는 점이 많은 것 같다.이전에 접했을 땐 잘 공감이 가지 않던 개념도 필요성이 생기니 더 잘 이해가 가는 것 같다.
  • django 강의 를 들었다. admin 사이트를 customize 하는 방법을 배웠다.

내일 할 일

  • 장고 프로젝트에 정렬기능 추가하기
  • 장고 강의 듣기
  • 점프투 파이썬 읽기 (튜플)

level 2. 요일 구하기

|

level 2. 요일 구하기

출처

문제

2016년 1월 1일은 금요일입니다. 2016년 A월 B일은 무슨 요일일까요? 두 수 A,B를 입력받아 A월 B일이 무슨 요일인지 출력하는 getDayName 함수를 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각

SUN,MON,TUE,WED,THU,FRI,SAT

를 출력해주면 됩니다. 예를 들어 A=5, B=24가 입력된다면 5월 24일은 화요일이므로 TUE를 반환하면 됩니다.

풀이 (python)

import datetime
def getDayName(a,b):
	return ['MON','TUE','WED','THU','FRI','SAT','SUN'][datetime.date(2016, a, b).weekday()]
#아래 코드는 테스트를 위한 출력 코드입니다.
print(getDayName(5,24))

배운점

  • datetime 모듈의 weekday() 메소드를 통해서 특정일의 요일을 구할 수 있다. 가이드문서

170309_TIL

|

django 06. 두번째 장고앱 14 - view 및 템플릿 테스트 하기

|

파이썬 웹 프로그래밍 - Django로 웹 서비스 개발하기

view 테스트하기

장고 테스트 클라이언트 생성 및 테스트

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

>>> from django.test import Client
>>> client = Client()

>>> from django.urls import reverse
>>> reverse('polls:index')
>>> reverse('polls:detail', kwargs = {'pk':10})
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
>>> response.content
>>> response.context['latest_question_list']

polls/views.py 업데이트

from django.utils import timezone

def get_queryset(self):
    return Question.objects.filter(
        pub_date__lte=timezone.now()
    ).order_by('-pub_date')[:5]

테스트에 view 테스트 추가

from django.urls import reverse

def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)


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

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

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

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

    def test_index_view_with_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('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question 2.>', '<Question: Past question 1.>']
        )

django 06. 두번째 장고앱 13 - 버그 수정 및 테스트 자동화

|

파이썬 웹 프로그래밍 - Django로 웹 서비스 개발하기

버그 확인

$ python manage.py shell
>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=7))
>>> future_question.was_published_recently()
True

테스트 파일 작성

  • polls/tests.py 수정
import datetime

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

from .models import Question


class QuestionMethodTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        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):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

더 많은 테스트 코드

def test_was_published_recently_with_old_question(self):
    """
    was_published_recently() should return False for questions whose
    pub_date is older than 1 day.
    """
    time = timezone.now() - datetime.timedelta(days=30)
    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() should return True for questions whose
    pub_date is within the last day.
    """
    time = timezone.now() - datetime.timedelta(hours=1)
    recent_question = Question(pub_date=time)
    self.assertIs(recent_question.was_published_recently(), True)