Pytest常用插件之HTML报告(十二)
- 2020 年 1 月 27 日
- 筆記
在Pytest的测试框架中,有很丰富的插件,还是接着之前的案例继续延伸来说这部分,今天主要介绍基于Pytest测试框架的测试报告部分,其实在Pytest测试框架里面,测试报告可以使用html的插件,也可以使用allure来生成测试报告,关于allure在使用会在下一个文章中详细的介绍它的使用。
首先来安装基于HTML测试报告的插件,插件名称为pytest-html,安装的命令为:pip3 install pytest-html,安装成功后,就会显示如下的信息:
Installing collected packages: pytest-html Successfully installed pytest-html-2.0.1
编写测试案例,以测试常用的网站为案例,具体使用的测试源码如下:
#!/usr/bin/python3 #coding:utf-8 import pytest import yaml import os import requests import json class Request: def request(self,url,method='get',**kwargs): if method=='get': return requests.request(url=url,method=method,**kwargs) elif method=='post': return requests.request(url=url,method=method,**kwargs) elif method=='put': return requests.request(url=url,method=method,**kwargs) elif method=='delete': return requests.request(url=url,method=method,**kwargs) def get(self,url,**kwargs): return self.request(url=url,method='get',**kwargs) def post(self,url,**kwargs): return self.request(url=url,method='post',**kwargs) def put(self,url,**kwargs): return self.request(url=url,method='put',**kwargs) def delete(self,url,**kwargs): return self.request(url=url,method='delete',**kwargs) def readYaml(): with open('books.yaml','r') as f: return list(yaml.safe_load_all(f)) @pytest.mark.parametrize('datas',readYaml()) def test_books(datas): if datas['method']=='get': r=Request().get(url=datas['url']) assert datas['expect'] in json.dumps(r.json(),ensure_ascii=False) elif datas['method']=='post': r=Request().post(url=datas['url'],json=datas['dict1']) assert datas['expect'] in json.dumps(r.json(),ensure_ascii=False) elif datas['method']=='put': r=Request().put(url=datas['url'],json=datas['dict1']) assert datas['expect'] in json.dumps(r.json(), ensure_ascii=False) elif datas['method']=='delete': r=Request().delete(url=datas['url']) assert datas['expect'] in json.dumps(r.json(), ensure_ascii=False) if __name__ == '__main__': pytest.main(["-v","-s","wxPytest.py"])
被测试的API的源码为:
#!/usr/bin/python3 #coding:utf-8 from flask import Flask,make_response,jsonify,abort,request from flask_restful import Api,Resource from flask_httpauth import HTTPBasicAuth app=Flask(__name__) api=Api(app=app) auth=HTTPBasicAuth() @auth.get_password def get_password(name): if name=='admin': return 'admin' @auth.error_handler def authoorized(): return make_response(jsonify({'msg':"请认证"}),401) books=[ {'id':1,'author':'wuya','name':'Python接口自动化测试实战','done':True}, {'id':2,'author':'无涯','name':'Selenium3自动化测试实战','done':False} ] class Books(Resource): # decorators = [auth.login_required] def get(self): return jsonify({'status':0,'msg':'ok','datas':books}) def post(self): if not request.json: return jsonify({'status':1001,'msg':'请求参数不是JSON的数据,请检查,谢谢!'}) else: book = { 'id': books[-1]['id'] + 1, 'author': request.json.get('author'), 'name': request.json.get('name'), 'done': True } books.append(book) return jsonify({'status':1002,'msg': '添加书籍成功','datas':book}, 201) class Book(Resource): # decorators = [auth.login_required] def get(self,book_id): book = list(filter(lambda t: t['id'] == book_id, books)) if len(book) == 0: return jsonify({'status': 1003, 'msg': '很抱歉,您查询的书的信息不存在'}) else: return jsonify({'status': 0, 'msg': 'ok', 'datas': book}) def put(self,book_id): book = list(filter(lambda t: t['id'] == book_id, books)) if len(book) == 0: return jsonify({'status': 1003, 'msg': '很抱歉,您查询的书的信息不存在'}) elif not request.json: return jsonify({'status': 1001, 'msg': '请求参数不是JSON的数据,请检查,谢谢!'}) elif 'author' not in request.json: return jsonify({'status': 1004, 'msg': '请求参数author不能为空'}) elif 'name' not in request.json: return jsonify({'status': 1005, 'msg': '请求参数name不能为空'}) elif 'done' not in request.json: return jsonify({'status': 1006, 'msg': '请求参数done不能为空'}) elif type(request.json['done'])!=bool: return jsonify({'status': 1007, 'msg': '请求参数done为bool类型'}) else: book[0]['author'] = request.json.get('author', book[0]['author']) book[0]['name'] = request.json.get('name', book[0]['name']) book[0]['done'] = request.json.get('done', book[0]['done']) return jsonify({'status': 1008, 'msg': '更新书的信息成功', 'datas': book}) def delete(self,book_id): book = list(filter(lambda t: t['id'] == book_id, books)) if len(book) == 0: return jsonify({'status': 1003, 'msg': '很抱歉,您查询的书的信息不存在'}) else: books.remove(book[0]) return jsonify({'status': 1009, 'msg': '删除书籍成功'}) api.add_resource(Books,'/v1/api/books') api.add_resource(Book,'/v1/api/book/<int:book_id>') if __name__ == '__main__': app.run(debug=True)
到测试的目录下,执行命令:
pytest -v -s –html=report.html
执行如上的命令后,就会显示执行的结果信息以及生成对应的HTML测试报告,如下图所示:

执行成功后,会在当前的目录下生成report.html的文件,打开后,就会显示基于HTML的测试报告,如下图所示:

在测试报告中可以很清晰的看到执行测试点的总数,以及成功的和失败的信息。