項目中想要用allure作爲報告測試模板但是發現官網文檔上java沒有像python一樣給出監聽log方法
所以找了一些資料查了一下發現這種方式算是比較簡單的添加日誌信息的的方法 如果哪位大神有直接監聽log方法 麻煩發一份到我郵箱 不勝感激 郵箱:[email protected]
/**
監聽器
**/
import io.qameta.allure.Attachment;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class TestFailListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
// takePhoto();
saveLog("123");
}
@Attachment(value = "screen shot",type = "image/png")
public byte[] takePhoto(){
/*
BaseTester 基類中的driver 無法調用driver截圖只能直接截圖
byte[] screenshotAs = ((TakesScreenshot)BaseTester.driver).getScreenshotAs(OutputType.BYTES);
return screenshotAs;*/
return null;
}
@Attachment()
public String saveLog(String mesg){
return mesg;
}
}
/**
自己封裝的加入到附件的報文信息格式
**/
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.qameta.allure.Attachment;
import org.apache.commons.lang3.StringUtils;
public class TestStep {
public static void requestAndRespondBody(String URL, String Body,String Respond){
requestBody(URL,Body);
respondBody(Respond);
}
@Attachment("請求報文")
public static String requestBody(String URL, String body) {
String str=getStr(body);
if(body!=null&&!body.equals("")){
//報告展現請求報文
return URL+"\n"+str;
}else{
return URL+"\n";
}
}
@Attachment("響應報文")
public static String respondBody(String respond) {
//報告展現響應報文
return getStr(respond);
}
@Attachment("數據庫斷言結果")
public static StringBuffer databaseAssertResult(StringBuffer assertResult){
//報告展現數據庫斷言結果
return assertResult;
}
@Attachment("響應報文斷言結果")
public static StringBuffer assertRespond(StringBuffer assertResult){
//報告展現數據庫斷言結果
return assertResult;
}
/**
* 判斷字符串是否可以轉化爲json對象
* @param content
* @return
*/
public static boolean isJsonObject(String content) {
// 此處應該注意,不要使用StringUtils.isEmpty(),因爲當content爲" "空格字符串時,JSONObject.parseObject可以解析成功,
// 實際上,這是沒有什麼意義的。所以content應該是非空白字符串且不爲空,判斷是否是JSON數組也是相同的情況。
if(StringUtils.isBlank(content))
return false;
try {
JSONObject jsonStr = JSONObject.parseObject(content);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 判斷字符串是否可以轉化爲JSON數組
* @param content
* @return
*/
public static boolean isJsonArray(String content) {
if(StringUtils.isBlank(content))
return false;
StringUtils.isEmpty(content);
try {
JSONArray jsonStr = JSONArray.parseArray(content);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 根據str轉json 轉不成功 返回str
* @param str
*/
public static String getStr(String body){
String str=null;
boolean prettyFormat = true; //格式化輸出
if(isJsonObject(body)){
JSONObject jsonObject = JSONObject.parseObject(body);
str = JSONObject.toJSONString(jsonObject,prettyFormat);
}else if(isJsonArray(body)){
JSONArray array = JSONObject.parseArray(body);
str=JSON.toJSONString(array,prettyFormat);
}else{
str=body;
}
return str;
}
}
在接口請求工具類中使用TestStep進行記錄請求報文響應報文
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.onlyedu.provider.basic.ChangeCampusBusiness;
import org.apache.log4j.Logger;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.onlyedu.provider.basic.BasicClass.basicUrl;
/**
* 請求接口工具類
*/
@Component
public class RequestUtils {
public static Logger logger=Logger.getLogger(RequestUtils.class);
private static ChangeCampusBusiness ccb = new ChangeCampusBusiness();
/**
* 登陸後返回cookie值
* @param url
* @param map
* @param restTemplate
* @return
*/
public static List<String> login(String url, HashMap<String,Object> map, RestTemplate restTemplate){
String parameters=mapToString(map);
logger.debug("開始登陸:參數:"+parameters);
ResponseEntity responseEntity =restTemplate.postForEntity(url,parameters,String.class);
HttpHeaders headers= responseEntity.getHeaders();
List<String> cookie = headers.get("Set-Cookie");
logger.debug("成功登陸:返回cookie:"+cookie);
return cookie;
}
/**
* POST方式請求接口
* @param url
* @param map
* @param restTemplate
* @return
*/
public static JSONObject requestByPOST (String url,Map<String,Object> map,RestTemplate restTemplate,HttpHeaders headers){
// result=restTemplate.postForEntity(basicUrl+"/api/login",parameter,String.class);
//發送請求
changeCampus(restTemplate,headers);
HttpEntity<MultiValueMap<String,Object>> request = getHttpEntity(map,headers);
logger.info("***********************發送Post請求 url=+"+url+":參數:"+request.toString());
String responseBody=null;
try {
responseBody =restTemplate.exchange(url,HttpMethod.POST,request,String.class).getBody();
TestStep.requestAndRespondBody(url,request.toString(),responseBody);
}catch (HttpStatusCodeException exception){
getErrMsg(exception,url,request.toString());
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(responseBody);
}
/**
* 根據get方式請求接口
* @param url
* @param map
* @param restTemplate
* @return
*/
public static JSONObject requestByGet(String url,Map<String,Object> map, RestTemplate restTemplate,HttpHeaders headers){
// header填充
changeCampus(restTemplate,headers);
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity(null,headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
String responseBody=null;
String reallyUrl=null;
try {
//如果存在參數
if(map!=null&& !map.isEmpty()){
for (Map.Entry<String,Object> e:
map.entrySet()) {
//構建查詢參數
builder.queryParam(e.getKey(),e.getValue());
}
//拼接好參數後的URl//test.com/url?param1={param1}¶m2={param2};
reallyUrl=builder.build().toString();
logger.info("***********************發送get請求 url=+"+reallyUrl);
responseBody =restTemplate.exchange(reallyUrl,HttpMethod.GET,request,String.class).getBody();
}else{
//不存在參數
reallyUrl=url;
responseBody=restTemplate.exchange(reallyUrl,HttpMethod.GET,request,String.class).getBody();
logger.info("***********************發送get請求 url=+"+url+"無參數");
}
TestStep.requestAndRespondBody(reallyUrl,"",responseBody);
}catch (HttpStatusCodeException exception) {
getErrMsg(exception,reallyUrl,"");
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(responseBody);
}
/**
* g根據put方式請求接口
* @param url
* @param map
* @param restTemplate
* @param headers
* @return
*/
public static JSONObject requestByPUT(String url,Map<String,Object> map, RestTemplate restTemplate,HttpHeaders headers){
HttpEntity<MultiValueMap<String,Object>> request = getHttpEntity(map,headers);
String body=null;
try {
logger.info("***********************發送put請求 url=+"+url+"參數:"+request.toString());
changeCampus(restTemplate,headers);
body = restTemplate.exchange(url, HttpMethod.PUT, request, String.class).getBody();
TestStep.requestAndRespondBody(url,request.toString(),body);
}catch (HttpStatusCodeException exception){
getErrMsg(exception,url,request.toString());
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(body);
}
/**
* delete請求
* @param url
* @param map
* @param restTemplate
* @param headers
* @return
*/
public static JSONObject requestByDelete(String url,Map<String,Object> map, RestTemplate restTemplate,HttpHeaders headers){
changeCampus(restTemplate,headers);
HttpEntity<MultiValueMap<String,Object>> request =getHttpEntity(map,headers);
String responseBody=null;
try {
logger.info("***********************發送del請求 url=+"+url+"參數:"+request.toString());
responseBody =restTemplate.exchange(url,HttpMethod.DELETE,request,String.class).getBody();
TestStep.requestAndRespondBody(url,request.toString(),responseBody);
}catch (HttpStatusCodeException exception){
getErrMsg(exception,url,request.toString());
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(responseBody);
}
/**
* patch請求
* @param url
* @param parameter
* @param restTemplate
* @param headers
* @return
*/
public static JSONObject requestByPatch(String url, Map parameter, RestTemplate restTemplate, HttpHeaders headers) {
changeCampus(restTemplate,headers);
HttpEntity<MultiValueMap<String,Object>> request =getHttpEntity(parameter,headers);
String responseBody=null;
try {
logger.info("***********************發送put請求 url=+"+url+"參數:"+request.toString());
responseBody =restTemplate.exchange(url,HttpMethod.PATCH,request,String.class).getBody();
TestStep.requestAndRespondBody(url,request.toString(),responseBody);
}catch (HttpStatusCodeException exception){
getErrMsg(exception,url,request.toString());
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(responseBody);
}
/**
* 將responseEntity轉成JSONOBject 如果狀態碼不是200則拋出異常
* @param entity
* @return
*/
public static JSONObject getJSONObjectForResponseEntity(String entity){
if(entity==null){
logger.error("***********************返回數據爲空");
throw new RuntimeException("服務器數據返回異常entity爲空");
}
logger.info("***********************返回數據"+entity);
//restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("userName", "password"));
if(entity.equals("true")){
return null;
}
JSONObject json=null;
Object ob = JSON.parse(entity);
if(ob instanceof JSONObject){
json = JSON.parseObject(entity);
}else{
logger.info("返回不是jsonObj數據進行強制轉換"+entity);
//如果不是jsonObject強行返回
JSONArray arra=JSON.parseArray(entity);
json=new JSONObject();
json.put("data",arra);
logger.info("數據轉換完成***************"+json);
}
return json;
}
/**
* 將map轉成String
* @param map
* @return
*/
public static String mapToString(Map map){
for (Object entity:map.keySet()) {
if("".equals(entity)){
return(String) map.get("");
}
}
return JSONObject.toJSONString(map);
}
public static void getErrMsg(HttpStatusCodeException exception,String url,String parameter){
HttpStatus statusCode = exception.getStatusCode();
byte [] bytes= exception.getResponseBodyAsByteArray();
String msg = null;
try {
msg = new String(bytes,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
logger.error("***********************發生運行時異常"+msg);
String errMsg="運行時發生異常"+msg+"返回狀態碼"+statusCode;
TestStep.requestAndRespondBody(url,parameter,errMsg);
}
/**
* 根據parameter headers 生成HTTPEntity
* @param parameter
* @param headers
* @return
*/
public static HttpEntity<MultiValueMap<String,Object>> getHttpEntity(Map parameter,HttpHeaders headers){
String param=null;
if(parameter!=null){
param=mapToString(parameter);
}
//把headers加進去
return new HttpEntity(param,headers);
}
public static void changeCampus(RestTemplate restTemplate,HttpHeaders headers){
//切換校區
logger.info("防止緩存切換校區校區ID:Campu_HuaMu__ZLF");
HashMap<String,Object> map=new HashMap<>();
map.put("businessUnitId", "BusUn00001024ZLF");
ccb.changeCampus(restTemplate, map, basicUrl + "/api/user/institution/departments/Campu_HuaMu__ZLF/change", headers);
}
public static JSONObject requestByGet1(String url,Map<String,Object> map, RestTemplate restTemplate,HttpHeaders headers){
// header填充
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity(null,headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
String responseBody=null;
String reallyUrl=null;
try {
//如果存在參數
if(map!=null&& !map.isEmpty()){
for (Map.Entry<String,Object> e:
map.entrySet()) {
//構建查詢參數
builder.queryParam(e.getKey(),e.getValue());
}
//拼接好參數後的URl//test.com/url?param1={param1}¶m2={param2};
reallyUrl=builder.build().toString();
logger.info("***********************發送get請求 url=+"+reallyUrl);
responseBody =restTemplate.exchange(reallyUrl,HttpMethod.GET,request,String.class).getBody();
}else{
//不存在參數
reallyUrl=url;
responseBody=restTemplate.exchange(reallyUrl,HttpMethod.GET,request,String.class).getBody();
logger.info("***********************發送get請求 url=+"+url+"無參數");
}
TestStep.requestAndRespondBody(reallyUrl,"",responseBody);
}catch (HttpStatusCodeException exception) {
getErrMsg(exception,reallyUrl,"");
exception.printStackTrace();
}
return getJSONObjectForResponseEntity(responseBody);
}
}