本文主要是介绍robotframework 图片校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题由来
由于某些时候需要校验图片是否为一致,比如一些重要的图标,接口返回的图片地址是否符合要求等
在网络上找了一圈,发现觉大多数都要用到额外的类库,感觉这样比较麻烦不太适合自己,想着原来用md5来判断文件是否一致的情况,那图片也可以用类似的方法,于是想到用base64编码图片来进行比较
具体代码如下:
#encoding=utf8
"""通过base64编码的字符来比较两个图片是否一致作者:Thomas日期:2015/4/8
"""import requests
import base64
from robot.utils.asserts import fail_unlessdef get_url_photo_str(url):'''参数为图片的网络地址use example:${data}= | Get Url Photo Str | ${url} |'''#yield base64.b64encode(requests.get(url).content)return base64.b64encode(requests.get(url).content)def get_path_photo_str(path):'''参数为图片的本地地址use example:${data}= | Get Path Photo Str | ${path} |'''with open(path, "rb") as image_file:encode_str = base64.b64encode(image_file.read())#yield encode_strreturn encode_strdef path_url_check(path,url):'''参数为图片的本地地址和网络地址,然后将两者的base64编码进行比较,如果一致就表示两个图片一样use example:| Path Url Check | ${path} | ${url} |'''fail_unless(_path_url_check(path,url), "local picture is different from url picture ")def url_url_check(url1,url2):'''参数为两个图片的网络地址,然后将两者的base64编码进行比较,如果一致就表示两个图片一样use example:| Url Url Check | ${url1} | ${url2} |'''fail_unless(_url_url_check(url1,url2),'the two url picture is different')def _url_url_check(url1,url2):'''网络图片比较'''return True if get_url_photo_str(url1)==get_url_photo_str(url2) \else Falsedef _path_url_check(path,url):'''本地图片和网络图片比较'''return True if get_path_photo_str(path)==get_url_photo_str(url) \else False
测试代码:
#!/usr/bin/env python
#encoding=utf-8import unittest
import online_photo_checkclass UserInfoTest(unittest.TestCase):def test_url_url_check(self):url1 = 'https://assets-cdn.github.com/images/modules/open_graph/github-mark.png'self.assertTrue(online_photo_check._url_url_check(url1, url1))url2 = 'https://assets-cdn.github.com/images/modules/open_graph/github-octocat.png'self.assertFalse(online_photo_check._url_url_check(url1, url2))def test_path_url_check(self):path = "c:\\github-octocat.png"url1 = 'https://assets-cdn.github.com/images/modules/open_graph/github-mark.png'self.assertFalse(online_photo_check._path_url_check(path, url1))url2 = 'https://assets-cdn.github.com/images/modules/open_graph/github-octocat.png'self.assertTrue(online_photo_check._path_url_check(path, url2))
这篇关于robotframework 图片校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!