addicted-to-coding
addicted-to-coding

Reputation: 295

Python: can unittest display expected and actual values?

If I have an assert in a unittest.TestCase as shown below:

self.assertTrue( person.age == 42, "age incorrect")

When it fails, it gives the "age incorrect" message. What I would also like to see is the expected and actual values. What's the best way to go about doing this? Is it something unittest can do?

EDIT I would like to see something like:

"age incorrect: expected value 42 actual value 39"

Upvotes: 24

Views: 16074

Answers (3)

Noel Golding
Noel Golding

Reputation: 300

you can set the longMessage attribute to True

expected_age = 42
actual_age = person.age # 39
self.longMessage = True
self.assertEqual(expected_age, actual_age, 'age incorrect')

you would get something like:

AssertionError: 42 != 39 : age incorrect

reference: https://docs.python.org/2/library/unittest.html#unittest.TestCase.longMessage

Upvotes: 30

Gregg Lind
Gregg Lind

Reputation: 21218

see: assertEqual

self.assertEqual(person.age, 42, 'age incorrect')

or with the default message (to answer the comment):

self.assertEqual(person.age, 42)

Upvotes: 5

Bakuriu
Bakuriu

Reputation: 101929

You should use a workaround to this problem, like this:

self.assertEqual(person.age, 42, 'age incorrect: expected value {0} actual value {1}'.format(42, person.age))

But i think not providing the "msg" parameter is the best option, since it generates the text:

first != equal

Most(*) tools for running tests also shows directly which line failed, thus you should be able to understand which test failed and why without using an extra message.

(*) read "all".

Upvotes: 13

Related Questions