2

I'm writing a unittest that will be run on my class's code. For one of the functions they must write, there are two possible return values that they could return and either one is okay for my purposes.

I've been using

actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)

But this doesn't work for accepting one of two valid return values, so I've changed it to:

actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)

Is there a way to do this that isn't as hacky?

4
  • 2
    Use: self.assertTrue(actual == expected1 or actual == expected2) Commented Feb 8, 2022 at 14:51
  • I've found it, thanks everyone! stackoverflow.com/questions/68506299/… Commented Feb 8, 2022 at 14:53
  • 1
    @jarmod note stackoverflow.com/questions/71035906/…, your suggestion has a similar problem. It's fine when the test passes, but if it ever fails it's not particularly helpful in figuring out what the problem was. (Related: stackoverflow.com/a/34414463/3001761) Commented Feb 8, 2022 at 15:06
  • @jonrsharpe agreed, much better. Wasn't aware of assertIn until I read the docs earlier, at which point I was beyond the 5 minute window to edit. Commented Feb 8, 2022 at 15:12

2 Answers 2

5

There exists assertIn test, which you could use in this case as follows

self.assertIn(actual,[expected1,expected2])

it does check if actual is present in list holding expected1,expected2.

Sign up to request clarification or add additional context in comments.

Comments

2

You can do assertTrue and in

self.assertTrue(actual in (expected1, expected2))

1 Comment

There's also assertIn, which gives substantially better diagnostics on failure than assertTrue ("<member> not found in <container>" vs. "False is not true"). assertTrue is rarely the best expectation (unless you're actually testing a function returning a boolean), as it flattens the feedback down to a binary outcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.