Skip to content

Latest commit

 

History

History
181 lines (120 loc) · 18.4 KB

README.md

File metadata and controls

181 lines (120 loc) · 18.4 KB

Testing

OpenFrame OSS Frontend is a multi-app repository (apps/web, apps/desktop, apps/mobile), and each app's test suite matches its runtime: Vitest and Node's built-in test runner for the Next.js web app, JUnit for the Android mobile shell, and Rust's cargo test idiom for the Tauri desktop shell. This document covers how tests are organized, how to run them locally and in CI, how to write new ones, and what level of coverage this repository expects.

This repository publishes no downstream-consumed library artifact from apps/web itself; the published artifact is openframe_console (cargo, desktop shell). Per get_repo_ecosystem, no other repository in the graph is currently recorded as depending on this repository's code, so test changes here are evaluated against this repository's own CI gates rather than external consumers. Coverage of that dependency graph is partial, so treat this as "no known consumer," not "no consumer."

Test Structure And Organization

Web App (apps/web)

The web app has two parallel test mechanisms, intentionally kept separate:

Mechanism Config What it covers Why separate
Vitest apps/web/vitest.config.mts .ts / .tsx files under src/** Needs a jsdom environment and Vite's module resolver
Node test runner invoked via npm run test:node src/lib/*.test.mjs files These files import 'node:test', which Vitest cannot run

As documented directly in vitest.config.mts, Vitest's include pattern is src/**/*.test.ts and src/**/*.test.tsx. Test files live beside the code they exercise rather than in a separate top-level test tree, and the .test.mjs files under src/lib/ are deliberately excluded from Vitest's include glob because they predate the Vitest setup and use node:test directly.

Key configuration details from apps/web/vitest.config.mts:

  • Environment: jsdom, required because the test suite imports the @flamingo-stack/openframe-frontend-core barrel, which touches browser globals at module scope even for non-component modules.
  • Path alias: @ resolves to apps/web/src, matching the application's own import alias.
  • Setup file: ./vitest.setup.ts, loaded before every test file.
  • Dependency inlining: @flamingo-stack/openframe-frontend-core is listed under test.server.deps.inline as a regular expression, so Vitest processes it through Vite's resolver instead of Node's raw ESM loader. The comment in the config explains why: the library's bundle imports Next.js entry points extensionlessly (next/link, next/navigation), which Node's ESM loader rejects but Vite resolves the same way the Next.js build does.
  • globals: false: test files must explicitly import describe, it, expect, etc. from vitest rather than relying on injected globals.

The shared test bootstrap that vitest.setup.ts wires into is documented in Vitest Setup (an @flamingo-stack/openframe-frontend-core module). It installs jsdom compatibility shims (matchMedia, ResizeObserver), a localStorage fallback, and a mocked navigation layer (mockReplace, mockPush, mockSearchParams, setMockSearchParams) registered through the frontend-core navigation shim rather than by mocking next/navigation directly. Any test that needs to assert on routing or query-parameter behavior should use that registered mock, not a direct next/navigation mock, because application code reads navigation hooks from the embed shim at src/embed-shims/next-navigation.

Mobile App (apps/mobile)

