Python基础知识(九)—–错误异常处理及测试

756-周同学

发表文章数:47

热门标签

,
首页 » Python » 正文

一. 错误异常处理

1. 错误类型

  1. 语法错误
  2. 语义错误
  3. 逻辑错误

2. 异常处理

  1. t r y有可能出现异常的代码
  2. except异常类型
try:
    x = 5 / 0
    print(x)
except ZeroDivisionError as e:
    print('no zero',e)
except:
    print('other errors')
else:
   print('no error')     
lass Person:
    def __init__(self,name):
        self.name = name

p = Person('Peter')

try:
    print(p.age)
except AttributeError as e:
    print('error',e) 
  1. finally, 不论是否遇到异常都出执行
try:
    f = open('data.txt')
    f.read()
except:
    print('error')
finally:
    f.close()
  1. raise手动抛出异常
def method():
    raise NotImplementedError('the method is not implemented')

method()
  1. else: 未遭遇测试

2. 测试

  1. 单元测试
    (1) 对代码最基本单元(函数、方法)的测试
    (2)给予特定条件判断结果是否符合预期
    (3)相对整个程序的测试,单元测试简化了测试任务
    (4)unittest 模块
def get_formatted_name(first,last):
    full_name = '{} {}'.format(first,last)
    return full_name.title()

print(get_formatted_name('tom','lee'))

import unittest
from main 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()
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('master skill:')
        for skill in self.skills:
            print('-',skill)
            
c = Coder('Tom')
c.mastering_skill('Python')
c.mastering_skill('C')
c.show_skills()

#Test
import unittest
from coder import Coder

class CoderTestCase(unittest.TestCase):
    def test_skill_in(self):
        c = Coder('Tom')
        c.mastering_skill('Python')
        c.mastering_skill('MVC')

        self.assertIn('Python',c.skills)

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

#Test
import unittest
from coder import Coder

class CoderTestCase(unittest.TestCase):
    def setUp(self):
        self.c = Coder('Tom')
        self.c.skills = ['Python','.Net']

    def test_skill_in(self):
        c = Coder('Tom')

        self.assertIn('Python',self.c.skills)

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

def add(a,b):
    return a+b

class MyTest(unittest.TestCase):
    def test_add(self):
        self.assertEqual(8,add(5,3))

if __name__ == '__main__':
    unittest.main()
  1. 代码组织
    (1)断言:assertEqual (值,表达式)是否相等
    assertTrue (值,表达式)是否为真
    assertIn (值,表达式)是否包含
    assertAlmostEqual (值,表达式)是否约等于
    assertIs(), 是否为同引用
    assertIsNone(), 是否为空
    assertIsInstance(), 是否某类型实例
    assertGreater(), 是否大雨
import unittest

person = {'name':'Mike','age':28}
number = [1,2,3,4,6]
s='class'

class TestAssert(unittest.TestCase):
    def test_assert_method(self):
        self.assertEqual('mike',person.get('name'))
         self.assertTrue('class'in s)
         self.assertIn('class',s)
         self.assertAlmostEqual(1+2,3)
         self.assertIs(True+1,2)
        self.assertIsNone(person.get('None',None))
         self.assertIsInstance(s,str)
         self.assertGreater(7,number[0])

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

(2)装置:测试用例类继承自unittest.TestCase
test_ 定义功能测试函数名
setUp() 函数定义准备初始化代码
TearDown()执行函数清理

class Calculator:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def add(self):
        return self.x + self.y

    def substract(self):
        return self.x - self.y

if __name__ == '__main__':
    c = Calculator(5,3)
    print(c.add())

#Test
import unittest
from calculator import Calculator

class CalculatorTest(unittest.TestCase):
    def setUp(self):
        self.c = Calculator(5,3)

    def test_add(self):
        #c = Calculator(5,3)
        self.assertEqual(8,self.c.add())

    def test_substract(self):
        #c = Calculator(8,4)
        self.assertEqual(4,self.c.substract())

    def tearDown(self):
        del self.c

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

3. 数值与日期

  1. 数值
    (1)格式化
a=528
b=1243445.445
c=-1287.332
'数值:{}'.format(a)
'数值:528'
f'number:{a}'
'number:528'

f'number:{c:-f}'
'number:-1287.332000'
f'number:{b:,f}'
'number:1,243,445.445000'
f'number:{b:,.2f}'
'number:1,243,445.45'

x = 18
y = 23
'{:.2f}'.format(x/y)
'0.78'
'{:.2%}'.format(x/y)
'78.26%'

(2)小数位的处理

import math
math.trunc(123.987)
123
math.floor(123.987)
123
math.ceil(123.987)
124
math.ceil(123.01)
124
round(b,2) #真正的四舍五入
1243445.45
  1. 随机数
Ist = list(range(1,11))
Ist
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random
random.choice(Ist)
6
random.sample(Ist,3)
[2, 3, 6]
random.shuffle(Ist)
Ist
[7, 1, 3, 2, 8, 4, 5, 6, 10, 9]
random.randint(1,10) #随机整数
7
random.random() #随机浮点数
0.91211063771254
random.getrandbits(5)
21

3.日期时间
(1)datetime:date,time,datetime

import datetime
now = datetime.datetime.now()
now
datetime.datetime(2020, 3, 1, 14, 39, 55, 253768)
now.year
2020
now.second
55
t = datetime.datetime(1990,3,3,12,33,44)
t.year
1990

(2) 格式转换

s='2018-3-15'
...t = datetime.datetime.strptime(s,'%Y-%m-%d')
t
datetime.datetime(2018, 3, 15, 0, 0)
now = datetime.datetime.now()
txt = now.strftime('%Y/%m/%d')
txt
'2020/03/01'

(3)时间差处理 timedelta

d= datetime.datetime(2018,3,5,22,44)
birthdate = datetime.datetime(2016,5,2,19,44,33)
d - birthdate
datetime.timedelta(672, 10767)
diff = d - birthdate
diff.days
672
diff.seconds
10767
diff.total_seconds()
58071567.0
o = datetime.datetime(3028,8,8,20,8)
o + datetime.timedelta(days=100)
datetime.datetime(3028, 11, 16, 20, 8)
result = d + datetime.timedelta(days=-100)
result
datetime.datetime(2017, 11, 25, 22, 44)
d
datetime.datetime(2018, 3, 5, 22, 44)
d + datetime.timedelta(seconds=3000)
datetime.datetime(2018, 3, 5, 23, 34)
标签:

未经允许不得转载:作者:756-周同学, 转载或复制请以 超链接形式 并注明出处 拜师资源博客
原文地址:《Python基础知识(九)—–错误异常处理及测试》 发布于2020-03-02

分享到:
赞(0) 打赏

评论 抢沙发

评论前必须登录!

  注册



长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

Vieu3.3主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录