Skip to content

Add test coverage for error mapping and tsjs helpers#648

Open
ChristianPavilonis wants to merge 1 commit intomainfrom
tests/improve-test-covereage
Open

Add test coverage for error mapping and tsjs helpers#648
ChristianPavilonis wants to merge 1 commit intomainfrom
tests/improve-test-covereage

Conversation

@ChristianPavilonis
Copy link
Copy Markdown
Collaborator

Summary

  • add exhaustive unit coverage for TrustedServerError::status_code() so each public variant is pinned to its expected HTTP response
  • add direct tsjs formatting tests for unified and deferred script URL/tag helpers using computed hashes
  • cover invalid UTF-8 cookie-header handling and simplify duplicate callback serde rename tests

Changes

File Change
crates/trusted-server-core/src/error.rs Added a table-driven test covering HTTP status code mapping for every TrustedServerError variant.
crates/trusted-server-core/src/tsjs.rs Added direct unit tests for unified and deferred TS/JS script URL and tag helpers.
crates/trusted-server-core/src/cookies.rs Added a unit test for invalid UTF-8 Cookie header handling in handle_request_cookies().
crates/trusted-server-core/src/models.rs Consolidated duplicate callback serde rename tests into one focused test.

Closes

Closes #448
Closes #450
Closes #454
Closes #456

Test plan

  • cargo test --workspace
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo fmt --all -- --check
  • JS tests: cd crates/js/lib && npx vitest run
  • JS format: cd crates/js/lib && npm run format
  • Docs format: cd docs && npm run format
  • WASM build: cargo build --package trusted-server-adapter-fastly --release --target wasm32-wasip1
  • Manual testing via fastly compute serve
  • Other:

Checklist

  • Changes follow CLAUDE.md conventions
  • No unwrap() in production code — use expect("should ...")
  • Uses tracing macros (not println!)
  • New code has tests
  • No secrets or credentials committed

Copy link
Copy Markdown
Collaborator

@aram356 aram356 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Pure test additions/consolidation — no production code changes. Tests pass on wasm32-wasip1, clippy is clean, and CI is fully green. The substantive concerns below are about test design — what these tests would catch on regression — rather than correctness of what was added. Requesting changes primarily on the exhaustiveness and tautology issues; the rest are non-blocking.

Blocking

♻️ refactor

  • Status code mapping test is not exhaustive at compile timeerror.rs:144-247. Hand-maintained cases array means a new variant added to TrustedServerError won't fail this test. A non-exhaustive match guard would force exhaustive coverage. See inline comment.
  • tsjs hash assertions are tautologicaltsjs.rs:75-116. expected_hash is derived by calling the same concatenated_hash the production code calls. If concatenated_hash regressed, both sides would change in lockstep. Suggest asserting hash structure (64 hex chars) and that different module sets yield different URLs. See inline comment.
  • Redundant import in tsjs test moduletsjs.rs:70. Duplicates the top-of-file import; use super::* at line 72 is sufficient (verified locally).

Non-blocking

🤔 thinking

  • tsjs_deferred_script_src_uses_empty_hash_for_unknown_module locks in silent failuretsjs.rs:137-143. Empty hash produces a 404-bound URL with no logging. Capturing this as "expected" makes future improvements look like regressions.

🌱 seedling

  • Production unwrap_or_default() for unknown deferred modules is invisibletsjs.rs:44 (unchanged in this PR, so noted in the body). single_module_hash(module_id).unwrap_or_default() silently produces a 404-bound URL with no logging when the module isn't registered. Worth a follow-up issue to add log::warn! for unregistered module IDs.

📝 note

  • Issue #454 wording vs implementationcookies.rs:353-372. Issue says "returning None" but production returns Err. Test correctly verifies current implementation; issue text is stale.

⛏ nitpick

  • ["core", "creative"] redundantly includes coretsjs.rs:76, 88. concatenate_modules always prepends core; could be simplified to ["creative"].
  • HeaderValue::from_bytes expect message is slightly misleadingcookies.rs:358. Reads like a property of handle_request_cookies but is about HeaderValue::from_bytes.

CI Status

  • fmt: PASS
  • clippy: PASS
  • rust tests: PASS (verified locally on wasm32-wasip1)
  • vitest: PASS
  • format-typescript / format-docs: PASS
  • browser & integration tests: PASS

