Kiểm thử giao diện có thể sử dụng Groovy như các kịch bản tiền xử lý và hậu xử lý để truyền tham số giữa các giao diện, tích hợp liền mạch với cú pháp Java. Việc đưa Groovy vào giúp việc thiết lập tham số hóa động trở nên tiện lợi rất nhiều.
Phần cốt lõi là tích hợp động cơ Groovy, dưới đây là logic triển khai động cơ.
- Phụ thuộc cốt lõi Groovy trong tệp pom
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>groovy-sandbox</artifactId>
<version>1.19</version>
</dependency>
- Thêm các import thường dùng vào động cơ Groovy Trong khối mã tĩnh
Một số phụ thuộc cơ bản như: JSONObject, JSONArray, JsonPath và các lớp công cụ khác
static {
config = new CompilerConfiguration();
// Thêm import mặc định
config.addCompilationCustomizers(new ImportCustomizer().addImports(
"com.taltools.script.exception.StepFailureException",
"com.jayway.jsonpath.JsonPath",
"com.alibaba.fastjson.JSONObject",
"com.alibaba.fastjson.JSONArray",
"groovy.json.JsonSlurper",
"org.apache.commons.codec.digest.DigestUtils",
"org.apache.commons.codec.digest.HmacUtils"));
// Thêm bộ ngắt luồng thực thi
config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt.class));
// Thêm bộ ngắt luồng thực thi có thể ngắt luồng hết thời gian, thời gian chờ được định nghĩa là 30s
config.addCompilationCustomizers(new ASTTransformationCustomizer(Collections.singletonMap("value", INTERRUPT_TIME_OUT), TimedInterrupt.class));
// Môi trường hộp cát
config.addCompilationCustomizers(new SandboxTransformer());
NO_RUNTIME_SANDBOX = new NoRuntimeSandbox();
NO_SYSTEM_HARM_SANDBOX = new NoSystemHarmSandbox();
}
- Thiết lập dung lượng bộ nhớ đệm & thời gian hết hạn
{
lruCache = CacheBuilder.newBuilder()
.maximumSize(1000) // dung lượng tối đa
.expireAfterAccess(12, TimeUnit.HOURS) // thời gian hết hạn của bộ nhớ đệm
.concurrencyLevel(Runtime.getRuntime().availableProcessors())// đặt cấp độ đồng thời bằng số nhân CPU
.build();
}
- Triển khai cốt lõi Groovy, ràng buộc tham số ngữ cảnh
- Ràng buộc tên biến tham số ngữ cảnh
@Override
public ScriptContext runScript(String scriptContent, ScriptContext context) {
if (scriptContent == null || scriptContent.isEmpty()) {
throw new IllegalArgumentException("Nội dung script đầu vào không được để trống");
}
log.debug("Thực thi script Groovy: {}", scriptContent);
Binding binding = generateBinding(context);
parseScript(scriptContent, binding).run();
ScriptContext retContext = new ScriptContext();
retContext.setVariables(binding.getVariables());
return retContext;
}
public long getCacheCount() {
return lruCache.size();
}
protected Script parseScript(String scriptContent, Binding binding) {
String md5 = DigestUtils.md5Hex(scriptContent);
String sha1 = DigestUtils.sha1Hex(scriptContent);
String key = md5 + "-" + sha1;
Class<? extends Script> scriptClass = lruCache.getIfPresent(key);
if (scriptClass == null) {
registerSandbox();
GroovyShell shell = new GroovyShell(config);
Script script = shell.parse(scriptContent);
scriptClass = script.getClass();
lruCache.put(key, scriptClass);
log.debug("Không tìm thấy script trong bộ nhớ đệm LRU, tạo đối tượng script và lưu vào bộ nhớ đệm, số lượng bộ nhớ đệm hiện tại: {}", getCacheCount());
} else {
log.debug("Tìm thấy script trong bộ nhớ đệm LRU, key: {}, số lượng bộ nhớ đệm hiện tại: {}", key, getCacheCount());
}
return InvokerHelper.createScript(scriptClass, binding);
}
- Thử nghiệm Động cơ Groovy với việc đặt tên tham số
- Trong thử nghiệm đơn vị, kiểm tra giá trị trả về của script Groovy
@Test
public void testGroovy(){
String req = " outputData['ten'] = testGroovy();\n" +
" static String testGroovy(){\n" +
" def ten = 'Groovy'\n" +
" def chao = \"Chào ${ten}\"\n" +
" return chao\n" +
" }";
GroovyEngine engine = new GroovyEngine();
ScriptContext context = new ScriptContext();
LinkedHashMap<String, Object> outputData = new LinkedHashMap<>();
context.setVariable("outputData",outputData);
ScriptContext ret = engine.runScript(req,context);
System.out.println(JsonUtils.obj2json(ret));
System.out.println(outputData);
}
- Kết quả in ra bảng điều khiển