1、基本用法:用于检查代码的运行结果是否正确
    注意:方法必须用test开头

    1. def calc(express):
    2. try:
    3. ret=eval(express)
    4. except:
    5. return
    6. else:
    7. return ret
    8. import unittest
    9. class Test_calc(unittest.TestCase):
    10. def test_add(self):
    11. express="1+1"
    12. ret=calc(express)
    13. self.assertEqual(2,ret,"%s测试不通过"%express)
    14. def test_sub(self):
    15. express="1-1"
    16. ret=calc(express)
    17. self.assertEqual(0,ret,"%s测试不通过"%express)
    18. def test_multi(self):
    19. express="1*3"
    20. ret=calc(express)
    21. self.assertEqual(2,ret,"%s测试不通过"%express)
    22. def test_divi(self):
    23. express="1/1"
    24. ret=calc(express)
    25. self.assertEqual(1,ret,"%s测试不通过"%express)
    26. def test_type(self):
    27. express = "1+1"
    28. ret = calc(express)
    29. self.assertIsInstance(ret,str,"类型不一致")
    30. if __name__ == '__main__':
    31. unittest.main()

    结果:
    image.png