Objective:
Interface automation refers to the simulation program interface level of automation, because the interface is not easy to change, maintenance costs are smaller, so the major companies are loved.
Interface automation consists of 2 parts, functional interface Automation testing and concurrent interface Automation testing.
This article focuses on the first, functional interface Automation framework.
First, Brief introduction
Environment: MAC, Python 3,pytest,allure,request
Process: Read YAML test data-Generate test Case-execute test Case-Generate Allure Report
Design description of the module class:
Request.py
Encapsulates the request method, which can support multi-protocol extensions (GET\POST\PUT)
Config.py
Read configuration files, including: Configuration of different environments, email related configuration
Log.py
Package record log method, divided into: Debug, info, warning, error, critical
Email.py
Package Smtplib method, run results send mail notification
Assert.py
Encapsulating the Assert method
run.py
Core code. Define and execute use case sets, generate reports
The YAML test data format is as follows:
---Basic: dec: "基础设置" parameters: - url: /settings/basic.json data: slug=da1677475c27 header: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko)\ Chrome/67.0.3396.99 Safari/537.36", "Content-Type": "keep-alive" }
Two, code structure and framework flow 1, code structure see:
2, the framework process see:
Iii. detailed features and instructions for use 1. Define configuration file Config.ini
This file distinguishes between the test environment [Private_debug] and the formal environment [online_release], respectively defining the relevant configuration items, and the [Mail] section for message-related configuration items
# http接口测试框架配置信息[private_debug]# debug测试服务tester = your nameenvironment = debugversionCode = your versionhost = www.jianshu.comloginHost = /LoginloginInfo = email=wang@user.com&password=123456[online_release]# release正式服务tester = your nameenvironment = releaseversionCode = v1.0host = www.jianshu.comloginHost = /LoginloginInfo = email=wang@user.com&password=123456[mail]#发送邮件信息smtpserver = smtp.163.comsender = test1@163.comreceiver = wang@user.comusername = wang@user.compassword = 123456
2. After reading the YAML test data package
YAML test data example in the first section, an interface can define multiple case data, get_parameter for the encapsulated read Yaml data method, after the loop read multiple case data exist in the list.
class Basic: params = get_parameter('Basic') url = [] data = [] header = [] for i in range(0, len(params)): url.append(params[i]['url']) data.append(params[i]['data']) header.append(params[i]['header'])
3. Writing Use Cases
class TestBasic: @pytest.allure.feature('Home') @allure.severity('blocker') @allure.story('Basic') def test_basic_01(self, action): """ 用例描述:未登陆状态下查看基础设置 """ conf = Config() data = Basic() test = Assert.Assertions() request = Request.Request(action) host = conf.host_debug req_url = 'http://' + host urls = data.url params = data.data headers = data.header api_url = req_url + urls[0] response = request.get_request(api_url, params[0], headers[0]) assert test.assert_code(response['code'], 401) assert test.assert_body(response['body'], 'error', u'继续操作前请注册或者登录.') assert test.assert_time(response['time_consuming'], 400) Consts.RESULT_LIST.append('True')
4. Run the entire frame run.py
if __name__ == '__main__': # 定义测试集 allure_list = '--allure_features=Home,Personal' args = ['-s', '-q', '--alluredir', xml_report_path, allure_list] log.info('执行用例集为:%s' % allure_list) self_args = sys.argv[1:] pytest.main(args) cmd = 'allure generate %s -o %s' % (xml_report_path, html_report_path) try: shell.invoke(cmd) except: log.error('执行用例失败,请检查环境配置') raise try: mail = Email.SendMail() mail.sendMail() except: log.error('发送邮件失败,请检查邮件配置') raise
5. Err.log instances
6, the assert part of the code
def assert_body (self, body, body_msg, expected_msg): "" Verifies the value of any property in the response body:p Aram Body: :p Aram Body_msg::p Aram Expected_msg:: Return: "" "try:msg = body[body_msg] assert msg = = expected_msg return True except:self.log.error ("Response body msg! = E Xpected_msg, Expected_msg is%s, Body_msg is%s "% (expected_msg, body_msg)) Consts.RESULT_LIST.append (' fail ') Raise Def assert_in_text (self, Body, expected_msg): "" "verifies whether the expected string is included in the body of response:p Ara M body::p Aram Expected_msg:: Return: "" "Try:text = Json.dumps (Body, ensure_ascii =false) # Print (text) assert expected_msg in text return True except:s Elf.log.error ("Response body Does not contain expected_msg, Expected_msg is%s"% expected_msg) consts.result_l Ist.append (' fail ') Raise
7. Request Part Code
def post_request (self, URL, data, header): "" "POST request:p Aram URL::p aram data::p AR AM Header:: return: "" "If not Url.startswith (' http://') = URL = '%s%s '% (' http:/', URL) Print (URL) try:if data is None:response = Self.get_session.post (Url=url, Hea Ders=header) Else:response = Self.get_session.post (Url=url, Params=data, Headers=header) except requests. Requestexception as E:print ('%s%s '% (' requestexception url: ', url)) print (e) return () Except Exception as E:print ('%s%s '% (' Exception url: ', url)) print (e) return ( # time_consuming is the response time in milliseconds time_consuming = response.elapsed.microseconds/1000 # Time_Total for response time, single bits are seconds time_total = Response.elapsed.total_seconds () Common.Consts.STRESS_LIST.append (time_consuming) re Sponse_Dicts = Dict () response_dicts[' code '] = Response.status_code try:response_dicts[' body ' = respon Se.json () except Exception as E:print (e) response_dicts[' body ' = ' response_dicts[' Text '] = response.text response_dicts[' time_consuming '] = time_consuming response_dicts[' time_total '] = time _total return response_dicts
Iv. Allure Report and overview of the EMAIL1 and Allure reports, see:
2, email See:
Five, follow-up optimization
1. Integrated Jenkins, generate Allure report using Jenkins Plugin
2. Multi-threaded concurrent Interface Automation test
3, interface encryption, parameter encryption
Open Source code: github.com/wangxiaoxi3/api_automation
Above, if you like, please praise ️.
Please follow my brief book, blog, testerhome,github~~~