在网上搜索了好多关于API自动化测试的文章,也看了一些书籍,从中总结了一些,自己写了一个简单的API测自动化框架(基于unittest的框架,利用了数据驱动,python的一个包ddt),适合用于回归测试(每个API关联较少的),中间还有一些小的问题,欢迎大家的指正。
主要框架结构:
1.一个用于写测试用例的excel文档(或其他格式的文档也可以),放在参数的文件夹中
2.关于log记录的文件夹
3.用于记录参数的文件夹
4.执行用例的文件
5.读取用例的文件
以下是各个部分的代码:
a.读取测试用例的部分代码
b.执行用例的代码:
import unittest
from ddt import ddt, data, unpack
from api_test.api_method import *
from api_test.base_method import *
@ddt
class MyTestCase(unittest.TestCase):
@data(*excel_n_Values)
@unpack
def test_something(self, num, method, url, headers, body, except_result):
# if num == 22:
# print base_url+operate_url(url)
response = requests.request(method, base_url+operate_url(url), headers=eval(headers), data=json.dumps(eval(body)))
response_body = operate_return_str(response.text)
# if num == 22:
# print response_body
store_variable(response_body)
# print environment_variables
write_log(num, response, int(except_result), response_body)
self.assertEqual(int(except_result), response.status_code)
if __name__ == '__main__':
unittest.main()
c.日志的代码:
# _*_ coding=utf-8 _*_
__author__ = 'lucas'
import logging
import logging.config
class Logger(object):
def __init__(self):
logging.config.fileConfig("/Users/lucas/PycharmProjects/AutoTest_UI/api_test/log/logging.conf") # 采用配置文件
@staticmethod
def debug(message):
logger = logging.getLogger("debug")
logger.debug(message)
@staticmethod
def info(message):
logger = logging.getLogger("info")
logger.info(message)
@staticmethod
def error(message):
logger = logging.getLogger("error")
logger.error(message)
@staticmethod
def warning(message):
logger = logging.getLogger("warning")
logger.warning(message)
@staticmethod
def critical(message):
logger = logging.getLogger("critical")
logger.critical(message)
instance = Logger()
d.关于参数的就具体看业务了,根据实际情况写
e.测试用例模板:
ok,暂时就这些了,尽管还有一点小问题,后期还需要进一步的优化,适合更复杂的场景,目前适合简单的回归测试的自动化,欢迎指正,共同努力优化。