Why not using Python Assert
Assertion in Python is pretty simple, you can assert any condition by assert
statement.
|
|
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.
Improved Solution #1
An improved solution is always appending message in your assertion.
|
|
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 😐
Improved Solution #2
You might know about test frameworks, how do they do assertion? Yes, using test framework assertion is a nice alternation.
py.test
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.
|
|
unittest
Python unittest module provides assertion feature in itself, it recommends self.assertXXX()
methods, but not assert XXX
statements.
|
|
ptest
I like ptest very much, its assertion feature is more readable and smart. Thanks its author Karl 🙂
|
|
Improved Solution #3
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.
|
|
Example:
|
|
From its github home page you will see it supports assertion in most test scenarios.
- Strings
- Numbers
- Lists
- Tuples
- Dicts
- Sets
- Booleans
- Dates
- Files
- Objects
The assertion message is really helpful, they looks like:
|
|
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.
Summary
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.
近期评论