Home > Net >  while writing Test for python script, the function I am Testing is interchanging the positional argu
while writing Test for python script, the function I am Testing is interchanging the positional argu

Time:12-29

import random

def run_game(guess, answer):
  if (0<guess<4):
      if (guess == answer):
          print('You Won!')
          return True
      else:
          print('Try Again!')
  else:
      print("Hey Bozo! I said 1~3")

if __name__ == '__main__':

  answer = random.randint(1,3)

  while True:
     try:
        guess = int(input('Please enter a number between 1~3:  ')

        if (run_game(guess, answer)):
             break
    
     except (ValueError,TypeError):
        print('Enter a number')
        continue

'''This is my test file'''

import unittest
import func_randomgame

class TestGame(unittest.TestCase):
    def test_1(self):
        result = func_randomgame.run_game(1, 1)
        self.assertTrue(result)
    def test_2(self):
        result = func_randomgame.run_game(5,1)
        self.assertFalse(result)
    def test_3(self):
        result = func_randomgame.run_game('5',1)
        self.assertFalse(result)



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

run_game(guess, answer) My fuction takes these two parameters. But test_3 is failing. If someone inputs string('5'), instead of a number result should be false and test_3 should be okay. But it is not the case. Please help me understand why is this happening.

CodePudding user response:

If someone inputs '5' as a string, the expression 0 < '5' < 4 fails with an exception:

TypeError: '<' not supported between instances of 'int' and 'str'

and thus your test is failing.

If you want your function to support string input, you should cast it before the comparison:

def run_game(guess, answer):
  guess_as_number = int(guess)
  if (0 < guess_as_number < 4):
      if (guess == answer):
          print('You Won!')
          return True
      else:
          print('Try Again!')
  else:
      print("Hey Bozo! I said 1~3")

This will handle this specific case. But for a more robust code, I'd suggest to surround with try..except and handle unexpected inputs with informative error message to the user.

CodePudding user response:

If someone inputs string('5'), instead of a number result should be false and test_3 should be okay. But it is not the case. Please help me understand why is this happening.

If you want your test case to pass, you need to check for the type of the guess variable before starting your calculations in your function. A simple fix would be as below.

def run_game(guess, answer):
    if type(guess) == int and (0<guess<4):
        if (guess == answer):
            print('You Won!')
            return True
        else:
            print('Try Again!')
    else:
        print("Hey Bozo! I said 1~3")

But it is to be recommended that you refactor your function for proper error handling with try except blocks

  • Related