2012-10-05 4 views
0

저는 한 달 동안 파이썬으로 프로그래밍을 해왔지만 테스트 사례를 작성한 적이 없습니다. 다음 프로그램의 테스트 결정에 2 개의 테스트 세트를 쓰려고합니다.테스트 세트를 작성하여 파이썬에서 프로그램의 결정을 테스트하는 방법은 무엇입니까?

#!/usr/bin/python3 

def books(): 
    a = input("Enter number of books:") 
    inp = int(a) 
    if inp==0: 
     print("You earned 0 points") 
    elif inp==1: 
     print("You earned 5 points") 
    elif inp==2: 
     print("You earned 15 points") 
    elif inp==3: 
     print("You earned 30 points") 
    elif inp==4: 
     print("You earned 60 points") 
    else: 
     print("No Negatives") 

books() 

이 프로그램의 결정을 테스트하기 위해 2 가지 테스트 세트를 작성하려면 어떻게합니까? 감사! 질문의 두 번째 버전에 대한

+0

왜 당신이 기능에 매개 변수를 원하는가'books' – avasal

+0

실수! 내 질문을 수정했습니다. –

답변

0

편집 :

def books(): 

    points = [0,5,15,30,60]; # list of the points 
    inp = 0; 

    while inp < 0 or inp >= len(points): 
     a = input("Enter number of books:") 
     inp = int(a) 

    print("You earned",points[inp],"points") 

books() 

당신은 책의 수와 점의 수 사이에 직접적인 상관 관계가있는 경우 목록을 피할 수 있지만 나도 몰라 그 알고리즘.

inp의 값이 문자열 인 경우 목록 대신 사전을 사용할 수 있습니다.

+0

답변 해 주셔서 감사합니다. 하지만 잘못된 코드를 게시 한 것처럼 보입니다. 내 질문을 편집했습니다. 당신도 그것을보고 너무 대답을 편집 할 수 있습니다. 감사! –

+0

답변이 업데이트되었습니다. – cdarke

0

테스트 예를 찾고있는 것처럼 들립니다. 파이썬 2.7에서이 작업이 수행되었다고 말하면주의 할 것이지만, 3에서 작동 할 것이라고 믿는다. (print 명령문을 함수로 변경했다. 나머지 작업은 확실하지 않다. :)). 코드에 몇 가지 수정을가했습니다 (cdarke에서 언급했듯이 포인트 수를 설정하는 더 쉬운 방법이 있지만이를 테스트 할 수있는 단계를 볼 수 있도록이 코드를 원본 코드와 가깝게 유지합니다). 다음

def Books(num_books): 
    # We let books take a parameter so that we can test it with different 
    # input values. 
    try: 
     # Convert to int and then choose your response 
     num_books = int(num_books) 
     if num_books < 0: 
      response = "No Negatives" 
     elif num_books == 0: 
      response = "You earned 0 points" 
     elif num_books == 1: 
      response = "You earned 5 points" 
     elif num_books == 2: 
      response = "You earned 15 points" 
     elif num_books == 3: 
      response = "You earned 30 points" 
     elif num_books == 4: 
      response = "You earned 60 points" 
     else: 
      response = "That's a lot of books" 

    except ValueError: 
     # This could be handled in a better way, but this lets you handle 
     # the case when a user enters a non-number (and lets you test the 
     # exception) 
     raise ValueError("Please enter a number.") 

    return response 


def main(): 
    # Here we wrap the main code in the main function to prevent it from 
    # executing when it is imported (which is what happens in the test case) 

    # Get the input from the user here - this way you can bypass entering a 
    # number in your tests. 
    a = input("Enter number of books: ") 

    # Print the result 
    print(Books(a)) 


if __name__ == '__main__': 
    main() 

그리고 당신은 단순히 python my_program_test.py으로 실행할 수있는 테스트 : 여기에 귀하의 코드 (주석) 약간의 수정이다

import my_program 
import unittest 

class MyProgramTest(unittest.TestCase): 

    def testBooks(self): 
     # The results you know you want 
     correct_results = { 
      0: "You earned 0 points", 
      1: "You earned 5 points", 
      2: "You earned 15 points", 
      3: "You earned 30 points", 
      4: "You earned 60 points", 
      5: "That's a lot of books" 
      } 

     # Now iterate through the dict, verifying that you get what you expect 
     for num, value in correct_results.iteritems(): 
      self.assertEqual(my_program.Books(num), value) 


    def testNegatives(self): 
     # Test a negative number to ensure you get the right response 
     num = -3 
     self.assertEqual(my_program.Books(num), "No Negatives") 


    def testNumbersOnly(self): 
     # This is kind of forced in there, but this tests to make sure that 
     # the proper exception is raised when a non-number is entered 
     non_number = "Not a number" 
     self.assertRaises(ValueError, my_program.Books, non_number) 

if __name__ == '__main__': 
    unittest.main() 
+0

@ 새 폴더 (New Folder) :이 대답은 파이썬 2에 대한 것입니다.'print' 문장에서 판단 할 때 파이썬 3을 사용하고있을 것입니다.'raw_input'은'input'을위한 오래된 파이썬입니다. (@RocketDonkey가'print'의 함수 버전을 사용했음을 알았지 만, 일반적으로 오래된 파이썬에서'from __future__ import print_function' 만 사용 가능합니다.) – cdarke

+0

@cdarke 그래, 파이썬 2.7에서 쓰고 있었고 코드 그래서 3을 가지고 그에게 도움이 될 것입니다 - 3 (나는 raw_input, 좋은 지적을 고칠 것입니다)과 함께 작동하지 않을 것입니다 내 것이 무엇입니까? 나는 어떤 점에서 그것을 사용해야한다고 생각한다. :) – RocketDonkey

+0

Nah, 그냥 '입력'SFAIK. 미안해해서 미안해. 예외 처리에는 몇 가지 변화가 있으며'unittest'의 몇 가지 새로운 기능이 있습니다 만, 기존의 것들이 여러분이 사용하는만큼 작동해야한다고 생각합니다. – cdarke

관련 문제