2015-11-03 61 views
0

我有一些REST端點和很少[asmx/svc]端點。 其中一些是GET,其他的是POST操作。端點的健康檢查 - 快速和骯髒的版本

我正試圖將快速和骯髒,可重複的健康檢查序列放在一起,以查找所有端點是否響應或是否有任何故障。 基本上要麼得到200或201,否則報告錯誤。

這樣做最簡單的方法是什麼?

回答

0

SOAPUI在內部使用apache http-client 4.1.1版本,您可以在groovy腳本testStep中使用它來執行您的檢查。

添加一個groovy腳本testStep到你的testCase裏面使用下面的代碼;如果它返回HTTP狀態200201認爲它正在工作,如果返回http-status 405(方法不允許),那麼它會嘗試使用POST執行相同的狀態代碼檢查,否則會被視爲關閉。

注意,一些服務可以但是運行可以返回例如400(錯誤請求)如果請求是不正確的,所以想想,如果你需要重新考慮你想要執行檢查的方式或添加一些其他的狀態碼考慮服務器是否正常運行。

import org.apache.http.HttpEntity 
import org.apache.http.HttpResponse 
import org.apache.http.client.methods.HttpGet 
import org.apache.http.client.methods.HttpPost 
import org.apache.http.impl.client.DefaultHttpClient 

// urls to check 
def urls = ['http://google.es','http://stackoverflow.com'] 

// apache http-client to use in closue 
DefaultHttpClient httpclient = new DefaultHttpClient() 

// util function to get the response 
def getStatus = { httpMethod -> 
    HttpResponse response = httpclient.execute(httpMethod) 
    // consume the entity to avoid error with http-client 
    if(response.getEntity() != null) { 
     response.getEntity().consumeContent(); 
    } 

    return response.getStatusLine().getStatusCode() 
} 

HttpGet httpget; 
HttpPost httppost; 

// finAll urls that are working 
def urlsWorking = urls.findAll { url -> 
    log.info "try GET for $url" 
    httpget = new HttpGet(url) 
    def status = getStatus(httpget) 

    // if status are 200 or 201 it's correct 
    if(status in [200,201]){ 
     log.info "$url is OK" 
     return true 
    // if GET is not allowed try with POST 
    }else if(status == 405){ 
     log.info "try POST for $url" 
     httppost = new HttpPost(url) 
     status = getStatus(httpget) 

     // if status are 200 or 201 it's correct 
     if(status in [200,201]){ 
      log.info "$url is OK" 
      return true 
     } 

     log.info "$url is NOT working status code: $status" 
     return false 
    }else{ 
     log.info "$url is NOT working status code: $status" 
     return false 
    } 
} 

// close connection to release resources 
httpclient.getConnectionManager().shutdown() 

log.info "URLS WORKING:" + urlsWorking 

此腳本日誌:

Tue Nov 03 22:37:59 CET 2015:INFO:try GET for http://google.es 
Tue Nov 03 22:38:00 CET 2015:INFO:http://google.es is OK 
Tue Nov 03 22:38:00 CET 2015:INFO:try GET for http://stackoverflow.com 
Tue Nov 03 22:38:03 CET 2015:INFO:http://stackoverflow.com is OK 
Tue Nov 03 22:38:03 CET 2015:INFO:URLS WORKING:[http://google.es, http://stackoverflow.com] 

希望它能幫助,