接口自動化是指模擬程序接口層面的自動化,因爲接口不易變動,維護成本更小,因此深受各大公司的喜好。
接口自動化包含2個部分,功能性的接口自動化測試和併發接口自動化測試。
本次文章着重介紹第一種,功能性的接口自動化框架。html
環境:Mac、Python 3,Pytest,Allure,Request
流程:讀取Yaml測試數據-生成測試用例-執行測試用例-生成Allure報告
模塊類的設計說明:git
Request.py
封裝request方法,能夠支持多協議擴展(get\post\put)
Config.py
讀取配置文件,包括:不一樣環境的配置,email相關配置
Log.py
封裝記錄log方法,分爲:debug、info、warning、error、critical
Email.py
封裝smtplib方法,運行結果發送郵件通知
Assert.py
封裝assert方法
run.py
核心代碼。定義並執行用例集,生成報告github
Yaml測試數據格式以下:shell
--- 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" }
該文件中區分測試環境[private_debug]和正式環境[online_release]分別定義相關配置項,[mail]部分爲郵件相關配置項json
# http接口測試框架配置信息 [private_debug] # debug測試服務 tester = your name environment = debug versionCode = your version host = www.jianshu.com loginHost = /Login loginInfo = email=wang@user.com&password=123456 [online_release] # release正式服務 tester = your name environment = release versionCode = v1.0 host = www.jianshu.com loginHost = /Login loginInfo = email=wang@user.com&password=123456 [mail] #發送郵件信息 smtpserver = smtp.163.com sender = test1@163.com receiver = wang@user.com username = wang@user.com password = 123456
yaml測試數據例子見第一節,一條接口可定義多條case數據,get_parameter爲已封裝好的讀取yaml數據方法,循環讀取後將多條case數據存在list中。api
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'])
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')
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
[ERROR 2018-08-24 09:55:37]Response body != expected_msg, expected_msg is {"error":"繼續操做前請註冊或者登陸9."}, body is {"error":"繼續操做前請註冊或者登陸."} [ERROR 2018-08-24 10:00:11]Response time > expected_time, expected_time is 400, time is 482.745 [ERROR 2018-08-25 21:49:41]statusCode error, expected_code is 208, statusCode is 200
def assert_body(self, body, body_msg, expected_msg): """ 驗證response body中任意屬性的值 :param body: :param body_msg: :param expected_msg: :return: """ try: msg = body[body_msg] assert msg == expected_msg return True except: self.log.error("Response body msg != expected_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): """ 驗證response body中是否包含預期字符串 :param body: :param expected_msg: :return: """ try: text = json.dumps(body, ensure_ascii=False) # print(text) assert expected_msg in text return True except: self.log.error("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg) Consts.RESULT_LIST.append('fail') raise
def post_request(self, url, data, header): """ Post請求 :param url: :param data: :param 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, headers=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爲響應時間,單位爲毫秒 time_consuming = response.elapsed.microseconds/1000 # time_total爲響應時間,單位爲秒 time_total = response.elapsed.total_seconds() Common.Consts.STRESS_LIST.append(time_consuming) response_dicts = dict() response_dicts['code'] = response.status_code try: response_dicts['body'] = response.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
一、集成Jenkins,使用Jenkins插件生成Allure報告
二、多線程併發接口自動化測試
三、接口加密,參數加密session
開源代碼:https://github.com/wangxiaoxi3/API_Automation多線程
以上,喜歡的話請點贊❤️吧~
請關注個人簡書,博客,TesterHome,Github~~~併發