Pytest是python的一个测试模块,可以编写一些简单的测试用例,也可以用来进行一些批量测试,下面简单介绍一下。
1,安装
# 来自jb51.cc
$ pip install -U pytest
or
$ easy_install -U pytest
$ py.test --version
2,基础语法
# 来自jb51.cc
#!/usr/bin/python
import pytest
def func(x):
return x + 1
def test_answer(): #测试用例,方法需要以test_开头
assert func(3) == 5
运行之
# 来自jb51.cc
$ py.test 2.py #注意需要用py.test命令来运行之
稍微复杂一点儿的写法:
# 来自jb51.cc
#!/usr/bin/python
import pytest
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = 3
assert x > 2
这里总结一下用法,
1,以test_开头的方法,会被py.test自动处理,无需额外调用该方法;
2,使用assert进行判断,assert后面应该是一个boolean类型的,可以是一个判断语句,比如3 > 2,又或者是a in b等等。
3,实际应用
这里有一个实际应用,我想批量检查一批机器上的cpu,内存,和机器上的2个分区,并将cpu大于80%,内存大于95,和分区大于80%的机器找出来,如何实现呢?
假设这里已经提供好了API,可以读取到所有机器上的cpu、内存、分区信息,API地址为http://api/latestMeteris?userCode=xxx&token=xxx&host=’172.20.116.70,172.20.116.72’&service=cpu,Memory,Disk
访问API时返回一串JSON,信息如下:
# 来自jb51.cc
{
"message":"success","result":"success","start":"2017-02-28 13:54:53","data":{
"Memory":{
"172.20.116.72":{
"swap_used":["9.60%"],"datetime":["2017-02-28 13:54:41"],"merge_time":["2017-02-28 13:54:41"],"ram_used":["25.52%"]
},"172.20.116.70":{
"swap_used":["6.17%"],"ram_used":["25.97%"]
}
},"cpu":{
"172.20.116.72":{
"datetime":["2017-02-28 13:54:41"],"cpu_prct_used":["3.00%"]
},"172.20.116.70":{
"datetime":["2017-02-28 13:54:41"],"cpu_prct_used":["1.00%"]
}
},"Disk":{
"172.20.116.72":{
"datetime":["2017-02-28 13:54:41"],"/export":["25.06%"],"/":["21.6%"]
},"/export":["44.68%"],"/":["36.15%"]
}
}
},"host_size":2,"end":"2017-02-28 13:54:53"
}
pytest脚本写法如下:
# 来自jb51.cc
#!/usr/bin/python
import os
import sys
import json
import urllib
import urllib2
import pytest
iplist = ["172.20.116.70","172.20.116.72"] #定义IP列表
ips = ','.join(iplist)
url = 'http://api/latestMeteris?userCode=xxx&token=xxx&host=' + ips + '&service=cpu,Disk'
req = urllib.urlopen(url)
result = req.read() #get a string type
a = json.loads(result) #transfer string type to dict type
@pytest.mark.parametrize('ip',iplist)
def test_cpu(ip):
value = a["data"]["cpu"][ip]["cpu_prct_used"][0]
assert float(value.strip("%")) < 80
@pytest.mark.parametrize('ip',iplist)
def test_memory(ip):
value = a["data"]["Memory"][ip]["ram_used"][0]
assert float(value.strip("%")) < 95
@pytest.mark.parametrize('ip',iplist)
def test_disk(ip):
value_root = a["data"]["Disk"][ip]['/'][0]
value_export = a["data"]["Disk"][ip]['/export'][0]
assert float(value_root.strip("%")) < 80 and float(value_export.strip("%")) < 80
运行脚本试一下
# 来自jb51.cc
$ py.test 2.py
========================= test session starts =========================
platform linux2 -- Python 2.7.4,pytest-3.0.6,py-1.4.31,pluggy-0.4.0
rootdir: /home/zhukun/0224,inifile:
collected 6 items
2.py ......
====================== 6 passed in 0.05 seconds ======================
意为6个测试全部通过。 原文链接:https://www.f2er.com/python/527107.html