对于经常借助于使用自动化手段测试的同学来说,无论使用接口自动化工具,还是自研的测试框架,一个完整的自动化用例,断言部分绝对是重中之重,因为断言的颗粒度在一定程度上能反映用例质量,必然断言颗粒度越细,越可能发现问题,对于接口测试来说,接口返回结果断言是必须的,但是这还不够,更建议对落库的数据与接口的request中重要字段进行断言, 而断言实质也是数据之间的比较,例如相等、包含、非空等。
今天介绍的Python库assertP就是这样一个方便测试同学高效断言的工具,测试同学直接将数据库取出的数据作为实际结果 与 预期结果进行比较。它支持相等断言、包含断言、非空断言、JSON断言,具体使用方法介绍如下。
pip install assertP
-- Create Table CREATE TABLE `al_pay` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_id` varchar(11) COLLATE utf8mb4_bin DEFAULT NULL, `pay_status` varchar(11) COLLATE utf8mb4_bin DEFAULT NULL, `pay_amount` int(11) DEFAULT NULL, `pay_cur` varchar(11) COLLATE utf8mb4_bin DEFAULT NULL, `order_id` varchar(30) COLLATE utf8mb4_bin NOT NULL DEFAULT '', `ext` varchar(200) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
测试代码:
import pymysqlfrom assertP import AssertPy_multi, AssertPy# 连接数据库, 和mysql服务端设置格式一样(还可设置为gbk, gb2312)conn = pymysql.connect(host="localhost", user="root", passwd="123456", db='article', charset='utf8', port=3306)cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)# 执行sql语句select_sql = "select order_id, user_id, pay_status, pay_amount from al_pay where order_id=%s;"cursor.execute(select_sql, ("2022010818343700000002",))act = cursor.fetchall()[0]exp = {'order_id': '2022010818343700000001', 'user_id': '20210100002', 'pay_status': 'CLOSED'}# 断言AssertPy('al_pay', act, exp)conn.commit()cursor.close()conn.close()
act = {'pay_amount': "2000", 'pay_cur': 'RMB', 'order_id': '2022010818343700000001', 'ext': '{"user_name": "QA", "currency": "RMB"}'}exp = {'pay_amount': "CONTAINS_CHECK:2000", 'pay_cur': 'RMB', 'order_id': '2022010818343700000001', 'ext': '{"user_name": "QA", "currency": "RMB"}'}AssertPy(tName, act, exp)
act = {'ext': '{"user_name": "QA", "currency": "RMB"}'}exp = {'ext': 'JSON:{"user_name": "QA", "currency": "USD"}'}AssertPy(tName, act, exp)
tName = "TestTable" act = [{'order_id': '2022010818343700000003', 'user_id': '20210100002', 'pay_status': 'PAYING'}, {'order_id': '2022010818343700000003', 'user_id': '20210100001', 'pay_status': 'SUCCESS'}] exp = [{'order_id': '2022010818343700000003', 'user_id': '20210100002', 'pay_status': 'PAYING'}, {'order_id': '2022010818343700000003', 'user_id': '20210100001', 'pay_status': 'SUCCESS'}] AssertPy_multi(tName, act, exp)
更多断言类型,扩展中。。。
assertP:https://pypi.org/project/assertP/
Selquel pro:www.sequelpro.com/
Python texttable:https://pypi.org/project/texttable/
PyMySQL:https://pypi.org/project/PyMySQL/
logging:https://docs.python.org/3/library/logging.html