java-commons/muscript-gson/src/test/java/io/gitlab/jfronny/muscript/gson/test/JsonTest.java

59 lines
2.1 KiB
Java
Raw Normal View History

package io.gitlab.jfronny.muscript.gson.test;
import io.gitlab.jfronny.commons.serialize.gson.api.v2.GsonHolders;
import io.gitlab.jfronny.muscript.StandardLib;
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)))));
assertEquals("[true,12,\"7\"]", serialize(of(of(true), of(12), of(7).asString())));
}
@Test
void simpleDeserialize() {
assertEquals(of("Yes"), deserialize("\"Yes\"", Dynamic.class));
assertEquals(of(Map.of("key", of(3))), deserialize("{\"key\":3}", Dynamic.class));
assertEquals(of(of(true), of(12), of(7).asString()), deserialize("[true,12,\"7\"]", Dynamic.class));
}
@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);
}
}