refactor(接口测试): 优化json中包含mock数据的处理逻辑

This commit is contained in:
wxg0103 2023-03-13 19:06:09 +08:00 committed by wxg0103
parent 29e805d972
commit 497654d673
2 changed files with 23 additions and 18 deletions

View File

@ -22,6 +22,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Data
@ -90,37 +92,39 @@ public class Body {
private void parseMock() {
if (StringUtils.isNotEmpty(this.getRaw())) {
String value = StringUtils.chomp(this.getRaw().trim());
if (StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) {
List list = JSON.parseArray(this.getRaw());
if (!this.getRaw().contains(ElementConstants.REF)) {
jsonMockParse(list);
try {
if (StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) {
List list = JSON.parseArray(this.getRaw());
if (!this.getRaw().contains(ElementConstants.REF)) {
jsonMockParse(list);
}
this.raw = JSONUtil.parserArray(JSONUtil.toJSONString(list));
} else {
Map<String, Object> map = JSON.parseObject(this.getRaw(), Map.class);
if (!this.getRaw().contains(ElementConstants.REF)) {
jsonMockParse(map);
}
this.raw = JSONUtil.parserObject(JSONUtil.toJSONString(map));
}
this.raw = JSONUtil.toJSONString(list);
} else {
Map<String, Object> map = JSON.parseObject(this.getRaw(), Map.class);
if (!this.getRaw().contains(ElementConstants.REF)) {
jsonMockParse(map);
} catch (Exception e) {
String pattern = "@[a-zA-Z]*";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(this.raw);
while (matcher.find()) {
this.raw = this.raw.replace(matcher.group(), "${__Mock(" + matcher.group() + ")}");
}
this.raw = JSONUtil.toJSONString(map);
}
}
}
private void analyticalData() {
try {
boolean isArray = false;
if (StringUtils.isNotBlank(this.type) && StringUtils.equals(this.type, JSON_STR)) {
if (StringUtils.isNotEmpty(this.format) && this.getJsonSchema() != null && JSON_SCHEMA.equals(this.format)) {
this.raw = StringEscapeUtils.unescapeJava(JSONSchemaBuilder.generator(JSONUtil.toJSONString(this.getJsonSchema())));
} else {
parseMock();
}
// 格式化处理
if (isArray) {
this.raw = JSONUtil.parserArray(this.raw);
} else {
this.raw = JSONUtil.parserObject(this.raw);
}
}
} catch (Exception e) {
LoggerUtil.error("json mock value is abnormal", e);

View File

@ -61,6 +61,7 @@ public class JSONSchemaBuilder {
String str = ScriptEngineUtils.calculate(evlValue);
switch (evlValue) {
case "@integer":
case "@natural":
concept.put(propertyName, NumberUtils.parseNumber(str, Long.class));
break;
case "@boolean":
@ -169,7 +170,7 @@ public class JSONSchemaBuilder {
}
public static void processArrayValue(Map<String, String> map, String value) {
String key = StringUtils.join("\"",value, "\"");
String key = StringUtils.join("\"", value, "\"");
String targetValue = StringUtils.join(value);
map.put(key, targetValue);
}