Python通过Pillow实现图片对比
作者:虫师 时间:2023-07-12 08:25:15
在编写Web自动化测试用例的时候,如何写断言使新手不解,严格意义上来讲,没有断言的自动化脚本不能叫测试用例。就像功能测试一样,当测试人员做了一些操作之后必然会判断实际结果是否等于预期结果,只不过,这个过程由测试人员的眼睛完成。而自动化测试脚本必然要通过一此信息来断定用例是否成功。
这其中常用的三种信息分别是:
title :页面不同或显示不同时往往title也会有所变化。
url :与title类似,当页面发生变化时,跟着url也会改变。
text:相比前者应用更广泛,因为通过它可以获取页面上的任意标识性文本,用于“证明”用例执行是成功的。例如,登陆之后人用户名,查询的结果等。
但是,在有些情况下,无法获取这些信息来证明用例是成功的怎么办?当然,下策是不写断言,脚本运行没有报错来证明用例执行成功,这当然是无奈之举。除此之外还可以选择断言两张图片,在用例执行正确的情况下对当前页面进行截图,在用例执行的过程中再次进行截图。通过对两张图片进行比较,从而判断用例是否运行成功。
Pillow下载:https://pypi.python.org/pypi/Pillow/3.0.0
根据自己的操作系统以及python版本选择下载。
安装:
> python3 -m pip install Pillow-3.0.0-cp35-none-win_amd64.whl
Processing c:\selenium\pillow-3.0.0-cp35-none-win_amd64.whl
Installing collected packages: Pillow
Successfully installed Pillow-3.0.0
注意,因为我本机同时安装了Python2.7和Python3.5,所以,这里特意指定安装在Python3的下面。
from PIL import Image
import math
import operator
from functools import reduce
def image_contrast(img1, img2):
image1 = Image.open(img1)
image2 = Image.open(img2)
h1 = image1.histogram()
h2 = image2.histogram()
result = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2, h1, h2)))/len(h1) )
return result
if __name__ == '__main__':
img1 = "./img1.jpg" # 指定图片路径
img2 = "./img2.jpg"
result = image_contrast(img1,img2)
print(result)
如果两张图片完全相等,则返回结果为浮点类型“0.0”,如果不相同则返回结果值越大。
这样就可以在自动化测试用例中调用该方法来断言执行结果。
关于Pillow库的详细文档:
http://pillow.readthedocs.org/en/latest/index.html
来源:https://www.cnblogs.com/fnng/p/4881102.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬虫使用requests发送post请求示例详解
Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError
![](https://img.aspxhome.com/file/2023/6/65476_0s.jpg)
解决pycharm编辑区显示yaml文件层级结构遇中文乱码问题
![](https://img.aspxhome.com/file/2023/0/123840_0s.jpg)
python 将列表里的字典元素合并为一个字典实例
Appium自动化测试实现H5页面元素定位
![](https://img.aspxhome.com/file/2023/0/60740_0s.png)
详解go中的引用类型
Python获取百度热搜的完整代码
![](https://img.aspxhome.com/file/2023/6/117296_0s.png)
MySQL性能优化的一些技巧帮助你的数据库
利用ASP在线维护数据库
![](https://img.aspxhome.com/file/UploadPic/200710/12/20071012135842950s.jpg)
Python利用treap实现双索引的方法
![](https://img.aspxhome.com/file/2023/8/80748_0s.jpg)
JavaScript+Canvas实现带跳动效果的粒子动画
![](https://img.aspxhome.com/file/2023/2/135932_0s.png)
python实现健康码查验系统
![](https://img.aspxhome.com/file/2023/3/97613_0s.jpg)
OpenCV每日函数之BarcodeDetector类条码检测器
![](https://img.aspxhome.com/file/2023/1/100791_1s.png)
win10从零安装配置pytorch全过程图文详解
![](https://img.aspxhome.com/file/2023/1/105401_0s.png)
PHP生成sitemap.xml地图函数
MySQL使用profile查询性能的操作教程
TensorFLow 数学运算的示例代码
![](https://img.aspxhome.com/file/2023/8/113148_0s.png)
详解Python import方法引入模块的实例
单点登录之cas集成sonar的配置方法
![](https://img.aspxhome.com/file/2023/0/132320_0s.jpg)
python人工智能tensorflow常用激活函数Activation Functions
![](https://img.aspxhome.com/file/2023/6/67236_0s.png)