The Android shell under apps/mobile/android has three distinct JUnit layers, visible directly in the source tree:

  • Unit tests (apps/mobile/android/app/src/test/java/...) — plain JVM tests, run via Gradle, no device or emulator needed. Examples in the tree: NativeUpdateCheckTimingTest.java, TokenLifecycleLostRotationTest.java, and the ota package's BundleCheckTest.java, BundleReaderTest.java, BundleRemovalTest.java, BytesTest.java, DirectorySinkTest.java, OtaSessionTest.java, OtaStateTest.java, SharedCasesTest.java, StrictFormatTest.java.
  • Shared test cases (apps/mobile/android/app/src/sharedTest/java/ai/openframe/mobile/ota/SharedCases.java) — one case runner consumed by both the JVM unit tests and the on-device instrumented tests, so the same manifest/bundle/environment/decision/key-ID fixtures are exercised on both runtimes. apps/mobile/android/app/build.gradle wires test.java.srcDirs and androidTest.java.srcDirs to this shared directory, and both test.resources.srcDirs and androidTest.assets.srcDirs point at ../../ota/fixtures.
  • Instrumented tests (apps/mobile/android/app/src/androidTest/java/...) — run on a device or emulator because some behavior depends on the Android runtime itself: UpdateStoreInstrumentedTest.java exercises the file-backed UpdateStore with a per-test cache directory, and ota/SharedCasesInstrumentedTest.java reruns the shared cases against Android's own security provider (Conscrypt) and ART's XZ decompression — deliberately different from the JVM, which runs SunEC and rejects a DER signature Conscrypt accepts. See Mobile Tests, Shared OTA Instrumented Tests, and Update Store Instrumented Tests for the documented behavior these suites pin down.

Each UpdateStoreInstrumentedTest creates a unique directory under the target app's cache dir (update-store-<timestamp>) and deletes it in @After, so instrumented runs never touch the real OTA directory and are safe to repeat on the same device.

Desktop App (apps/desktop)

The desktop shell is a Tauri application; its Rust crate is declared in apps/desktop/src-tauri/Cargo.toml with the package name openframe-console (published as cargo artifact openframe_console per the ecosystem facts). The crate exposes an app_lib library (see apps/desktop/src-tauri/src/lib.rs, invoked from apps/desktop/src-tauri/src/main.rs), which is the idiomatic layout cargo test expects for in-crate unit tests alongside the library's own source modules (autostart.rs, chat_api.rs, nats.rs, tokens.rs, updater.rs, etc.).

Running Tests

Web App

All web commands run from apps/web (or with --workspace=apps/web conventions, as applicable); the scripts are defined in apps/web/package.json:

cd apps/web

# Run both suites: Vitest (once) then the node:test suite
npm run test

# Run only the Vitest suite once
npx vitest run

# Run only the Vitest suite in watch mode
npm run test:watch

# Run only the node:test suite (src/lib/*.test.mjs)
npm run test:node

The test script itself is vitest run && npm run test:node — Vitest runs first, then the Node-native suite. Running npm run test:watch runs vitest without the run flag, which keeps Vitest attached and reruns affected files as they change.

Besides the test scripts, these related apps/web/package.json scripts matter for a complete pre-submission check:

cd apps/web

npm run lint          # eslint . --cache --max-warnings 0
npm run type-check    # tsc --noEmit
npm run format        # prettier --check .

Mobile App

Run Android unit tests from the apps/mobile/android Gradle project (standard Gradle unit-test task against the module declared in apps/mobile/android/app/build.gradle):

cd apps/mobile/android
./gradlew test

Instrumented tests require a connected device or running emulator, since they exercise the on-device security provider and filesystem:

cd apps/mobile/android
./gradlew connectedAndroidTest

The apps/mobile/package.json also defines an OTA fixture/tooling test command, run with Node's built-in test runner:

cd apps/mobile
npm run test

That script expands to node --test scripts/ota.test.mjs scripts/ota-fixtures.test.mjs scripts/ota-stamp.test.mjs — these are tests for the Node-side OTA packing/signing scripts (apps/mobile/scripts/ota-pack.mjs, ota-stamp.mjs, ota-fixtures.mjs), separate from the Android JUnit suites above.

Desktop App

The desktop Rust crate follows the standard cargo test convention from apps/desktop/src-tauri:

cd apps/desktop/src-tauri
cargo test

In CI

