Assertion is the basics of testing.
Assertion in Python is pretty simple, you can assert any condition by
assert 1 + 1 == 2
It is great that
assert can stop your application/tests when something goes wrong. However, it is not good enough that the AssertionError does not expose more information. In above example, we received the error message only with file name and line number, you have to start debugger to discover more.
An improved solution is always appending message in your assertion.
"nothin is impossible."s =
Well, it fixed the problem, but it not elegant. If you are a QA engineer, you have to do a lot of assertions in thousands of test cases. With above solution, I would choose to die :-|
You might know about test frameworks, how do they do assertion? Yes, using test framework assertion is a nice alternation.
If you are running tests with py.test, you can keep everything unchanged in your code, the failure message will tell you what is going on in failed assertion.
Python unittest module provides assertion feature in itself, it recommends
self.assertXXX() methods, but not
assert XXX statements.
I like ptest very much, its assertion feature is more readable and smart. Thanks its author Karl :-)
from ptest.decorator import *
It is not only you and me are frustrating on python assertion, so people created packages to replace default assertion. I strongly recommend you should have a try for assertpy package, which is high rating and powerful.
pip install assertpy
from assertpy import assert_that
From its github home page you will see it supports assertion in most test scenarios.
The assertion message is really helpful, they looks like:
Expected <foo> to be of length <4>, but was <3>.
Before I found this package I am thinking about writing common assertion package for Labs, but now, I don’t think I should spend time to invent the wheel again.
Assertion is pretty important to a system, it can increase stability and save your time in debugging.
Replacing all built-in assertion to 3rd party assertion in your code is not a good idea, because IDE like PyCharm knows nothing about that, so it will not provide auto-completion for those assertion.
So my suggestion is, using more powerful assert functions in scenarios that you really want to verify something, keeping built-in assertion where you might fall in a pitfall, and with essential message. Keep It Simple and Stupid.