Skip to content

Build your personal knowledge base with Trilium Notes

test: cover the branch's untested error paths, and leave the Android adapters out of Codecov

Elian Dorandbf27b0ecb6a
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.md
index 8cdd4bf699..8aac94c874 100644
--- a/.claude/skills/developing-capacitor-mobile/SKILL.md
+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md
@@ -210,7 +210,7 @@ cd apps/mobile/android
The project needs `cap sync android` (or `cap update android`) once first, for the generated `capacitor-cordova-android-plugins/`.
-- **Only Android-free classes are testable.** Unit tests compile against `android.jar`, whose classes (`Uri`, `Handler`, `Log`, `Base64`, `WebResourceResponse`) are stubs that throw "Method not mocked". Logic therefore lives in classes that import none of them (`LocalRequestBroker`, `NativeHttpProxy`, `InterceptedResponse`), with the WebView, the main thread, base64 and logging passed in; the `Trilium*` classes are thin adapters with no tests. Keep new native logic on the same side of that line.
+- **Only Android-free classes are testable.** Unit tests compile against `android.jar`, whose classes (`Uri`, `Handler`, `Log`, `Base64`, `WebResourceResponse`) are stubs that throw "Method not mocked". Logic therefore lives in classes that import none of them (`LocalRequestBroker`, `NativeHttpProxy`, `InterceptedResponse`), with the WebView, the main thread, base64 and logging passed in; the `Trilium*` classes and `MainActivity` are thin adapters with no tests, and the request-path ones (`TriliumRequestBridge`, `TriliumWebViewClient`, `MainActivity`) are listed under `ignore:` in `codecov.yml` so the patch check does not count them. Keep new native logic on the same side of that line, and a new adapter goes on that list.
- **`org.json` comes from a `testImplementation` dependency**, since `android.jar`'s copy is a stub too. **`com.sun.net.httpserver` is not on the test classpath**, so `NativeHttpProxyTest` serves canned responses from a `ServerSocket` (`StubServer`).
- **`minSdk` is 24**: `String.join` and `java.util.Base64` need API 26, so production code avoids them; tests can use them.
The iOS request logic has XCTest tests in a Swift package, `apps/mobile/ios/RequestBroker/`:
diff --git a/apps/client/src/services/server.spec.ts b/apps/client/src/services/server.spec.ts
index 8299cd8942..ba9ea618bf 100644
--- a/apps/client/src/services/server.spec.ts
+++ b/apps/client/src/services/server.spec.ts
@@ -635,6 +635,17 @@ describe("uploadForm", () => {
});
});
+ it("answers an empty JSON reply with null and any other reply with its text", async () => {
+ const reply = (response: Response) => {
+ (window as any).standaloneApi = { localUpload: vi.fn(async () => response) };
+ return server.uploadForm("notes/root/notes-import", options);
+ };
+
+ expect(await reply(new Response("", { headers: { "content-type": "application/json" } }))).toBeNull();
+ expect(await reply(new Response("<p>done</p>", { headers: { "content-type": "text/html" } }))).toBe("<p>done</p>");
+ expect(await reply(new Response(new Blob([ "plain" ])))).toBe("plain");
+ });
+
it("rejects with the status and text of an error reply, the fields a jqXHR carries", async () => {
(window as any).standaloneApi = {
localUpload: vi.fn(async () => new Response("Import failed", { status: 500 }))
diff --git a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
index 11158f8277..456fa610ab 100644
--- a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
+++ b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
@@ -27,6 +27,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -123,6 +124,7 @@ public class LocalRequestBrokerTest {
// WebView treats the stream as the whole resource and skips to the range start itself,
// in a loop, as SkipToRequestedRange in Chromium's input_stream_reader.cc does.
assertEquals(0, response.body.available());
+ assertEquals(0, response.body.skip(0));
long toSkip = 1000;
while (toSkip > 0) {
long skipped = response.body.skip(toSkip);
@@ -146,6 +148,17 @@ public class LocalRequestBrokerTest {
assertEquals(2, response.body.skip(2));
assertEquals("ole", read(response.body));
+
+ Future<InterceptedResponse> unsatisfiable = request(broker, null, "https://localhost/api/notes/y", new HashMap<>());
+ int rangeId = idOf(awaitScript(1));
+ broker.onMessage("{\"type\":\"head\",\"id\":" + rangeId + ",\"status\":206,\"headers\":{"
+ + "\"content-range\":\"bytes */5\"}}");
+ InterceptedResponse range = unsatisfiable.get(WAIT_MS, TimeUnit.MILLISECONDS);
+ broker.onFrame(frame(rangeId, "whole"));
+ broker.onMessage("{\"type\":\"end\",\"id\":" + rangeId + "}");
+
+ assertEquals(2, range.body.skip(2));
+ assertEquals("ole", read(range.body));
}
@Test
@@ -214,6 +227,29 @@ public class LocalRequestBrokerTest {
assertEquals("The page has no request handler", read(response.body));
}
+ @Test
+ public void ignoresARejectionThatArrivesAfterTheRequestFailed() throws Exception {
+ List<Consumer<Boolean>> verdicts = Collections.synchronizedList(new ArrayList<>());
+ LocalRequestBroker broker = new LocalRequestBroker(
+ (script, accepted) -> verdicts.add(accepted),
+ Runnable::run,
+ data -> Base64.getDecoder().decode(data),
+ warnings::add,
+ WAIT_MS,
+ true);
+ broker.onMessage("{\"type\":\"ready\"}");
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/api/x", new HashMap<>());
+ long deadline = System.currentTimeMillis() + WAIT_MS;
+ while (verdicts.isEmpty() && System.currentTimeMillis() < deadline) {
+ Thread.sleep(5);
+ }
+
+ broker.onPageStarted();
+ verdicts.get(0).accept(false);
+
+ assertEquals("The page reloaded before answering", read(pending.get(WAIT_MS, TimeUnit.MILLISECONDS).body));
+ }
+
@Test
public void failsPendingRequestsOnReloadAndWaitsForTheNewPage() throws Exception {
LocalRequestBroker broker = readyBroker();
@@ -278,6 +314,12 @@ public class LocalRequestBrokerTest {
assertEquals(502, response.status);
assertEquals("The local worker answered with status " + status, read(response.body));
}
+
+ Future<InterceptedResponse> pending = request(broker, "GET", "https://localhost/api/missing", new HashMap<>());
+ int id = idOf(awaitScript(statuses.length));
+ broker.onMessage("{\"type\":\"head\",\"id\":" + id + ",\"status\":404}");
+ broker.onMessage("{\"type\":\"end\",\"id\":" + id + "}");
+ assertEquals(404, pending.get(WAIT_MS, TimeUnit.MILLISECONDS).status);
}
@Test
diff --git a/apps/server/src/zip_provider.spec.ts b/apps/server/src/zip_provider.spec.ts
index 2c0157fd1b..594df964cc 100644
--- a/apps/server/src/zip_provider.spec.ts
+++ b/apps/server/src/zip_provider.spec.ts
@@ -223,6 +223,11 @@ describe("NodejsZipProvider", () => {
});
});
+ it("rejects a Blob source, which only the browser provider reads", async () => {
+ await expect(provider.readZipFile({ blob: new Blob([]) }, async () => {}))
+ .rejects.toThrow("A Blob zip source is only readable in the browser.");
+ });
+
describe("reading from a path (in place, no full-buffer load)", () => {
const dir = mkdtempSync(join(tmpdir(), "trilium-zip-provider-spec-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.ts
index d01caa46de..3e888a227c 100644
--- a/apps/standalone/src/lightweight/browser_router.spec.ts
+++ b/apps/standalone/src/lightweight/browser_router.spec.ts
@@ -181,6 +181,14 @@ describe("BrowserRouter body parsing", () => {
await router.dispatch("POST", "http://localhost/upload", body);
expect(buffered?.file?.buffer && Array.from(buffered.file.buffer)).toEqual([ 4, 5, 6 ]);
+
+ const untyped = new File([ new Uint8Array([ 7 ]) ], "blob");
+ await router.dispatch("POST", "http://localhost/import", { type: "upload", fields: {}, file: untyped });
+ expect(inPlace?.file?.mimetype).toBe("application/octet-stream");
+
+ await router.dispatch("POST", "http://localhost/upload", { type: "upload", fields: { taskId: "t2" } });
+ expect(buffered?.body).toEqual({ taskId: "t2" });
+ expect(buffered?.file).toBeUndefined();
});
it("warns when multipart parsing fails", async () => {
diff --git a/apps/standalone/src/lightweight/zip_provider.spec.ts b/apps/standalone/src/lightweight/zip_provider.spec.ts
index f0c9525b75..5e2216f8ce 100644
--- a/apps/standalone/src/lightweight/zip_provider.spec.ts
+++ b/apps/standalone/src/lightweight/zip_provider.spec.ts
@@ -335,6 +335,9 @@ describe("BrowserZipProvider entry formats", () => {
it("reads a stored (uncompressed) entry", async () => {
const zip = zipSync({ "plain.txt": [ strToU8("as is"), { level: 0 } ] });
expect(await readAll(zip)).toEqual({ "plain.txt": "as is" });
+
+ const withExtraField = zipSync({ "plain.txt": [ strToU8("as is"), { level: 0, extra: { 0x5455: new Uint8Array([ 1 ]) } } ] });
+ expect(await readAll(withExtraField)).toEqual({ "plain.txt": "as is" });
});
it("reads a ZIP64 archive, whose sizes and offsets are in 64-bit records", async () => {
@@ -358,6 +361,37 @@ describe("BrowserZipProvider entry formats", () => {
await expect(readNames(zip)).rejects.toThrow("Corrupt ZIP: the central directory ends in an unreadable record.");
});
+ it("rejects an archive whose directory records point outside the file", async () => {
+ const zip64 = makeZip64("big.txt", "sixty-four");
+ const zip64View = new DataView(zip64.buffer);
+ zip64View.setUint32(zip64.length - 22 - 20 - 56, 0, true);
+ await expect(readNames(zip64)).rejects.toThrow("the ZIP64 end-of-central-directory record is missing");
+
+ const directoryPastEnd = makeZip({ "a.txt": "x" });
+ new DataView(directoryPastEnd.buffer).setUint32(directoryPastEnd.length - 22 + 16, 0x7fffffff, true);
+ await expect(readNames(directoryPastEnd)).rejects.toThrow("the central directory lies past the end of the file");
+
+ const recordPastDirectory = patchCentralHeader(makeZip({ "a.txt": "x" }), (view, at) => view.setUint16(at + 30, 0xffff, true));
+ await expect(readNames(recordPastDirectory)).rejects.toThrow("a central directory record runs past the directory");
+
+ await expect(readNames(new Uint8Array(64))).rejects.toThrow("Truncated ZIP: no end-of-central-directory record.");
+ });
+
+ it("rejects entry content that lies outside the file", async () => {
+ const shortZip64Extra = makeZip64("big.txt", "sixty-four");
+ const extraSizeField = 30 + 7 + 10 + 46 + 7 + 2;
+ new DataView(shortZip64Extra.buffer).setUint16(extraSizeField, 8, true);
+ await expect(readAll(shortZip64Extra)).rejects.toThrow("Corrupt ZIP: an entry's local header is missing.");
+
+ const truncated = patchCentralHeader(makeZip({ "a.txt": "x" }), (view, at) => view.setUint32(at + 20, 0xffff, true));
+ await expect(readAll(truncated)).rejects.toThrow("Truncated ZIP: an entry's data runs past the end of the file.");
+ });
+
+ it("keeps an unflagged name that decodes in no encoding as one character per byte", async () => {
+ const zip = makeLegacyZip([{ placeholder: "A", nameBytes: [0xfe] }]);
+ expect(await readNames(zip, "x-unknown-encoding")).toEqual([ "þ" ]);
+ });
+
it("rejects an entry it cannot read, but only when its content is asked for", async () => {
const unsupported = patchCentralHeader(makeZip({ "a.txt": "x" }), (view, at) => view.setUint16(at + 10, 12, true));
const encrypted = patchCentralHeader(makeZip({ "a.txt": "x" }), (view, at) => view.setUint16(at + 8, view.getUint16(at + 8, true) | 1, true));
diff --git a/codecov.yml b/codecov.yml
index 2674504813..0dd1c1584b 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -76,6 +76,11 @@ flags:
- apps/web-clipper/utils.ts
carryforward: true
+ignore:
+ - apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
+ - apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumRequestBridge.java
+ - apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumWebViewClient.java
+
comment:
layout: "condensed_header, condensed_files, condensed_footer"
require_changes: true