.github/workflows/test.yml ("Openframe Test") runs on pull requests targeting main and on merge_group events. It first runs a changes job using dorny/paths-filter to decide which of web, desktop, and shared_fixtures changed (with predicate-quantifier: every, so, for example, the web filter is true only when the change touches neither apps/desktop/** nor apps/mobile/**). When web changes, the build_image job builds the apps/web/Dockerfile image for both linux/amd64 and linux/arm64, runs a Trivy vulnerability scan via .github/steps/trivy on pull requests (a fixable HIGH/CRITICAL finding fails the job and blocks the push), and — on pull_request events only — pushes the image tagged pr-<number> and pr-<number>-<sha> to ghcr.io/flamingo-stack/openframe-oss-frontend/openframe-oss-frontend. A cleanup job removes those PR-tagged images once the pull request closes.

Note that test.yml builds and scans the Docker image as its CI gate for the web app; it does not itself invoke npm run test as a separate workflow step in the material shown here — the npm test / Vitest / lint / type-check commands above are what you run locally (and what the Dockerfile's own build steps, such as npm run generate-enums && relay-compiler && next-styles build, depend on implicitly through npm run build).

.github/workflows/release.yml similarly gates desktop and mobile artifact builds behind path-based changes detection and builds the shared web export (npm run build:export) once per release, which the desktop and mobile OTA jobs then consume.

Writing New Tests

Web App Conventions (Vitest)

  • File naming and placement: co-locate a test with the module it covers, using *.test.ts or *.test.tsx, so it is picked up by the include glob in apps/web/vitest.config.mts (src/**/*.test.ts, src/**/*.test.tsx).
  • Imports are explicit: because globals: false is set, import test primitives directly:
import { describe, it, expect, vi } from 'vitest';
  • Routing and query-state assertions: use the registered mocks from the frontend-core Vitest setup rather than mocking next/navigation:
import { setMockSearchParams, mockReplace, mockPush } from '@flamingo-stack/openframe-frontend-core/vitest.setup';

setMockSearchParams(new URLSearchParams({ status: 'open', page: '2' }));
// ... render or invoke the hook under test ...
expect(mockReplace).toHaveBeenCalledWith('/tickets?page=2', { scroll: false });

The setup's beforeEach clears mockReplace/mockPush call history and resets the search params to empty before every test, so state never leaks across test files.

  • jsdom-dependent code: matchMedia and ResizeObserver fallbacks installed by vitest.setup.ts are deliberately inert (no simulated breakpoint matches, no triggered resize callbacks). If a test needs to assert behavior driven by either, override the global locally within that test rather than relying on the shared default.
  • Node-only .mjs tests: if a module under src/lib/ needs a test that depends on node:test semantics (not jsdom, not Vite module resolution), add a *.test.mjs file beside it and make sure it is also referenced by the test:node script's glob (src/lib/*.test.mjs) in apps/web/package.json.
  • ESLint test rules: the shared @flamingo-stack/openframe-frontend-core ESLint configuration's tests layer (documented in Specialized Checks) enforces several safety rules you should follow when writing new web tests:
    • Await Testing Library findBy* queries.
    • Avoid no-node-access violations — assert on behavior, not on raw DOM structure.
    • Avoid no-conditional-expect — don't let an assertion be skippable by a conditional branch.
    • Use Vitest's two-argument expect(actual, message) form when a label helps debugging.
    • vitest/expect-expect recognizes both direct expect(...) calls and your own assert*-named helper functions, so a custom assertion helper named with that convention will satisfy the rule.
    • testing-library/custom-renders is disabled repository-wide because some helper functions are named with render in them without returning a Testing Library render result — don't assume the inverse elsewhere.
    • no-script-url is disabled in test files specifically so a security test can express a rejected javascript: URL input directly.
    • eslint-plugin-jest-dom is intentionally not used; its preference-style rules don't catch the safety failures this repository cares about, and some of its autofixes can change assertion semantics.

