What is a python unit test? (example)

Source: Internet
Author: User
Tags abs python script

Unit Test

Unit tests are used to test the correctness of a module, a function, or a class.

For example, for the function abs (), we can write the following test cases:

1. Enter a positive number, such as 1, 1.2, 0.99, expecting the return value to be the same as the input;

2. Enter negative numbers, such as-1,-1.2,-0.99, expecting the return value to be the opposite of the input;

3. Enter 0, expect to return 0;

4. Enter non-numeric types, such as none, [], {}, and expect to throw typeerror.

Putting the above test cases into a test module is a complete unit test.

If the unit test passes, it means that the function that we are testing is working correctly. If the unit test does not pass, either the function has a bug, or the test condition is entered incorrectly, in short, a repair is required to enable the unit test to pass.

What does it mean after unit tests are passed? If we make modifications to the ABS () function code, we just need to run the unit test again, and if it does, our changes will not affect the original behavior of the ABS () function, if the test does not pass, it means that our changes are inconsistent with the original behavior, either modify the code or modify the test.

The greatest benefit of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we have designed. In the future, it can be greatly ensured that the module behavior is still correct.

Let's write a dict class that behaves the same as dict, but can be accessed through attributes, as follows:

>>> d = Dict (A=1, b=2) >>> d[' a ']1>>> d.a1

The mydict.py code is as follows:

Class Dict (Dict):    def __init__ (self, **kw):        super (). __init__ (**kw)    def __getattr__ (self, key):        try:            return Self[key]        except Keyerror:            raise Attributeerror (r "' Dict ' object has no attribute '%s '"% key)    def __setattr__ (self, Key, value):        Self[key] = value

In order to write unit tests, we need to introduce Python's own unittest module and write mydict_test.py as follows:

Import unittestfrom mydict import Dictclass testdict (unittest. TestCase):    def test_init (self):        d = Dict (a=1, b= ' test ')        self.assertequal (D.A, 1)        self.assertequal ( D.B, ' test ')        self.asserttrue (Isinstance (d, Dict))    def test_key (self):        d = dict ()        d[' key ' = ' value '        self.assertequal (D.key, ' value ')    def test_attr (self):        d = Dict ()        D.key = ' value '        Self.asserttrue (' key ' in D)        self.assertequal ("d[' key '), ' value ')    def test_keyerror (self):        d = Dict () With        self.assertraises (keyerror):            value = d[' empty ',    def test_attrerror (self):        d = Dict ()        With Self.assertraises (attributeerror):            value = D.empty

When writing unit tests, we need to write a test class from UnitTest. TestCase inheritance.

The method that begins with test is the method of testing, and the method that does not begin with test is not considered a test method and is not executed when the test is performed.

You need to write a test_xxx () method for each type of test. Due to unittest. TestCase provides a lot of built-in conditional judgments, and we just need to call these methods to assert that the output is what we expect. The most common assertion is assertequal ():

Self.assertequal (ABS (-1), 1) # The Assertion function returns a result equal to 1

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

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

When accessing a nonexistent key through d.empty, we expect to throw Attributeerror:

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

run unit test

Once the unit tests have been written, we can run the unit tests. The simplest way to run is to add two lines of code at the end of the mydict_test.py:

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

This allows the mydict_test.py to be run as a normal Python script:

$ python mydict_test.py

Another way is to run unit tests directly at the command line with the parameter-M unittest:

$ python-m unittest mydict_test ...----------------------------------------------------------------------Ran 5 Tests in 0.000sOK

This is recommended because it allows you to run many unit tests in batches at once, and there are many tools that can run these unit tests automatically.

Related Article

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.