[python learning] python assertion assert-30

What is an assertion?

An assertion is the comparison of the world result with the expected result. A test that meets the expectations is a pass, and a test that does not meet the expectations is a fail. The assert (assertion) in python is used to judge an expression and trigger an exception when the expression condition is false

assert  表达式 , 描述

The expression is our expected result. When the result of the expression is False, an AssertionError exception will be thrown. If there is no exception catcher, the program will directly end the operation when it encounters an exception. Otherwise, if the expression evaluates to True, the program continues down.

When do we use assertions?

Assertions need to be used with caution, especially when writing test cases or programs, because when we run the program, if the assertion fails, the program will end without exception capture, causing the subsequent code to fail to execute.

Assertions are generally used in defensive programming, when checking program logic at runtime, checking conventions, program constants, and checking documentation. There is no need to add assertions to code that never fails.

Common formats:

assert 1==1
from random import randint

def random_num():
    return randint(1,10)

def test_1():
    assert random_num() == 2

Common basic assertion methods:

import unittest
import random
# 定义测试类
c=random.randint(10,100)
d=random.randint(10,100)
class TestDemo(unittest.TestCase):
    def test_a(self,a=c,b=d):
        try:
            self.assertEqual(a,b)
            print("{0}等于{1},a的值:{0},b的值:{1}".format(a,b))
        except:
            print("{0}不等于{1},a的值:{0},b的值:{1}".format(a,b))
            raise
    def test_b(self,a=c,b=d):
        try:
            self.assertNotAlmostEqual(a,b)
            print("{0}不等于{1},a的值:{0},b的值:{1}".format(a,b))
        except:
            print("{0}等于{1},a的值:{0},b的值:{1}".format(a,b))
            raise

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

 

Guess you like

Origin blog.csdn.net/admins_/article/details/122401960