文章目录

  • Python基础知识(八)
  • 一、异常处理及测试
  • (一)错误类型
  • (二)异常处理
  • 二、简单代码测试
  • (一)unittest单元测试的包:full_name.title():将单词的第一个字母变成大写输出。
  • (二)get_formatted_name
  • 三、测试
  • (一)测试级别
  • (二)单元测试基本介绍
  • (三)单元测试常用的断言方法
  • 1、通过assertEqual(值,表达式)断言是否相等。
  • 2、assertTrue()是否为真
  • 3、assertIn()是否包含
  • 4、assertAlmostEqual()是否约等于
  • 5、assertIs()判断是否为同一引用
  • 6、assertIsNone()判断是否为空
  • 6、assertIsInstance()判断是否为某类型实例
  • 7、assertIsGreater()判断是否大于
  • (四)测试案例的编写
  • 四、数值与日期
  • (一)数值
  • 1、数值的格式化
  • 2、小数位的处理
  • 3、随机数
  • (二)日期
  • 1、datetime:year 、month、day
  • 2、格式转换
  • (三)Python的时间差处理:timedelta


Python基础知识(八)

一、异常处理及测试

(一)错误类型

语法错误:出现SyntaxError是代码拼写有问题
           语义错误:被除数为0
           逻辑错误:代码没有错误,但是结果不是我们所需要的

(二)异常处理

捕获异常代码:

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

运行结果:

Render配置python python中render_Python


try:有可能出现异常

except 异常类型 as 实例:捕获特定异常

finally:不论是否遇到异常均会执行

else:未遇到异常时

raise:手动抛出异常

>>">class Person:
    def __init__(self,name):
        self.name = name

p = Person('Peter')

try:
    print(p.age)
except AttributeError  as  e:
    print('遇到属性异常',e)

运行结果:

Render配置python python中render_Python_02

二、简单代码测试

(一)unittest单元测试的包:full_name.title():将单词的第一个字母变成大写输出。

>>">def get_formatted_name(first,last):
    full_name = "{} {}".format(first,last)
    return full_name.title()

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

运行结果:

Render配置python python中render_Python_03

(二)get_formatted_name

在main.py中

>>">def get_formatted_name(first,last):
    full_name = "{} {}".format(first,last)
    return full_name.title()


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

在test_name_fuction.py中

>>">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")

运行结果:
Launching unittests with arguments python -m unittest E:/mypython03/test_name_function.py in E:\mypython03

Tom Lee

Ran 1 test in 0.002s

OK

在coder.py中

>>">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)

c = Coder('Tom')
c.mastering_skill('Python')
c.mastering_skill('c#')
c.show_skills()

在test_coder.py中

>>">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('ASP.NET MVC')

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


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

运行结果:

Render配置python python中render_Render配置python_04

三、测试

(一)测试级别

单元测试
     集成测试
     系统测试
     验收测试
     回归测试

(二)单元测试基本介绍

对代码最基本单元(函数、方法)的测试
给予特定条件判断结果是否符合预期
相对整个程序的测试,单元测试简化了测试任务
unittest模块

(三)单元测试常用的断言方法

1、通过assertEqual(值,表达式)断言是否相等。
>>">import unittest



__author__ = "Eason"
__copyright__ = "Copyright  2013-2017,codeclassroom.com"


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()

运行结果:

Render配置python python中render_Render配置python_05

>>">import unittest



__author__ = "Eason"
__copyright__ = "Copyright  2013-2017,codeclassroom.com"


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


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


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

运行结果:

Render配置python python中render_Python_06


测试减法

>>">import unittest



__author__ = "Eason"
__copyright__ = "Copyright  2013-2017,codeclassroom.com"


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

def subtract(a,b):
    return a -b


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

    def test_subtract(self):
        self.assertEqual(2,subtract(5,3))


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

运行结果:

Render配置python python中render_python_07

>>">
import unittest


__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


