python错误异常处理,测试模块以及常用断言方法

python错误异常处理,测试模块以及常用断言方法_第1张图片
错误判断,try

try:
    x = 5 / 0
    print(x)
except ZeroDivisionError as e:
    print('不能除零',e)
except:
    print('其他错误')
else:
    print('没有异常')

#测试完有无异常,文件或数据库需要关闭,用finally:(不管有无异常都要执行)
f = open('data.txt')
try:
    f.read()
except:
    print('文件操作遇到错误!')
finally:
    f.close()

测试
建立类模块

class Coder:
    def __init__(self,name):
        self.name = name
        self.skills = []

    def get_skill(self,skill):
        self.skills.append(skill)

    def show_skills(self):
        print('掌握技能')
        for skill in self.skills:
            print('-',skill)


建立测试模块,测试类中函数功能

import unittest
from coder import Coder

class SkillTextCase(unittest.TestCase):
    #setUp():初始化函数,但测试实例很多时,可以使用,不用去测试函数中创建值
    def setUp(self):
         self.c = Coder('Tom')
         self.c.skills = ['python','DQN']

    def SkillTextIn(self):
#       skill_text = Coder.get_skill('python')
#       skill_text = Coder.get_skill('DQN')
        self.assertIn('python',self.c.skills)#断言

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

常用assert断言方法

import unittest

person = {'name':'mateng','age':25}
nember = [1,2,3,4,5,6]
s = 'hahahahaha'

class TestAssert(unittest.TestCase):
    def test_assert_method(self):
        #self.assertEqual('mateng',person.get('name'))
        #self.assertTrue('haha' in s)
        #self.assertIn(3,nember)
        #self.assertAlmostEqual(3.3,1.1+2.2)
        #self.assertIs(True + 1, 2)
        #self.assertIsNone(person.get('Sex',None))
        #self.assertIsInstance(s,str)
        self.assertGreater(nember[5],nember[3])
if __name__ == '__main__':
    unittest.main()

你可能感兴趣的:(python错误异常处理,测试模块以及常用断言方法)