Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 852
addicted-to-coding Avatar asked Jan 08 '11 15:01

addicted-to-coding


3 Answers

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

like image 195
Noel Golding Avatar answered Oct 19 '22 22:10

Noel Golding


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".

like image 34
Bakuriu Avatar answered Oct 19 '22 20:10

Bakuriu


see: assertEqual

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

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

self.assertEqual(person.age, 42)
like image 27
Gregg Lind Avatar answered Oct 19 '22 20:10

Gregg Lind