Python learning-unit testing

If you have heard of "Test-Driven Development" (TDD: Test-Driven Development), unit testing is no stranger.

Unit testing is 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, and expect the return value to be the same as the input;
  2. Enter a negative number, 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. Enter a non-numeric type, such as None, [], {}, expecting a TypeError to be thrown.

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

If the unit test passes, the function we tested can work normally. If the unit test fails, either the function has a bug or the test condition is incorrectly entered. In short, it needs to be fixed to make the unit test pass.

What's the point of passing the unit test? If we modify the code of the abs() function , 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 our modification. Inconsistent with the original behavior, either modify the code or modify the test .

The biggest advantage of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we designed. In the future modification, it can greatly guarantee that the behavior of the module is still correct.

Let's write a Dict class. The behavior of this class is the same as that of dict, but it can be accessed through attributes. It looks like this:

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

The code of mydict.py 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 starting with test are test methods. Methods not starting with test are not considered test methods and will not be executed during testing.

A test_xxx() method needs to be written 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 to throw a specified type of Error. For example, when accessing a non-existent key through d['empty'], the assertion will throw a KeyError:

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

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112570211