English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Why Python Assert Is Not Satisfactory63;
Assertions in Python are very simple to use; you can follow an assertion with any judgment condition, and an exception will be raised if the assertion fails.
>>> assert 1 + 1 == 2 >>> assert isinstance('Hello', str) >>> assert isinstance('Hello', int) Traceback (most recent call last): File '<input>', line 1, in <module> AssertionError
In fact, assert looks good, but it's not very pleasant to use. For example, someone tells you that the program is wrong, but doesn't tell you where it's wrong. Often, such assert is better not to write, and if it's written, I want to curse. It's better to throw an exception more directly.
Improvement Proposal #1
A slightly improved solution is to also put the necessary information after the assert statement, like this.
>>> s = "nothin is impossible." >>> key = "nothing" >>> assert key in s, 'Key: '{}' is not in Target: '{}''.format(key, s) Traceback (most recent call last): File '<input>', line 1, in <module> AssertionError: Key: 'nothing' is not in Target: 'nothin is impossible.'
It looks okay, but it's actually quite painful to write. Suppose you are a tester with thousands of test cases that need to make assertions and validations. I believe that facing the above approach, you must have a thousand horses galloping through your mind.
Improvement Proposal #2
Whether you are engaged in testing or development, you must have heard a lot about testing frameworks. Can you guess what I'm going to say? Yes, without the assertion mechanism in the testing framework, aren't you?洒.
py.test
py.test is a lightweight testing framework, so it doesn't have its own assertion system at all. However, it enhances the built-in assertions in Python, and if an assertion fails, the framework itself will try to provide as much information as possible about the cause of the failure. This means that when implementing tests with py.test, you don't have to change a single line of code.
import pytest def test_case(): expected = "Hello" actual = "hello" assert expected == actual if __name__ == '__main__': pytest.main() """ ================================== FAILURES =================================== __test_case__ def test_case(): expected = "Hello" actual = "hello" > assert expected == actual E assert 'Hello' == 'hello' E - Hello E ? ^ E + hello E ? ^ assertion_in_python.py:7: AssertionError ========================== 1 failed in 0.05 seconds =========================== """
unittest
Python's built-in unittest unit testing framework has its own assertion methods self.assertXXX(), and it is not recommended to use assert XXX statements.
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FoO') if __name__ == '__main__': unittest.main() """ Failure Expected :'FOO' Actual :'FoO' Traceback (most recent call last): File "assertion_in_python.py", line 6, in test_upper self.assertEqual('foo'.upper(), 'FoO') AssertionError: 'FOO' != 'FoO' """
ptest
I really like ptest, thank you Karl the great god for writing such a test framework. The assertions in ptest are very readable, and you can easily complete various assertion statements with the intelligent hints of the IDE.
from ptest.decorator import * from ptest.assertion import * @TestClass() class TestCases: @Test() def test1(self): actual = 'foo' expected = 'bar' assert_that(expected).is_equal_to(actual) """ Start to run following 1 tests: ------------------------------ ... [demo.assertion_in_python.TestCases.test1@Test] Failed with the following message: ... AssertionError: Unexpectedly that the str <bar> is not equal to str <foo>. """
Improvement Proposal #3
It's not just that you and I are dissatisfied with assertions in Python, so everyone is competing to invent their own assert package. Here I strongly recommend the assertpy package, which is extremely powerful and highly praised.
pip install assertpy
See examples:
from assertpy import assert_that def test_something(): assert_that(1 + 2).is_equal_to(3) assert_that('foobar')\ .is_length(6)\ .starts_with('foo')\ .ends_with('bar') assert_that(['a', 'b', 'c'])\ .contains('a')\ .does_not_contain('x')
You will find on its homepage documentation that it supports almost all test scenarios you can think of, including but not limited to the following list.
Strings
Numbers
Lists
Tuples
Dicts
Sets
Booleans
Dates
Files
Objects
And its assertion information is concise and clear, neither more nor less.
Expected <foo> to be of length <4>, but was <3>. Expected <foo> to be empty string, but was not. Expected <False>, but was not. Expected <foo> to contain only digits, but did not. Expected <123> to contain only alphabetic chars, but did not. Expected <foo> to contain only uppercase chars, but did not. Expected <FOO> to contain only lowercase characters, but did not. Expected <foo> to be equal to <bar>, but was not. Expected <foo> to be not equal to <foo>, but was. Expected <foo> to be case-Expected to be case insensitive equal to <BAR>, but was not.
Before discovering assertpy, I also wanted to write a similar package, as general as possible. But now, why do I have to reinvent the wheel? It's completely unnecessary!
Summary
Assertions play a very important role in software systems, and well-written assertions can make your system more stable. In fact, the default assertion statement in Python also has another function. If you write an assertion related to type, the IDE will treat this object as this type, and then the intelligent hint is like a godsend.
Whether to replace the built-in assertion statements with third-party assertions that are more readable and powerful depends entirely on the actual situation. For example, if you really need to verify something and care about the verification results, then you must not use simple assert; if you are just worried that there may be a pit or let the IDE recognize an object, using the built-in assert is simple and convenient.
So, project experience is quite important. That's all for this article. I hope the content of this article can be helpful to everyone's learning or work, and if you have any questions, you can leave a message for communication.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report infringement, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)