Why is Python Assert so disappointing?

Source: Internet
Author: User

The assertions in Python are very simple to use, and you can keep an arbitrary judging condition behind the assert and throw an exception if the assertion fails.

assert assert isinstance ('Hello', str)assert isinstance (' Hello ' , int) Traceback (most recent):  '<input>' in < module>Assertionerror

assertIt actually looks good, but it's not cool to use. Just like someone tells you that the program is wrong, but don't tell me what's wrong. Many times this is assert better than not to write, write I want to dozens. Throwing an exception directly is a bit more enjoyable.

Improved programme #1

A slightly improved throw-away solution is to put the necessary information assert behind the statement, such as this.

>>> s ="Nothin is impossible.">>> key =" Nothing">>>assertKeyinchS"Key: ' {} ' isn't in Target: ' {} '". Format (key, s) Traceback (most recent call last): File"<input>", Line 1,inch<module>Assertionerror:key:' Nothing'  is  not inchTarget:'Nothin is impossible.'

It looks OK, but it's actually very painful to write. If you are a test Wang, there are thousands of test cases need to do the assertion to do the verification, I believe you face the above practice, there must be thousands that horse in the heart.

Improved programme #2

Whether you're testing or developing, you've probably heard a lot of testing frameworks. You guessed what I was going to say? Yes, you do not have to test the assertion mechanism 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 at all, but it reinforces the assertion that Python comes with, and if the assertion fails, the framework itself provides as much of the reason for the assertion failure as possible. Then it means that you don't have to change your line of code to implement the test with Py.test.

Importpytestdeftest_case (): Expected="Hello"actual="Hello"    assertexpected = =actualif __name__=='__main__': Pytest.main ()"""================================== Failures ===================================______________________________ ____ Test_case __________________________________ def test_case (): expected = "Hello" actual = "Hello"       ; Assert expected = = Actuale assert ' hello ' = = ' Hello ' E-helloe? ^e + Helloe? ^assertion_in_python.py:7: assertionerror========================== 1 failed in 0.05 seconds ======================== ===""""

UnitTest

Python's own UnitTest unit test framework has its own assertion method self.assertXXX() , and the use of statements is not recommended assert XXX .

ImportUnitTestclassTeststringmethods (unittest. TestCase):defTest_upper (self): self.assertequal ('Foo'. Upper (),'FoO')if __name__=='__main__': Unittest.main ()"""failureexpected: ' foo ' Actual: ' foo ' Traceback (most recent call last): File "assertion_in_python.py", line 6, in TES T_upper self.assertequal (' foo '. Upper (), ' foo ') assertionerror: ' foo '! = ' foo '"""

Ptest

I like ptest very much and thank Karl Great God for writing such a test framework. Assertions in Ptest are very readable, and smart hints are handy for you to easily complete various assertion statements through the IDE.

 fromPtest.decoratorImport* fromPtest.assertionImport*@TestClass ()classtestcases: @Test ()deftest1 (self): actual='Foo'expected='Bar'Assert_that (Expected). Is_equal_to (Actual)"""Start to run following 1 tests:------------------------------... [[email protected]] Failed with following message: ... assertionerror:unexpectedly that the Str <bar> isn't equal to Str <foo>."""

Improved programme #3

It's not just you and me that are not satisfied with the assertions in Python, so everyone is scrambling to invent their own assert package. Here I highly recommend assertpy this package, it is unusually strong and rave.

Pip Install Assertpy

See Example:

 fromAssertpyImportAssert_thatdeftest_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 home page document you will find 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 and clear, not many.

Expected <foo> to is of length <4>, but is <3>. Expected<foo> to is empty string, but is not. Expected<false> not. Expected<foo> to contain-digits, but did not. Expected<123> to contain-alphabetic chars, but did not. Expected<foo> to contain-uppercase chars, but did not. Expected<FOO> to contain-lowercase chars, but did not. Expected<foo> to being equal to &LT;BAR&GT; not. Expected<foo> to be notEqual to <foo>, but was. Expected<foo> to is case-insensitive equal to <bar> not.

I also wanted to write a similar package before I found assertpy, as common as possible. But now, I'm going to reinvent the wheel for Mao? No need at all!

Summarize

Assertions have a very important role in software systems, writing well can make your system more stable, but also allows you to have more real time to face objects, rather than debugging code.

The default assertion statement in Python actually has a role, and if you write a type-related assertion, the IDE treats the object as this type, and the smart tip acts as a divine aid.

Instead of replacing built-in assertion statements with more readable, more powerful third-party assertions, it depends entirely on the situation. For example, if you really need to verify something and care about the results, you must not use simple assert, and if you are just concerned about a point where there may be a pit or an IDE knowing an object, it is easy and convenient to use built-in assert.

So, the project experience is quite important.

Why is Python Assert so disappointing?

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.