Initialize Compose Launcher source and deployment
This commit is contained in:
commit
12a8c24441
77 files changed
+9594
No files matched your search
@@ -0,0 +1,24 @@
|
||||
package com.ttstd.launcher;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
|
||||
class LauncherApplicationTest {
|
||||
@TempDir Path temp;
|
||||
|
||||
@Test
|
||||
void startsAndSeedsNewDatabase() throws Exception {
|
||||
try (var context = new SpringApplicationBuilder(LauncherApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.run("--launcher.admin-token=test-launcher-admin-token-24",
|
||||
"--launcher.device-token=test-launcher-device-token-24",
|
||||
"--launcher.database=" + temp.resolve("new.sqlite"))) {
|
||||
assertEquals(1, context.getBean(LayoutStore.class).latest().revision());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.ttstd.launcher;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
class LayoutApiTest {
|
||||
private static final String ADMIN = "Bearer test-launcher-admin-token-24";
|
||||
private static final String DEVICE = "Bearer test-launcher-device-token-24";
|
||||
private static final String ADMIN_LAYOUT = "/api/admin/layout";
|
||||
private final JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
@TempDir Path dir;
|
||||
|
||||
@Test
|
||||
void migratedDatabaseRetainsLayoutsAndSupportsPublishRollbackAndRestart() throws Exception {
|
||||
Path database = dir.resolve("layouts.sqlite");
|
||||
String legacyLayout;
|
||||
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
|
||||
legacyLayout = new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute("""
|
||||
CREATE TABLE releases (
|
||||
revision INTEGER PRIMARY KEY CHECK (revision BETWEEN 1 AND 2147483647),
|
||||
layout TEXT NOT NULL,
|
||||
publishedAt TEXT NOT NULL,
|
||||
restoredFrom INTEGER REFERENCES releases(revision)
|
||||
) STRICT
|
||||
""");
|
||||
try (var insert = connection.prepareStatement("INSERT INTO releases VALUES (1, ?, '2026-01-01T00:00:00.000Z', NULL)")) {
|
||||
insert.setString(1, legacyLayout);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
MockMvc mvc = mvc(database);
|
||||
var editor = mvc.perform(get("/")).andExpect(status().isOk()).andReturn().getResponse();
|
||||
assertTrue(editor.getHeader("Content-Security-Policy").contains("script-src 'self'"));
|
||||
String html = editor.getContentAsString(StandardCharsets.UTF_8);
|
||||
assertEquals(html, mvc.perform(get("/canvas.html")).andExpect(status().isOk())
|
||||
.andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8));
|
||||
var js = Pattern.compile("src=\"\\./(assets/[^\"]+\\.js)\"").matcher(html);
|
||||
assertTrue(js.find());
|
||||
mvc.perform(get("/" + js.group(1))).andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith("text/javascript"));
|
||||
var css = Pattern.compile("href=\"\\./(assets/[^\"]+\\.css)\"").matcher(html);
|
||||
assertTrue(css.find());
|
||||
mvc.perform(get("/" + css.group(1))).andExpect(status().isOk())
|
||||
.andExpect(content().contentTypeCompatibleWith("text/css"));
|
||||
mvc.perform(get("/assets/invalid.js")).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/healthz")).andExpect(status().isOk());
|
||||
mvc.perform(get("/api/layout")).andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string("WWW-Authenticate", "Bearer"));
|
||||
mvc.perform(get("/api/admin/history").header("Authorization", DEVICE)).andExpect(status().isUnauthorized());
|
||||
|
||||
var original = mvc.perform(get("/api/layout").header("Authorization", DEVICE))
|
||||
.andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "1"))
|
||||
.andReturn().getResponse();
|
||||
assertEquals(legacyLayout, original.getContentAsString(StandardCharsets.UTF_8));
|
||||
String tag = original.getHeader("ETag");
|
||||
assertEquals(new LayoutStore.Release(1, legacyLayout).etag(), tag);
|
||||
mvc.perform(get("/api/layout").header("Authorization", DEVICE).header("If-None-Match", tag))
|
||||
.andExpect(status().isNotModified()).andExpect(header().string("ETag", tag));
|
||||
|
||||
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(legacyLayout)).andExpect(status().isPreconditionRequired());
|
||||
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{} {}")).andExpect(status().isBadRequest());
|
||||
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content(new byte[LayoutStore.MAX_BYTES + 1]))
|
||||
.andExpect(status().is(413));
|
||||
var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"schemaVersion\":2,\"pages\":[]}"))
|
||||
.andExpect(status().is(422)).andReturn().getResponse();
|
||||
assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").size() >= 2);
|
||||
|
||||
var changed = (ObjectNode) mapper.readTree(legacyLayout);
|
||||
changed.put("futureField", "同步验证");
|
||||
String body = mapper.writeValueAsString(changed);
|
||||
Callable<Integer> publish = () -> mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN)
|
||||
.header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content(body))
|
||||
.andReturn().getResponse().getStatus();
|
||||
var executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
var outcomes = executor.invokeAll(List.of(publish, publish));
|
||||
assertEquals(List.of(200, 412), List.of(outcomes.get(0).get(), outcomes.get(1).get()).stream().sorted().toList());
|
||||
} finally {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
|
||||
var posted = mvc.perform(get("/api/admin/history/2").header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse();
|
||||
assertEquals("同步验证", mapper.readTree(posted.getContentAsByteArray()).path("futureField").stringValue());
|
||||
assertNotNull(posted.getHeader("ETag"));
|
||||
mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
|
||||
.header("If-Match", posted.getHeader("ETag")).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"revision\":1}"))
|
||||
.andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "3"));
|
||||
|
||||
MockMvc restarted = mvc(database);
|
||||
var history = restarted.perform(get("/api/admin/history").header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse();
|
||||
var revisions = mapper.readTree(history.getContentAsByteArray()).path("revisions");
|
||||
assertEquals(3, revisions.size());
|
||||
assertEquals(1, revisions.get(0).path("restoredFrom").intValue());
|
||||
var latest = restarted.perform(get("/api/layout").header("Authorization", DEVICE))
|
||||
.andExpect(status().isOk()).andReturn().getResponse();
|
||||
assertEquals(((ObjectNode) mapper.readTree(legacyLayout)).put("revision", 3),
|
||||
mapper.readTree(latest.getContentAsByteArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorsAreReturnedAsJson() throws Exception {
|
||||
MockMvc mvc = mvc(dir.resolve("errors.sqlite"));
|
||||
var unauthorized = mvc.perform(get(ADMIN_LAYOUT)).andExpect(status().isUnauthorized())
|
||||
.andReturn().getResponse();
|
||||
assertEquals("访问令牌无效", message(unauthorized.getContentAsByteArray()));
|
||||
|
||||
var wrongMethod = mvc.perform(post("/healthz")).andExpect(status().isMethodNotAllowed())
|
||||
.andReturn().getResponse();
|
||||
assertEquals("不支持的请求方法", message(wrongMethod.getContentAsByteArray()));
|
||||
|
||||
var badPage = mvc.perform(get("/api/admin/history").header("Authorization", ADMIN).param("before", "abc"))
|
||||
.andExpect(status().isBadRequest()).andReturn().getResponse();
|
||||
assertEquals("无效的分页参数", message(badPage.getContentAsByteArray()));
|
||||
|
||||
var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
|
||||
var badRevision = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
|
||||
.header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":0}"))
|
||||
.andExpect(status().isBadRequest()).andReturn().getResponse();
|
||||
assertEquals("无效的回滚版本号", message(badRevision.getContentAsByteArray()));
|
||||
|
||||
var missing = mvc.perform(get("/api/admin/history/999").header("Authorization", ADMIN))
|
||||
.andExpect(status().isNotFound()).andReturn().getResponse();
|
||||
assertEquals("该版本不存在", message(missing.getContentAsByteArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyIsPagedWithNextBefore() throws Exception {
|
||||
Path database = dir.resolve("paged.sqlite");
|
||||
var store = new LayoutStore(database.toString(), mapper, new LayoutValidator());
|
||||
String layout = store.latest().layout();
|
||||
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
|
||||
var insert = connection.prepareStatement("""
|
||||
INSERT INTO releases (revision, layout, publishedAt, restoredFrom) VALUES (?, ?, ?, NULL)
|
||||
""")) {
|
||||
for (int revision = 2; revision <= 101; revision++) {
|
||||
insert.setInt(1, revision);
|
||||
insert.setString(2, layout);
|
||||
insert.setString(3, "2026-01-01T00:00:00Z");
|
||||
insert.executeUpdate();
|
||||
}
|
||||
}
|
||||
MockMvc mvc = mvc(database);
|
||||
var first = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertEquals(50, first.path("revisions").size());
|
||||
assertEquals(101, first.path("revisions").get(0).path("revision").intValue());
|
||||
assertEquals(52, first.path("nextBefore").intValue());
|
||||
|
||||
var second = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN)
|
||||
.param("before", "52")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertEquals(50, second.path("revisions").size());
|
||||
assertEquals(2, second.path("nextBefore").intValue());
|
||||
|
||||
var last = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN)
|
||||
.param("before", "2")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertEquals(1, last.path("revisions").size());
|
||||
assertTrue(last.path("nextBefore").isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOversizedCanvasAndInvalidRollbackSource() throws Exception {
|
||||
Path database = dir.resolve("guarded.sqlite");
|
||||
MockMvc mvc = mvc(database);
|
||||
var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
|
||||
|
||||
var layout = (ObjectNode) mapper.readTree(new ClassPathResource("launcher/default_layout.json").getInputStream());
|
||||
((ObjectNode) layout.get("canvas")).put("designWidth", 9000);
|
||||
var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(layout)))
|
||||
.andExpect(status().is(422)).andReturn().getResponse();
|
||||
assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").toString().contains("canvas"));
|
||||
|
||||
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
|
||||
var statement = connection.createStatement()) {
|
||||
statement.executeUpdate("""
|
||||
INSERT INTO releases (revision, layout, publishedAt, restoredFrom)
|
||||
VALUES (2, '{"schemaVersion":2,"pages":[]}', '2026-01-01T00:00:00Z', NULL)
|
||||
""");
|
||||
}
|
||||
var latestTag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
|
||||
var rollback = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
|
||||
.header("If-Match", latestTag).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"revision\":2}"))
|
||||
.andExpect(status().is(422)).andReturn().getResponse();
|
||||
assertEquals("历史版本布局校验失败,无法回滚", message(rollback.getContentAsByteArray()));
|
||||
}
|
||||
|
||||
private String message(byte[] body) throws Exception {
|
||||
return mapper.readTree(body).path("message").stringValue();
|
||||
}
|
||||
|
||||
private MockMvc mvc(Path database) throws Exception {
|
||||
var validator = new LayoutValidator();
|
||||
var store = new LayoutStore(database.toString(), mapper, validator);
|
||||
var policy = new RequestPolicy(ADMIN.substring(7), DEVICE.substring(7));
|
||||
return MockMvcBuilders.standaloneSetup(new LayoutController(store, policy, validator, mapper))
|
||||
.setControllerAdvice(new ApiExceptionHandler())
|
||||
.addFilters(policy).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.ttstd.launcher;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
class LayoutValidatorTest {
|
||||
private final LayoutValidator validator = new LayoutValidator();
|
||||
private final JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
@Test
|
||||
void builtInLayoutHasNoErrors() throws Exception {
|
||||
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
|
||||
var layout = mapper.readTree(new String(input.readAllBytes(), StandardCharsets.UTF_8));
|
||||
assertTrue(validator.validate(layout).stream().noneMatch(issue -> issue.level().equals("error")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsBrokenProtocolFields() throws Exception {
|
||||
var issues = issues("""
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"canvas": {"designWidth": 100, "designHeight": 100, "safeTop": -1, "safeBottom": 0},
|
||||
"fit": {"mode": "contain", "anchorY": 0.5},
|
||||
"pages": [{
|
||||
"index": 0,
|
||||
"background": {"type": "wallpaper"},
|
||||
"items": [
|
||||
{"id": "", "type": "app_icon", "x": -1, "y": 0, "w": 0, "h": 10, "z": 1,
|
||||
"payload": {"package": ""}},
|
||||
{"id": "", "type": "widget", "x": 10, "y": 10, "w": 10, "h": 10, "z": 1,
|
||||
"payload": {"provider": "nocomponent"}}
|
||||
]
|
||||
}]
|
||||
}
|
||||
""");
|
||||
assertTrue(hasError(issues, "schemaVersion"));
|
||||
assertTrue(hasError(issues, "canvas"));
|
||||
assertTrue(hasError(issues, "pages[0].items[0].id"));
|
||||
assertTrue(hasError(issues, "pages[0].items[0].payload.package"));
|
||||
assertTrue(hasError(issues, "pages[0].items[1].payload.provider"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOversizedCanvasAndEmptyPages() throws Exception {
|
||||
var issues = issues("""
|
||||
{"schemaVersion":3,"canvas":{"designWidth":9000,"designHeight":9000},"pages":[]}
|
||||
""");
|
||||
assertTrue(hasError(issues, "canvas"));
|
||||
assertTrue(hasError(issues, "pages"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnsOnProtocolEdgeCases() throws Exception {
|
||||
var issues = issues("""
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"canvas": {"designWidth": 1080, "designHeight": 1920, "safeTop": 132, "safeBottom": 72},
|
||||
"fit": {"mode": "unknown", "anchorY": 1.4},
|
||||
"pages": [
|
||||
{"index": 1, "background": {"type": "image", "color": "white"},
|
||||
"items": [{"id": "%s", "type": "mystery", "x": 0, "y": 0, "w": 10, "h": 10, "z": 1,
|
||||
"payload": {"label": "%s", "radius": -1, "intent": "bad"}}]},
|
||||
{"index": 1, "background": {"type": "gradient", "from": "#ffffff"}, "items": []}
|
||||
]
|
||||
}
|
||||
""".formatted("x".repeat(65), "标题".repeat(60)));
|
||||
assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error")));
|
||||
for (String path : List.of("fit.mode", "fit.anchorY", "pages[0].index", "pages[1].index",
|
||||
"pages[0].background.type", "pages[0].background.color", "pages[1].background",
|
||||
"pages[0].items[0].id", "pages[0].items[0].type", "pages[0].items[0].payload.label",
|
||||
"pages[0].items[0].payload.radius", "pages[0].items[0].payload.intent")) {
|
||||
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning") && issue.path().equals(path)),
|
||||
"缺少告警:" + path);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnsOnSmallSafeAreasLikeTheEditor() throws Exception {
|
||||
var issues = issues("""
|
||||
{"schemaVersion":3,
|
||||
"canvas":{"designWidth":1080,"designHeight":1920,"safeTop":100,"safeBottom":20},
|
||||
"pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]}
|
||||
""");
|
||||
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning")
|
||||
&& issue.path().equals("canvas.safeTop")));
|
||||
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning")
|
||||
&& issue.path().equals("canvas.safeBottom")));
|
||||
assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsUnknownTopLevelFields() throws Exception {
|
||||
var issues = issues("""
|
||||
{"schemaVersion":3,"futureField":{"a":1},
|
||||
"canvas":{"designWidth":1080,"designHeight":1920},
|
||||
"pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]}
|
||||
""");
|
||||
assertEquals(List.of(), issues.stream().filter(issue -> issue.level().equals("error")).toList());
|
||||
}
|
||||
|
||||
private List<LayoutValidator.Issue> issues(String json) throws Exception {
|
||||
return validator.validate(mapper.readTree(json));
|
||||
}
|
||||
|
||||
private static boolean hasError(List<LayoutValidator.Issue> issues, String path) {
|
||||
return issues.stream().anyMatch(issue -> issue.level().equals("error") && issue.path().equals(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ttstd.launcher;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
class UniformityTest {
|
||||
private final LayoutValidator validator = new LayoutValidator();
|
||||
private final JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
@Test
|
||||
void sharedLayoutCases() throws Exception {
|
||||
var fixtures = Path.of("..", "docs", "layout-cases.json");
|
||||
for (var fixture : mapper.readTree(fixtures.toFile())) {
|
||||
assertEquals(fixture.path("accepted").booleanValue(),
|
||||
errors(validator.validate(fixture.path("layout"))).isEmpty(),
|
||||
fixture.path("name").stringValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInLayoutMatchesProtocolBaseline() throws Exception {
|
||||
var layout = mapper.readTree(read("launcher/default_layout.json"));
|
||||
assertTrue(errors(validator.validate(layout)).isEmpty());
|
||||
assertEquals(3, layout.path("schemaVersion").intValue());
|
||||
assertEquals(1080, layout.path("canvas").path("designWidth").intValue());
|
||||
assertEquals(1920, layout.path("canvas").path("designHeight").intValue());
|
||||
assertEquals(132, layout.path("canvas").path("safeTop").intValue());
|
||||
assertEquals(72, layout.path("canvas").path("safeBottom").intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void protocolLimitsMatchEditorAndAndroid() throws Exception {
|
||||
String page = "{\"index\":%d,\"background\":{\"type\":\"wallpaper\"},\"items\":[]}";
|
||||
String pages20 = IntStream.range(0, 20).mapToObj(i -> page.formatted(i)).collect(joining(","));
|
||||
String pages21 = IntStream.range(0, 21).mapToObj(i -> page.formatted(i)).collect(joining(","));
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages20 + "]")))).isEmpty());
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages21 + "]"))))
|
||||
.stream().anyMatch(issue -> issue.path().equals("pages")));
|
||||
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(319, 480, "["
|
||||
+ page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas")));
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(8193, 1920, "["
|
||||
+ page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas")));
|
||||
|
||||
String item = "{\"id\":\"i%d\",\"type\":\"app_icon\",\"x\":0,\"y\":0,\"w\":10,\"h\":10,\"z\":1,"
|
||||
+ "\"payload\":{\"package\":\"com.demo.app\"}}";
|
||||
String items80 = IntStream.range(0, 80).mapToObj(i -> item.formatted(i)).collect(joining(","));
|
||||
String page80 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items80 + "]}";
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page80 + "]")))).isEmpty());
|
||||
String items81 = items80 + "," + item.formatted(80);
|
||||
String page81 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items81 + "]}";
|
||||
assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page81 + "]"))))
|
||||
.stream().anyMatch(issue -> issue.path().equals("pages[0].items")));
|
||||
}
|
||||
|
||||
private static String layout(int width, int height, String pages) {
|
||||
return "{\"schemaVersion\":3,\"canvas\":{\"designWidth\":" + width
|
||||
+ ",\"designHeight\":" + height + "},\"pages\":" + pages + "}";
|
||||
}
|
||||
|
||||
private static List<LayoutValidator.Issue> errors(List<LayoutValidator.Issue> issues) {
|
||||
return issues.stream().filter(issue -> issue.level().equals("error")).toList();
|
||||
}
|
||||
|
||||
private static String read(String resource) throws Exception {
|
||||
try (var input = new ClassPathResource(resource).getInputStream()) {
|
||||
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user