Home>Article>Backend Development> What is python unit testing? (detailed examples)

What is python unit testing? (detailed examples)

乌拉乌拉~
乌拉乌拉~ Original
2018-08-23 13:38:14 2518browse

In the following article, we will learn about what unit testing is in python. Learn about python unit testing and what role python unit testing can play in python programming.

Unit testing

Unit testing is used to test the correctness of a module, a function or a class Work.

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, and expect the return value to be the same as the input;

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

3. Enter 0, expect to return 0;

4. If you enter a non-numeric type, such as None, [], {}, expect a TypeError to be thrown.

Put the above test cases into a test module, which is a complete unit test.

If the unit test passes, it means that the function we tested can work normally. If the unit test fails, either there is a bug in the function, or the test conditions are entered incorrectly. In short, it needs to be fixed to make the unit test pass.

What is the significance of passing the unit test? If we make modifications to the abs() function code, we only need to run the unit test again. If it passes, it means that our modification will not affect the original behavior of the abs() function. If the test fails, it means that our modification If it is inconsistent with the original behavior, either modify the code or modify the test.

The biggest benefit of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we designed. When modified in the future, it can be greatly guaranteed that the module behavior will still be correct.

Let’s write a Dict class. This class behaves the same as dict, but can be accessed through attributes. It is used like the following:

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

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 the unittest module that comes with Python and write mydict_test.py as follows:

import unittest from mydict import Dict class 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 that inherits from unittest.TestCase .

Methods that begin with test are test methods. Methods that do not begin with test are not considered test methods and will not be executed during testing.

You need to write a test_xxx() method for each type of test. Since unittest.TestCase provides many built-in conditional judgments, we only need to call these methods to assert whether the output is what we expect. The most commonly used assertion is assertEqual():

self.assertEqual(abs(-1), 1) # 断言函数返回的结果与1相等

Another important assertion is to expect an Error of a specified type to be thrown. For example, when accessing a non-existent key through d['empty'], the assertion will throw KeyError:

with self.assertRaises(KeyError): value = d['empty']

When accessing a non-existent key through d.empty, we expect an AttributeError to be thrown:

with self.assertRaises(AttributeError): value = d.empty

Run unit test

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

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

这样就可以把mydict_test.py当做正常的python脚本运行:

$ python mydict_test.py

另一种方法是在命令行通过参数-m unittest直接运行单元测试:

$ python -m unittest mydict_test ..... ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK

这是推荐的做法,因为这样可以一次批量运行很多单元测试,并且,有很多工具可以自动来运行这些单元测试。

以上就是本篇文章所讲述的所有内容,这篇文章主要介绍了python单元测试的相关知识,希望你能借助资料从而理解上述所说的内容。希望我在这片文章所讲述的内容能够对你有所帮助,让你学习python更加轻松。

更多相关知识,请访问php中文网Python教程栏目。

The above is the detailed content of What is python unit testing? (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn