Python Unit Test

buzonliao
Python 101
Published in
2 min readOct 11, 2023
Photo by Ferenc Almasi on Unsplash

Take your number-guessing game to the next level with Python. This script defines a function that accepts a user’s input between 1 and 10 and tests it against a randomly generated answer. Enhance your code’s testability by encapsulating the logic within a function. The included unit tests ensure your game’s functionality is rock-solid. Run the tests using python3 -m unittest -v for a comprehensive evaluation of your code.

Function

  • Accept an input number between 1 and 10
  • Put logic in a function for better testing
import random

def run_guess_game(guess, answer):
try:
if 0 < guess < 11:
if guess == answer:
print('you are a genius!')
return True
else:
print('hey boo, I said 1~10')
return False
except TypeError:
print('please enter a number')
return False

if __name__ == '__main__':
answer = random.randint(1,10)
while True:
try:
guess = int(input('guess a number 1~10: '))
if (run_guess_game(guess, answer)):
break
except ValueError:
print('please enter a number')
continue

Test Code


import unittest
import guess_number

class TestGame(unittest.TestCase):

def test_input(self):
guess = 10
answer = 10
result = guess_number.run_guess_game(guess,answer)
self.assertTrue(result)

def test_input_wrong_guess(self):
guess = 0
answer = 5
result = guess_number.run_guess_game(guess,answer)
self.assertFalse(result)

def test_input_out_of_bound(self):
guess = 11
answer = 15
result = guess_number.run_guess_game(guess,answer)
self.assertFalse(result)

def test_input_wrong_type(self):
guess = '11'
answer = 5
result = guess_number.run_guess_game(guess,answer)
self.assertFalse(result)

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

Execute

python3 -m unittest -v

--

--