person = {'name':'Mike','age':20}
numbers = [1,3,2,88,7,44]
s = '优品课堂 codeclassroom.com'



class TestAssert(unittest.TestCase):
    def test_assert_method(self):
        self.assertEqual('Mike',person.get('name'))


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

运行结果:

Render配置python python中render_python基础知识(八)_08

2、assertTrue()是否为真
>>">
import unittest


__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


person = {'name':'Mike','age':20}
numbers = [1,3,2,88,7,44]
s = '优品课堂 codeclassroom.com'



class TestAssert(unittest.TestCase):
    def test_assert_method(self):
        # self.assertEqual('Mike',person.get('name'))
         self.assertTrue('优品课堂' in s)



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

运行结果:

Render配置python python中render_Python_09

3、assertIn()是否包含
>>">
import unittest


__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


person = {'name':'Mike','age':20}
numbers = [1,3,2,88,7,44]
s = '优品课堂 codeclassroom.com'



class TestAssert(unittest.TestCase):
    def test_assert_method(self):
        # self.assertEqual('Mike',person.get('name'))
        # self.assertTrue('优品课堂' in s)
        self.assertIn('优品课堂',s)


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

运行结果:

Render配置python python中render_Python_10

4、assertAlmostEqual()是否约等于
self.assertAlmostEqual(3.3,1.1 + 2.2)

运行结果:

Render配置python python中render_python_11

5、assertIs()判断是否为同一引用
self.assertIs(True + 1,2)

运行结果:

Render配置python python中render_Render配置python_12

6、assertIsNone()判断是否为空
self.assertIsNone(person.get('None',None))

运行结果

Render配置python python中render_Python_13

6、assertIsInstance()判断是否为某类型实例
self.assertIsInstance(numbers[0],int)
7、assertIsGreater()判断是否大于
self.assertGreater(7,numbers[0])

(四)测试案例的编写

在mypython01项目中
calculator.py文件

>>">

__author__ = 'Eason'
__copyright__ = 'Copyright 2013-2017,codeclassroom.com'


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

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

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


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

创建dictory名:test然后创建calculator_test.py文件

>>">import  unittest
from calculator import Calculator

__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


class CalculatorTest(unittest.TestCase):
    def test_add(self):
        c = Calculator(5,3)
        self.assertEqual(8,c.add())

    def test_subtracty(self):
        c = Calculator(8,4)
        self.assertEqual(4,c.subtract())

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

运行结果:

Render配置python python中render_Python_14


默认自定义的测试用下划线开头,可以将函数中相同的成员放在准备工作setUp()中。

>>">import  unittest
from calculator import Calculator

__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


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_subtracty(self):
        # c = Calculator(8,4)
        self.assertEqual(2,self.c.subtract())

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

运行结果:

Render配置python python中render_python_15


tearDown()用来做一些清理工作

>>">import  unittest
from calculator import Calculator

__author__ = "Eason"
__copyright__ = "Copyright 2013-2017,codeclassroom.com"


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_subtracty(self):
       # c = Calculator(8,4)
       self.assertEqual(2,self.c.subtract())

   def tearDown(self):
       del self.c


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

运行结果:

Render配置python python中render_单元测试_16

四、数值与日期

(一)数值

