基於Wiremock建立Mock Service平臺(轉)

本文連接:https://blog.csdn.net/liuchunming033/article/details/52399397                                                                                                                                                                                                                                                                       一、Wiremock工具介紹html

通常開發項目都會分模塊進行,好比都會把前端和後端分開,在前端和後端裏面也一般是分模塊開發的。當開發進度不一致時,能夠對依賴接口構建Mock Service,模擬不一樣輸入/數據/場景,這樣不至於影響本模塊的開發進度。構建Mock Service方法不少,今天介紹Wiremock,Wiremock很是輕便易用,甚至不用編程,一個jar包基本夠用了,固然,也能夠把它引用寫進測試代碼裏。前端

官網地址:http://wiremock.org/java

Jar包下載:http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.1.10/wiremock-standalone-2.1.10.jarpython

 

二、Wiremock工做原理linux

啓動wiremockgit

 

java -jar wiremock-2.1.10-standalone.jar –port 9999 —verbose1github

(–port設定端口爲9999; –verbose開啓日誌。更多參數須要參考: http://wiremock.org/docs/running-standalone/ 啓動後在同目錄下生成兩個空的文件夾:__files和mappings。__files是放上傳/下載/錄製文件的,mappings放response和request url的映射的。 在mappings文件夾下隨便建立一個*.json文件,好比長下面這樣:正則表達式

 

"request": {         "method": "GET",         "url": "/api/testdetail"     },     "response": {         "status": 200,         "bodyFileName": "testdetail.json」,         "headers": {             "Content-Type": "application/json",             "Cache-Control": "max-age=86400"         }     } }12345678910111213sql

bodyFileName還能夠是html、xml等文檔。 在瀏覽器或者使用curl命令,調用http://localhost:9999/api/testdetail,就能返回testdetail.json的內容了。testdetail.json就是須要咱們在__files裏面創建的響應文件。wiremock也支持直接在response結構體中返回響應內容,好比在mapping文件中,將response寫成下面這樣:shell

 

"response": {     "status": 200,     "body": 「Hello world ",     "headers": {         "Content-Type": "application/json",         "Cache-Control": "max-age=86400"     }1234567

當發送請求時候,將直接返回「Hello world」。

 

三、Wiremock支持的HTTP方法

HTTP方法支持GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS等,自定義頭、數據模板(bodyPatterns,如不符合,拋出404錯誤),URL Template,Query參數匹配,顯示指定文件內容等。下面將介紹如何使用wiremock實現這些。

 

3.1 POST

POST http://localhost:9999/api/products

 

{     "request": {         "method": "POST",         "url": "/api/products",           "bodyPatterns": [                  {"equalToJson" : "{ \"name\": \"new product\", \"creator\": \"tester\", \"createTime\": \"2015-09-07\" }", "jsonCompareMode": "LENIENT"}          ]     },     "response": {         "status": 201,         "body": "Add successfully.",          "headers":{                    "x-token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxx"          }     }

}123456789101112131415161718

 

3.2 PUT

PUT: http://localhost:9999/api/products/1

 

{     "request": {         "method": "PUT",         "url": "/api/products/1",         "bodyPatterns": [{             "equalToJson": "{ \"id\": 1, \"name\": \"new product\", \"creator\": \"tester\", \"createTime\": \"2015-09-07\" }",             "jsonCompareMode": "LENIENT"         }]     },     "response": {         "status": 200,         "body": "Update successfully.",         "headers": {             "x-token": " xxxxxxxxxxxxxxxxxxxxxxxxxxxx"         }     } }1234567891011121314151617

 

3.3 DELETE

DELETE: http://localhost:9999/api/products/1

 

{     "request": {         "method": "DELETE",         "url": "/api/products/1"     },     "response": {         "status": 204,              "headers":{                   "x-token":" xxxxxxxxxxxxxxxxxxxxxxxxxxxx"         }     } }12345678910111213

 

3.4 URL Matching

URL Matching: http://localhost:9999/api/products/1(2/3…)

 

{     "request": {         "method": "GET",         "urlPattern": "/api/products/[0-9]+"     },     "response": {         "status": 200     } }123456789

 

3.5 Query參數匹配

Query參數匹配:http://localhost:9999/api/products?search=china

 

{     "request": {         "method": "GET",         "urlPath": "/api/products",         "queryParameters": {             "search": {                 "contains": "chin"             }         }     },     "response": {         "status": 200,         "headers": {             "Content-Type": "application/json"         },         "body": "{ \"id\": 7, \"name\": \"shan zai\", \"from\":\"China\" },{ \"id\": 7, \"name\": \"shan zai\", \"from\":\"China(RPC)\" }"     } }123456789101112131415161718

 

3.6 模擬錯誤

模擬404錯誤

 

{     "request": {         "url": "/unknown.html",         "method": "GET"     },     "response": {         "status": 404,         "headers": {             "Content-Type": "text/html; charset=utf-8"         }     } }12345678910111213

 

3.7 設置響應延遲

 

{     "request": {         "method": "GET",         "url": "/delayed"     },     "response": {         "status": 200,         "bodyFileName": "mytest.json",         "headers": {             "Content-Type": "application/json",             "Cache-Control": "max-age=86400"         },         "fixedDelayMilliseconds": 2000     } }123456789101112131415

 

四、Mock Service平臺化

使用WireMock經過mappings和__files文件夾能夠有效管理映射和返回內容文件。而這兩個文件目前是手動編輯,若是能夠作成平臺化管理,全部接口經過建立完成,文件命名規則所有由系統進行管理,將節省的時間更多投入業務關注和及早進行自測,這樣子的收益將會更大。

那怎麼樣的平臺纔算可以知足當前需求呢?

基於HTTP協議   支持Url、UrlPattern匹配、Query參數   支持數據存儲   API接口規範化管理   提交表單便可生成mapping和__files所需文件   不一樣項目接口有不一樣的前綴   可以返回指定格式(json、xml、html等)內容   可以設定響應延遲   設置cookies   設置headers   支持用戶驗證

根據需求設計整體架構以下: 包括前臺和後臺。前臺負責接受用戶的Mock設置,後臺負責將用戶的設置轉換爲WireMock所須要的mapping和__file文件,並提供查詢功能。 MockServer架構圖   根據架構圖,作了整體設計以下:   頁面分爲Mock項目管理和Mock API管理。Mock項目管理能夠建立、修改、刪除Mock項目,Mock PAI管理能夠建立、修改、刪除Mock的API。後臺管理負責生成mapping和file文件、對wiremock進行重啓等。

 

4.1 技術選型

因爲你們對python都比較熟悉,也有過使用python的Flask框架進行開發經驗,此次依然採用Flask+Mysql的方案。從界面錄入到mapping、_files文件生成處理採用Python,後臺工具使用WireMock的standalone模式,經過shell腳本進行一鍵啓停管理,以及實時刷新url、mapping映射。

 

4.2 Mock項目管理頁

 

4.2.1 添加項目

配置協議、進行mock服務器的重啓、從新加載(有新的mapping、file文件生成系統會自動reset便可,固然手工reset也能夠,即時加載無須重啓服務等待)。

 

4.2.2 顯示項目

4.2.3 修改項目

4.2.4 刪除項目

 

4.3 Mock API管理頁

 

4.3.1 添加API

選擇方法、URL類型,填寫URL(若是選擇URL類型爲UrlPattern,則填寫正則表達式),填寫狀態碼、返回接口,以及返回頭,就能夠完成一個mock接口的建立。這些信息要存儲到Mysql。   1)手工輸入 適合響應體比較短小的狀況   2)經過url獲取 返回體比較大,目標Mock接口已經存在,能夠直接抓取生成文件;   3)上傳文件的方式 返回體比較大、目標Mock接口還未開發完成,手工上傳返回內容的文件便可。   以上三種靈活的保存返回內容方式,最終保存的接口會按照如下格式生成mapping和__files所需文件。

 

