Why "python" python Assert is not as satisfactory as __python

Source: Internet
Author: User
Tags assert readable

Assertions in Python are simple to use, and you can keep up with arbitrary criteria after an assert, and throw an exception 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

The assert looks good, but it's not fun to use. Just like someone tells you that the program is wrong, but don't tell me what's wrong. A lot of times such an assert is better than not to write, wrote I would like to dozens. It's more enjoyable to throw an exception directly. Improvement Programme #1

A slightly better way to lose is to put the necessary information behind the Assert statement, for example.

>>> s = "nothin is impossible."
>>> key = "Nothing"
>>> assert key in S, "key: ' {} ' isn't in Target: ' {} '". Format (key, s)

Trace Back (most recent called last):
  File "<input>", line 1, in <module>
assertionerror:key: ' Nothing ' is no T in Target: ' Nothin is impossible. '

It looks fine, but it's actually a pain in the egg. If you are a test Wang, there are tens of thousands of test cases need to do the assertion of verification, I believe you face the above practice, there must be thousands that horse Pentium. Improvement Programme #2

Whether you are a test or a development, you must have heard a lot of test framework. You guessed what I was going to say. Yes, without testing the mechanism of the assertion in the framework, you are not sprinkled. py.test

Py.test is a lightweight test framework, so it doesn't write its own assertion system, but it reinforces Python's own assertions, and if the assertion fails, the framework itself provides as many reasons as possible for the assertion to fail. Then it means that you can use Py.test to implement the test, you do not have to change a 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 self-contained unittest unit test framework has its own assertion method Self.assertxxx (), and it is not recommended to use the Assert XXX statement.

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 like ptest very much, thanks to Karl Great God wrote such a test framework. Assertions in Ptest are very readable and smart tips are also handy for you to easily complete various assertion statements through the IDE.

From ptest.decorator Import *
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 following message:
....
assertionerror:unexpectedly that the Str <bar> isn't equal to Str <foo>. ""
Improvement Programme #3

Not only are you and I not satisfied with the assertions in Python, so everyone is scrambling to invent their own assert packs. Here I strongly recommend assertpy this package, which is unusually powerful and highly acclaimed.

Pip Install Assertpy

See Example:

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 ')

From its GitHub homepage document you will find that it supports almost any test scenario 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, not many.

Expected <foo> to is of length <4>, but was <3>.
Expected <foo> to is empty string, but is not.
Expected <false> but is 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 chars, but did not.
Expected <foo> to is equal to <bar>, but is not.
Expected <foo> to is not equal to
<foo> Expected <foo> to is case-insensitive equal to <bar>, but is not.

I also wanted to write a similar package before I found assertpy, as generic as possible. But now, I have to reinvent the wheel for Mao. No need at all. Summary

Assertions have a very important role to play in a software system, and writing well can make your system more stable, and it allows you to have more time to actually face objects than to debug your code.

The default assertion statement in Python actually has one effect, and if you write a type-related assertion, the IDE treats the object as this type, and the smart hint is like God's help.

It is entirely up to the facts to replace the built-in assertion statement with a more readable and powerful third-party assertion. For example, if you really need to validate something and are concerned about the validation results, you must not use a simple assert; If you're just worried that a point might have a hole or that the IDE knows an object, it's easy and easy to use the built-in assert.

So, the project experience is quite important.

Article from: https://segmentfault.com/a/1190000007248161

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.