Mobile App Conventions (JUnit)

  • Where a test belongs:
    • A pure-logic case with no Android dependency → apps/mobile/android/app/src/test/java/... (JVM unit test).
    • A case that must validate against Android's actual security provider, ART, or the filesystem of a running app → apps/mobile/android/app/src/androidTest/java/... (instrumented test).
    • A case that should run identically on both → add it to SharedCases in apps/mobile/android/app/src/sharedTest/java/ai/openframe/mobile/ota/SharedCases.java, then call it from both a JVM test (e.g. SharedCasesTest.java) and the instrumented adapter (SharedCasesInstrumentedTest.java).
  • Isolating filesystem state: follow UpdateStoreInstrumentedTest's pattern — create a unique directory per test in @Before (e.g. update-store- + a monotonic value) and recursively delete it in @After. Never write directly into the application's real OTA directory from a test.
  • Distinguishing failure types: the existing suite is explicit about three different failure categories for stored state — missing (first launch, returns OtaState.EMPTY), malformed (also treated as empty), and present-but-unreadable (must propagate as an IOException, not be silently treated as empty). When adding a new persistence-related test, preserve this distinction rather than collapsing it.
  • Shared fixtures location: apps/mobile/android/app/build.gradle points test.resources.srcDirs and androidTest.assets.srcDirs at ../../ota/fixtures (i.e. apps/mobile/ota/fixtures). Add new manifest/bundle/environment/decision/key-ID fixtures there so both runtimes can read them through the same SharedCases.Fixtures interface (assets::open on Android, resource loading on the JVM).

Desktop App Conventions (Rust)

  • Add #[cfg(test)] modules inside the relevant source file under apps/desktop/src-tauri/src/ (alongside existing modules like tokens.rs, nats.rs, autostart.rs), following the standard Rust convention cargo test expects — this repository does not show a separate top-level tests/ integration-test directory for the desktop crate in the material available.
  • Keep platform-conditional code (the Cargo.toml target-specific dependency blocks for Windows, macOS, and Linux/macOS) in mind: a test that exercises windows_toast.rs, macos_wake.rs, or macos_un.rs logic will only compile and run on its target OS, matching the [target.'cfg(...)'.dependencies] sections in apps/desktop/src-tauri/Cargo.toml.

Coverage Requirements

No coverage threshold, coverage-reporting tool invocation, or coverage gate is configured in the material available for this repository — apps/web/package.json's test script runs vitest run && npm run test:node without a --coverage flag, and no code-review rule enforcing a coverage percentage was returned for this repository by the active rules catalog.

In the absence of an enforced numeric threshold, apply these repository-evidenced expectations when adding or changing behavior:

  • New hooks and utilities under apps/web/src should get a co-located *.test.ts/*.test.tsx file exercising both the success path and at least one failure/edge path, matching the pattern described for existing hooks such as useCustomersOverview (see Customer Overview's "Testing Considerations" section, which enumerates authentication gating, empty results, HTTP failures, malformed responses, retry/error state, and partial-failure behavior as required cases for that hook).
  • OTA and update-store changes on mobile must preserve the three-way distinction between "missing," "malformed/recoverable," and "present but unreadable" state, and must assert both the in-memory session outcome and the on-disk effect when a transition crosses a process boundary — this is the explicit guidance baked into the existing UpdateStoreInstrumentedTest suite.
  • CI's Trivy scan in test.yml is a hard gate on the built web Docker image for HIGH/CRITICAL vulnerabilities on every pull request; a fixable finding fails build_image and blocks the image push, so dependency and base-image changes should be validated against it before merge.
  • Run npm run lint, npm run type-check, and npm run format alongside the test suites locally before opening a pull request, since these are the static-analysis equivalents to behavioral test coverage for this codebase and are backed by the shared ESLint configuration described in ESLint Config And Scripts.

For broader setup instructions (installing dependencies, environment variables, local dev server), see Local Development and Environment. For the repository's overall development workflow and where testing fits into it, see the Development overview and Contributing Guidelines.