项目中想要用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);
}
}