MeterSphere使用之自定义代码段


//登录
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import org.apache.http.HttpResponse;

import com.alibaba.fastjson.JSONObject;
//创建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
//参数
String payload = "salesman_no=202107&pwd=Aa111111"; //这里用自己的昆仑登录账号
//定义请求的参数
URI uri = new URIBuilder().setScheme("https").setHost("test-bx.qjbxtech.com").setPath("/manage/kunlun/login").build();
//创建http请求
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/x-www-form-urlEncoded");
request.setEntity(new StringEntity(StringEscapeUtils.unescapeJava(payload)));
log.info("请求地址"+uri.toString());
HttpResponse response = httpClient.execute(request);
//判断状态是否是200
log.info("状态码=="+response.getStatusLine().getStatusCode());
String access_code = "";
if(response.getStatusLine().getStatusCode()==200){
   String result = EntityUtils.toString(response.getEntity());
   JSONObject jo = JSONObject.parseObject(result);
   access_code = jo.getJSONObject("data").getString("access_code");
   log.info("token的值==="+access_code);

}
vars.put("access_code", access_code);
//断言全部列表
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;

String result = prev.getResponseDataAsString();
log.info("接口返回值:"+result);
// 1.json字符串转json对象
JSONObject jsonObject = JSONObject.parseObject(result);
log.info("接口返回值json对象:"+jsonObject);
// 2.获取data部分对象
jsonObject = jsonObject.getJSONObject("data");
// data中的内容带有中括号[],所以要转化为JSONArray类型的对象
JSONArray data = jsonObject.getJSONArray("data");
//定义一个集合
List  list = new ArrayList();
for (int i = 0; i < data.size(); i++) {
        JSONObject ob = (JSONObject) data.get(i);// 得到json对象;
        data_value = ob.getString("cus_id"); // cus_id 这个值会变化,根据响应结果中你想断言的字段进行提取
        list.add(data_value);

}
log.info("list值:" + list);
HashSet set = new HashSet(list);
list.clear();
list.addAll(set);
log.info("去重后的list值:" + list);
int size = list.size();//集合的长度
int flag = 0;
if (size > 1) {
        flag = 0;
} else {
        flag = 1;
}
log.info("flag值:" + flag);

vars.put("flag",String.valueOf(flag));

value = vars.get("flag");

result = "1".equals(value);
log.info("result的值=="+result);
if (!result){
	msg = "assertion [" + value + " == '1']: false;";
	AssertionResult.setFailureMessage(msg);
	AssertionResult.setFailure(true);
}

你可能感兴趣的:(metersphere)