"should map {error:?} to the expected HTTP status",
);
}
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ refactor — The table-driven cases array is hand-maintained. If a new TrustedServerError variant is added and status_code() is updated but this test isn't, the test silently passes despite the new variant being uncovered. Since the whole point of this test is to lock in the variant→status mapping, a compile-time exhaustiveness guard would be much stronger.

Fix — add a non-exhaustive match somewhere in the test that fails to compile if a variant is added:

// Compile-time guard: adding a TrustedServerError variant without
// updating this test will fail to compile.
let _exhaustive = |e: &TrustedServerError| match e {
    TrustedServerError::BadRequest { .. }
    | TrustedServerError::Configuration { .. }
    | TrustedServerError::Auction { .. }
    | TrustedServerError::Gam { .. }
    | TrustedServerError::GdprConsent { .. }
    | TrustedServerError::InvalidUtf8 { .. }
    | TrustedServerError::InvalidHeaderValue { .. }
    | TrustedServerError::KvStore { .. }
    | TrustedServerError::Prebid { .. }
    | TrustedServerError::Integration { .. }
    | TrustedServerError::Proxy { .. }
    | TrustedServerError::Forbidden { .. }
    | TrustedServerError::AllowlistViolation { .. }
    | TrustedServerError::Settings { .. }
    | TrustedServerError::Ec { .. } => (),
};

format!("/static/tsjs=tsjs-unified.min.js?v={expected_hash}"),
"should include the unified bundle path and cache-busting hash",
);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ refactorexpected_hash is derived by calling concatenated_hash — the same function the production code calls. The test verifies "function composition matches itself" instead of cache-busting behavior. If concatenated_hash silently regressed (e.g. always returned "") both production and test would change in lockstep and the test would still pass.

Fix — assert hash structure (64 hex chars for SHA-256) and that different module sets yield different URLs:

let a = tsjs_script_src(&["creative"]);
let b = tsjs_script_src(&["creative", "prebid"]);
assert_ne!(a, b, "different module sets must yield different cache-busting URLs");
let hash = a.rsplit_once("?v=").expect("should have v= param").1;
assert_eq!(hash.len(), 64, "should be SHA-256 hex");
assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));

The same concern applies to tsjs_unified_helpers_use_all_module_ids below.


#[cfg(test)]
mod tests {
use trusted_server_js::{all_module_ids, concatenated_hash, single_module_hash};
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ refactor — Duplicate of the import at the top of the file. Submodules can see private items of ancestors, so use super::*; at line 72 is sufficient. Verified locally: removing this line keeps both cargo build and cargo test green.

Fix — delete this line.

"/static/tsjs=tsjs-unknown-module.min.js?v=",
"should fall back to an empty hash for unknown deferred modules",
);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 thinking — This test asserts that calling tsjs_deferred_script_src("unknown-module") produces "/static/tsjs=tsjs-unknown-module.min.js?v=" — an empty hash that points at a non-existent file → silent 404 in the browser. Capturing this as "what we expect" makes future improvements to the production unwrap_or_default() (e.g. logging or returning Option<String>) look like regressions when they're actually fixes.

Suggestion — either re-frame the test so its name describes a documented contract (e.g. "caller is responsible for not generating tags for unregistered modules") and add a log::warn! in production for unknown IDs, or mark this as a known-bad behavior with a follow-up issue.

),
"should return InvalidHeaderValue for invalid UTF-8 cookie headers",
);
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 note — Issue #454 says "returning None" but handle_request_cookies returns Err(InvalidHeaderValue) for non-UTF-8 cookie headers. The test correctly verifies the current implementation. Just flagging that the issue text is stale (likely written when the function had a different signature) — the issue can still be closed; no action on this PR.


#[test]
fn tsjs_script_src_formats_unified_bundle_url_with_hash() {
let module_ids = ["core", "creative"];
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpickbundle.rs::concatenate_modules always prepends "core" and skips it when present in ids (bundle.rs:31-39). Passing ["core", "creative"] produces the same hash as ["creative"]. Could be simplified to ["creative"] to avoid implying caller-side intent that doesn't matter. Same applies to line 88.

req.set_header(
header::COOKIE,
HeaderValue::from_bytes(b"session=\xFF")
.expect("should allow non-UTF-8 cookie header bytes"),
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick — The expect message reads like a property of handle_request_cookies, but it's actually about HeaderValue::from_bytes accepting any opaque bytes. Consider "should construct HeaderValue from non-UTF-8 bytes" for clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants