Home > database >  Why does my unit testing return the wrong boolean value when my function works as it should?
Why does my unit testing return the wrong boolean value when my function works as it should?

Time:11-07

My program is supposed to return the compass point clockwise to what the user inputs.

When I test my function using print, it returns a value with false when it should be true.

def turn_clockwise(x):
    if x == 'N':
        print('E')
    elif x == 'E':
        print('S')
    elif x == 'S':
        print('W')
    elif x == 'W':
        print('N')
    else:
        print('Input is not a compass point.')

user_input = input('Enter a compass point: ')

turn_clockwise(user_input)

print(turn_clockwise('N')=='E')


The last print function tests whether the answer is true or false. Although the first call to function returns 'E', the test comes out as false. The following is what is printed into the terminal after my input of 'N'.

Enter a compass point: N

E

E

False

I also tried replacing == with != and it returns the expected answer which is true.

The output even prints out the answer of the function before returning the boolean.

CodePudding user response:

You're confusing return values with print statements.
When you print a value, it simply shows it to the screen, and doesn't return it out of the function.
If you want to return it as well as print, you need to add a return statement wherever you need it.

The reason your boolean value was false is because in the absence of a return statement, a function returns None, and None != 'E'.

def turn_clockwise(x):
    if x == 'N':
        print('E')
        return 'E'
    elif x == 'E':
        print('S')
        return 'S'
    elif x == 'S':
        print('W')
        return 'W'
    elif x == 'W':
        print('N')
        return 'N'
    else:
        print('Input is not a compass point.')
  • Related