Python3 Basics: Unit Test __python

Source: Internet
Author: User

to write unit tests, we need to introduce Python's own unittest module.
When writing unit tests, we need to write a test class from unittest. TestCase inheritance.
The method that begins with test is a method of testing, and a method that does not begin with test is not considered a test method and is not executed when it is tested.
UnitTest. TestCase provides a number of built-in conditional judgments:

Self.assertequal (ABS (-1), 1) # assertion function returns the same result as 1

Another important assertion is that the assertion throws a keyerror when it expects to throw a specified type of error, such as accessing a nonexistent key via d[' empty ':

With Self.assertraises (keyerror):
    value = d[' Empty ']

And by D.empty access to nonexistent key, we expect to throw Attributeerror:

With Self.assertraises (attributeerror):
    value = D.empty
Run unit Tests

The simplest way to do this is to add in the unit test py file:

if __name__ = = ' __main__ ':
unittest.main ()

Then it's OK to run the test script normally.
Another approach is to run unit tests directly on the command line via parameter- m unittest , which is recommended because you can run many unit tests at once, and there are a number of tools that can automatically run these unit tests. Setup and teardown

You can write two special setUp () and teardown () methods in a unit test. The two methods are executed separately before and after each call to a test method .

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.