Python语言之异常处理与测试
目录
(一)异常处理
1.捕获所有异常
try: x = 5 / 0 except: print('程序有错误')
2.捕获特定异常
try: x = 5 / 0 except ZeroDivisionError as e: print('不能为0',e) except: print('其他错误') else: print('没有错误') finally: print('关闭资源')
3.手动抛出异常
def method(): raise NotImplementedError('该方法还未被实现')
(二)测试
使用Python自带的unittest模块
example 1:测试某个函数
import unittest from example import get_formatted_name class NameTestCase(unittest.TestCase): def test_title_name(self): formatted_name = get_formatted_name('tom','lee') self.assertEqual(formatted_name,'Tom Lee') if __name__ == '__main__': unittest.main()
example 2:测试某个类
class Coder: def __init__(self,name): self.name = name self.skills = [] def mastering_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 CoderTestCase(unittest.TestCase): def setUp(self): self.c = Coder('Tom') self.c.mastering_skill('Python') self.c.mastering_skill('Java') def test_skill_in(self): self.assertIn("Python",self.c.skills) def tearDown(self): print('销毁') if __name__ == '__main__': unittest.main()
常用的断言方法:
import unittest person ={'name':'Tom','age':30} numbers = [1,23,3,4,4,54] s = 'hello world python' class TestAssert(unittest.TestCase): def test_assert_method(self): self.assertEqual('Tom',person.get('name')) self.assertTrue('hello' in s) self.assertIn('hello',s) #self.assertEqual(3.3,1.1+2.2) self.assertAlmostEqual(3.3,1.1+2.2) #判断在内存中是否是同一个引用 self.assertIs(True+1,2) self.assertIsNone(None) #判断是否是某个类型的实例 self.assertIsInstance(numbers[0],int) #是否大于 self.assertGreater(5,4) if __name__ == '__main__': unittest.main()
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27