1、数值的格式化
>>">>>>a = 520
>>>b =1234567890.123456
>>>c = -123456.654321
>>>type(a)
<class 'int'>
>>>type(b)
<class 'float'>
>>>type(c)
<class 'float'>
>>>'数值:{}'.format(a)
'数值:520'
>>>'数值:{}'.format(b)
'数值:1234567890.123456'
>>>f'数值:{a}'
'数值:520'
>>>f'数值:{b}'
'数值:1234567890.123456'
>>>'数值:{}'.format(a)
'数值:520'
>>>'数值:{:f}'.format(a)
'数值:520.000000'
>>>f'数值:{a:f}'
'数值:520.000000'
>>>f'数值:{a:+f}'
'数值:+520.000000'
>>>f'数值:{a:-f}'
'数值:520.000000'
>>>f'数值:{c:-f}'
'数值:-123456.654321'
>>>f'数值:{b:f}'
'数值:1234567890.123456'
>>>f'数值:{b:,f}'
'数值:1,234,567,890.123456'
2、小数位的处理
>>">>>>f'数值:{b:,.3f}'
'数值:1,234,567,890.123'
>>>f'数值:{b:,.2f}'
'数值:1,234,567,890.12'
>>>f'数值:{b:,.4f}'
'数值:1,234,567,890.1235'
>>>x = 18
>>>y = 23
>>>'{:.2f}.format(x/y)'
'{:.2f}.format(x/y)'
>>>'{:.2f}'.format(x/y)
'0.78'
>>>'{:.2%}'.format(x/y)
'78.26%'
>>>import math
>>>math.trunc(b)
1234567890
>>>math.trunc(123.987)
123
>>>math.floor(b)
1234567890
>>>math.floor(123.987)
123
>>>math.ceil(123.01)
124
>>>round(b,2)
1234567890.12
>>>round(b,3)
1234567890.123
>>>round(b,4)
1234567890.1235
3、随机数

random.choice():随机从一个序列中得到一个值

>>">>>>lst = list(range(1,11))
>>>lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>import random
>>>random.choice(lst)
8
>>>random.choice(lst)
4
>>>random.choice(lst)
10

random.sample():找出特定数量的序列

>>">>>>random.sample(lst,3)
[3, 2, 10]
>>>random.sample(lst,3)
[4, 5, 1]
>>>random.sample(lst,3)
[3, 5, 9]

random.shuffle():打乱列表中值的顺序

>>">>>>lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>random.shuffle(lst)
>>>lst
[10, 2, 8, 7, 1, 4, 3, 9, 6, 5]

random.randint():随机产生固定范围内的值

>>">>>>random.randint(1,10)
8

random.random()随机产生一个浮点数

>>">>>>random.random()
0.16785246599323045

返回指定比特位的随机数

>>">>>>random.getrandbits(5)
5
>>>random.getrandbits(5)
2

(二)日期

1、datetime:year 、month、day
>>">>>>import datetime
>>>datetime.MAXYEAR
9999
>>>datetime.MINYEAR
1
>>>today = datetime.date.today()
>>>today
datetime.date(2019, 9, 13)
>>>today.year
2019
>>>today.month
9
>>>today.day
13
>>>today.weekday()
4
>>>today.isoweekday()
5

构造时间,中间以逗号隔开

>>">>>>birthdate = datetime.date(2018,3,12)
>>>birthdate.year
2018
>>>birthdate.day
12
>>>t = datetime.time(15,46,32)
>>>t.hour
15
>>>t.minute
46

构造年,月,日,时,分,秒

>>">>>>t = datetime.datetime(1998,3,3,20,33,44)
>>>t.year
1998
>>>t.month
3
>>>t.day
3
>>>t.hour
20
>>>t.minute
33
>>>t.second
44
2、格式转换

字符串到日期时间 datetime.datetime.strptime(‘txt’,‘格式’)
日期时间到字符串 datetime.datetime.strftime('格式‘)

>>">>>>import datetime
>>>s = '2018-3-15'
>>>type(s)
<class 'str'>
>>>t = datetime.datetime.strptime(s,'%Y-%m-%d')
>>>t
datetime.datetime(2018, 3, 15, 0, 0)

now = datetime.datetime.now()
now
datetime.datetime(2019, 9, 13, 16, 8, 9, 102131)
txt = now.strftime('%Y/%M/%d')
txt
'2019/08/13'

占位符:%Y 四位年份 %y二位年份 %m二位月份 %d二位日期 %H二位小时
%M二位分钟 %S二位分钟 %f微秒 %w星期数 0…

(三)Python的时间差处理:timedelta

>>">>>>o = datetime.datetime(2008,8,8,20,8)
>>>o + datetime.timedelta(days = 100)
datetime.datetime(2008, 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)