2023-08-25 16:24:28 +02:00
|
|
|
package io.gitlab.jfronny.muscript.gson.test;
|
|
|
|
|
|
|
|
import io.gitlab.jfronny.commons.serialize.gson.api.v2.GsonHolders;
|
2023-09-21 19:28:17 +02:00
|
|
|
import io.gitlab.jfronny.muscript.libs.StandardLib;
|
2023-08-25 16:24:28 +02:00
|
|
|
import io.gitlab.jfronny.muscript.compiler.Parser;
|
|
|
|
import io.gitlab.jfronny.muscript.data.Scope;
|
|
|
|
import io.gitlab.jfronny.muscript.data.dynamic.Dynamic;
|
|
|
|
import io.gitlab.jfronny.muscript.data.dynamic.additional.DFinal;
|
|
|
|
import io.gitlab.jfronny.muscript.gson.GsonLib;
|
|
|
|
import org.junit.jupiter.api.Test;
|
|
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
|
import static io.gitlab.jfronny.muscript.data.dynamic.additional.DFinal.of;
|
|
|
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
|
|
|
|
|
|
class JsonTest {
|
|
|
|
@Test
|
|
|
|
void simpleSerialize() {
|
|
|
|
assertEquals("\"Yes\"", serialize(of("Yes")));
|
|
|
|
assertEquals("{\"key\":3}", serialize(of(Map.of("key", of(3)))));
|
2023-09-21 19:08:14 +02:00
|
|
|
assertEquals("[true,12,7]", serialize(of(of(true), of(12), of(7).asString()))); // string lens ignored
|
2023-08-25 16:24:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@Test
|
|
|
|
void simpleDeserialize() {
|
|
|
|
assertEquals(of("Yes"), deserialize("\"Yes\"", Dynamic.class));
|
|
|
|
assertEquals(of(Map.of("key", of(3))), deserialize("{\"key\":3}", Dynamic.class));
|
2023-09-21 19:08:14 +02:00
|
|
|
assertEquals(of(of(true), of(12), of("7")), deserialize("[true,12,\"7\"]", Dynamic.class));
|
2023-08-25 16:24:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@Test
|
|
|
|
void muscriptDSL() {
|
|
|
|
assertEquals("{\"key\":\"One\",\"key2\":3}", execute("{key = 'One', key2 = 3}::toJson()").asString().getValue());
|
|
|
|
assertEquals(of(Map.of("key", of(3), "value", of(false))), execute("args[0]::fromJson()", "{\"key\": 3, \"value\": false}"));
|
|
|
|
}
|
|
|
|
|
|
|
|
private Scope createScope() {
|
|
|
|
return GsonLib.addTo(StandardLib.createScope());
|
|
|
|
}
|
|
|
|
|
|
|
|
private Dynamic execute(String source, String... args) {
|
|
|
|
return Parser.parse(source)
|
|
|
|
.asDynamicExpr()
|
|
|
|
.get(createScope()
|
|
|
|
.set("args", DFinal.of(Arrays.stream(args).map(DFinal::of).toList()))
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
private String serialize(Object object) {
|
|
|
|
return GsonHolders.API.getGson().toJson(object);
|
|
|
|
}
|
|
|
|
|
|
|
|
private <T> T deserialize(String source, Class<T> klazz) {
|
|
|
|
return GsonHolders.API.getGson().fromJson(source, klazz);
|
|
|
|
}
|
|
|
|
}
|