4.3.2 顯示API

展現列表,列出相關URL、方法、是否正則、返回碼、返回類型。

 

4.3.2 修改API

4.3.3 刪除API

 

4.4 MockServer後臺

使用Java-WireMock進行後臺服務,在項目配置頁經過按鈕:重啓、從新加載,調用後臺腳本:wiremock_controller.sh,腳本內容參考:

 

#!/bin/bash if [ "$#" = 0 ];then     echo "Usage: $0 (start|stop|restart|reset)"     exit 1 fi

dirWiremock=`pwd` getCount=`ps -ef | grep "wiremock-1.53-standalone" | grep -v "grep" |wc -l` wiremock_jar=${dirWiremock}/wiremock-1.53-standalone.jar port=9999 wiremock_url=http://localhost:${port}

stop(){     count=${getCount}     if [ 1==${count} ];then     curl -d log=aaa ${wiremock_url}/__admin/shutdown     echo "Stop success!......"     else         echo "Already stop"     fi }

start(){     count=${getCount}     if [ 0==${count} ];then        nohup java -jar ${wiremock_jar} --verbose=true --port=${port} &           echo "Start success!......"     else         echo "Already start"     fi }

if [ "$1" = "restart" ];then     count=${getCount}     if [ 1==${count} ];then           echo "Wiremock is running,wait for restarting! ...."           stop            echo "Start wiremock......"           start      else         start     fi

elif [ "$1" = "start" ];then         echo "Start wiremock......"         start

elif [ "$1" = "stop" ];then         echo "Stop wiremock......"         stop

elif [ "$1" = "reset" ];then     count=${getCount}     if [ 0==${count} ];then           echo "Wiremock must be running before reset,wait for starting! ...."           start     fi         curl -d log=aaa  ${wiremock_url}/__admin/mappings/reset     echo "Reset success!......" fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960

其中: 「nohup java -jar wiremock j ar−−verbose=true−−port= wiremockjar−−verbose=true−−port={wiremock_jar} --verbose=true --port={port} &」:在linux系統後臺運行WireMock; 「curl -d log=aaa ${wiremock_url}/__admin/mappings/reset」:是經過發送POST請求,從新加載新生成的配置文件。

 

五、總結

Mock API接口是很是必要的,由於不一樣研發組的系統之間的數據交互每每是經過接口來實現,當不一樣組接口開發不一樣步時,接口測試沒法及早參與,對接調試比較困難。這樣勢必致使軟件開發迭代變慢,沒有時間對質量進行充分驗證。 能夠借鑑《自動化單元測試實踐之路》在單元測試中,使用Mockito對依賴進行Mock,那一樣道理,使用Mock技術也能夠對HTTP API進行Mock,按照這個思路探索下去,看看有沒有開源解決方案,是否可以解決當前問題,若是能夠就不用重複寫一套解決方案;若是不行,那可否基於開源的作二次開發呢?

六、參考文檔

http://wiremock.org/docs/ http://www.infoq.com/cn/articles/evolution-of-httpservermock-from-hand-to-platform/ ———————————————— 版權聲明:本文爲CSDN博主「liuchunming033」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。 原文連接:https://blog.csdn.net/liuchunming033/article/details/52399397

相關文章
相關標籤/搜索