Unit-Testing two-integer answers in python

I’m currently working on a college assignment that requires me to do unit testing in python. The program I need to do unit testing for was very simple to make; I just needed it to take an input of two numbers, and then output the smaller number of the two, followed by the larger one.

I’m a bit confused on how to unit test this though. I can unit test in python by having something like:

    result = 3 + 7
    test1.assertEqual(result, 10)

However, I need something more like:

    input_a = 3
    input_b = 4
    test1.assertEqual(answer(input_a, input_b), 3, 4)

In a case like the one above, ‘answer’ is a function that checks which of the two numbers are bigger and smaller, and then returns them accordingly. For example, if ‘answer’ takes two numbers ‘a’ and ‘b’, where a > b, then the ‘answer’ function will end with ‘return b, a’.

I’ve tried the second code sample that I gave above, but it does not seem to work, as running the test gives an assertion error: AssertionError: (3, 4) != 3 : 4

Does anyone have any ideas on how I can or need to format a unit test that tests a sequence of two numbers? If so, I would appreciate it.

  • 2

    Maybe I’m misunderstanding but what’s wrong with assertEqual(answer(input_a, input_b), (3, 4))?

    – 

  • 3

    return 1, 2 is the same thing as return (1, 2) (a single tuple). Python is sometimes described as allowing functions to “return multiple values”, but that’s misleading. It’s just a tuple.

    – 




  • Well… I guess I didn’t think about using parenthesis on the two numbers. So, after seeing the comment, I tried it and it worked!

    – 

  • So… thanks for your help, sorry about the inconvenience- this question apparently had a simple solution I didn’t think to try.

    – 

  • Non-empty tuples are always defined by commas. The parentheses are needed only when the comma can be mistaken for another syntactic construct. foo(1, 2, 3) is a function call with 3 integer arguments; foo(1, (2,3)) is a function call with 1 integer argument and 1 tuple argument.

    – 




As suggested in the comments, you can enclose 3, 4 in parenthesis in order to resolve your issue like this:

test1.assertEqual(answer(input_a, input_b), (3, 4))

Note: your function returns a tuple of two values, you want the values used in comparison to match the tuple returned by your function in this Positive Test Case.

Leave a Comment