From 812ebe3c54670683e410d64a267997d29af68415 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:17:10 +0200 Subject: [PATCH] test: lint test code in CI, and run core's integration tests (#379) Test code was never linted and compliance-core not at all; its integration tests did not compile (TrackedRepository no longer exists). Tests may now unwrap (clippy.toml), the remaining lints are fixed, CI runs clippy with --all-targets on every crate including core, and core's integration tests run. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .gitea/workflows/ci.yml | 20 +++++--- clippy.toml | 4 ++ compliance-agent/src/llm/embedding.rs | 10 +--- compliance-agent/src/pipeline/plan.rs | 4 +- compliance-agent/src/scheduler.rs | 50 +++++++++---------- compliance-agent/tests/c5_example2.rs | 2 + compliance-agent/tests/c5_semantic_live.rs | 2 + compliance-agent/tests/common/mod.rs | 2 + compliance-agent/tests/demo_seed.rs | 2 + compliance-agent/tests/e2e.rs | 2 + .../tests/grounded_surface_live.rs | 2 + .../tests/integration/api/cascade_delete.rs | 12 ++--- .../tests/integration/api/findings.rs | 2 +- .../tests/integration/api/stats.rs | 4 +- compliance-core/src/models/scan.rs | 42 ++++++++-------- compliance-core/src/scan_matrix.rs | 2 +- compliance-core/tests/models.rs | 16 ------ .../src/infrastructure/session_store.rs | 6 +-- 18 files changed, 92 insertions(+), 92 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index fb14741..b087fd9 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -107,19 +107,22 @@ jobs: env: RUSTC_WRAPPER: "" - # Clippy (compiles once, sccache reuses across feature sets) + # Clippy (compiles once, sccache reuses across feature sets). --all-targets + # lints test code too; tests may unwrap (clippy.toml), production may not. + - name: Clippy (core) + run: cargo clippy -p compliance-core --all-targets -- -D warnings - name: Clippy (agent) - run: cargo clippy -p compliance-agent -- -D warnings + run: cargo clippy -p compliance-agent --all-targets -- -D warnings - name: Clippy (dashboard server) - run: cargo clippy -p compliance-dashboard --features server --no-default-features -- -D warnings + run: cargo clippy -p compliance-dashboard --features server --no-default-features --all-targets -- -D warnings - name: Clippy (dashboard web) - run: cargo clippy -p compliance-dashboard --features web --no-default-features -- -D warnings + run: cargo clippy -p compliance-dashboard --features web --no-default-features --all-targets -- -D warnings - name: Clippy (mcp) - run: cargo clippy -p compliance-mcp -- -D warnings + run: cargo clippy -p compliance-mcp --all-targets -- -D warnings - name: Clippy (werkbank-exec) - run: cargo clippy -p werkbank-exec -- -D warnings + run: cargo clippy -p werkbank-exec --all-targets -- -D warnings - name: Clippy (control-map) - run: cargo clippy -p control-map -- -D warnings + run: cargo clippy -p control-map --all-targets -- -D warnings # Security audit - name: Security Audit @@ -130,6 +133,9 @@ jobs: # Tests (reuses compilation artifacts from clippy) - name: Tests (core + agent + werkbank-exec + control-map) run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib + # compliance-core's integration tests need no services. + - name: Tests (core integration) + run: cargo test -p compliance-core --tests - name: Tests (dashboard server) run: cargo test -p compliance-dashboard --features server --no-default-features - name: Tests (dashboard web) diff --git a/clippy.toml b/clippy.toml index cda8d17..b89ab49 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1 +1,5 @@ avoid-breaking-exported-api = false +# Tests may unwrap: a panic is how a test fails. Production code keeps the +# workspace-wide deny on unwrap_used / expect_used. +allow-unwrap-in-tests = true +allow-expect-in-tests = true diff --git a/compliance-agent/src/llm/embedding.rs b/compliance-agent/src/llm/embedding.rs index cf6f9a5..32d5a72 100644 --- a/compliance-agent/src/llm/embedding.rs +++ b/compliance-agent/src/llm/embedding.rs @@ -26,6 +26,8 @@ struct EmbeddingData { /// array (bge-multilingual-gemma2 rejects >25 with "batch size overflow"), so we /// chunk larger corpora — a whole control catalog (~1.8k) would otherwise 500. const EMBED_BATCH_SIZE: usize = 16; +// The bge backend takes at most 25 inputs per request. +const _: () = assert!(EMBED_BATCH_SIZE <= 25); // ── Embedding implementation ─────────────────────────────────── @@ -111,12 +113,4 @@ mod tests { let out = client().embed(Vec::new()).await.unwrap(); assert!(out.is_empty()); } - - #[test] - fn batch_size_is_within_backend_cap() { - assert!( - EMBED_BATCH_SIZE <= 25, - "must stay under the bge 25-input cap" - ); - } } diff --git a/compliance-agent/src/pipeline/plan.rs b/compliance-agent/src/pipeline/plan.rs index ead2c57..4cf9fae 100644 --- a/compliance-agent/src/pipeline/plan.rs +++ b/compliance-agent/src/pipeline/plan.rs @@ -155,7 +155,7 @@ mod tests { t } - fn step_for<'a>(plan: &'a ScanPlan, scan: ScanType) -> Option<&'a ScanStep> { + fn step_for(plan: &ScanPlan, scan: ScanType) -> Option<&ScanStep> { plan.steps.iter().find(|s| s.scan_type == scan) } @@ -192,7 +192,7 @@ mod tests { assert_eq!(sast.artifact_id, arc_id); } - fn unavailable_for<'a>(plan: &'a ScanPlan, scan: ScanType) -> Option<&'a UnavailableScan> { + fn unavailable_for(plan: &ScanPlan, scan: ScanType) -> Option<&UnavailableScan> { plan.unavailable.iter().find(|u| u.scan_type == scan) } diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index cf79255..ac384ad 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -143,31 +143,6 @@ fn tenants_from_env() -> Vec { .unwrap_or_else(|| vec![DEFAULT_SCHEDULER_TENANT_ID.to_string()]) } -#[cfg(test)] -mod tests { - use crate::registry::scheduler_runs_for; - - #[test] - fn ladder_filter_keeps_running_skips_read_only_and_dead() { - let rows = [ - ("a", "active"), - ("b", "trial"), - ("c", "demo"), - ("d", "warning"), - ("e", "restricted"), - ("f", "frozen"), - ("g", "halted"), - ("h", "archived"), - ]; - let out: Vec<&str> = rows - .iter() - .filter(|(_, s)| scheduler_runs_for(s)) - .map(|(id, _)| *id) - .collect(); - assert_eq!(out, vec!["a", "b", "c", "d"]); - } -} - async fn tenant_db(agent: &ComplianceAgent, tenant_id: &str) -> Option { match agent.db_pool.for_tenant_id(tenant_id).await { Ok(db) => Some(db), @@ -366,3 +341,28 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { tracing::info!("CVE monitor: no new CVEs found for tenant '{tenant_id}'"); } } + +#[cfg(test)] +mod tests { + use crate::registry::scheduler_runs_for; + + #[test] + fn ladder_filter_keeps_running_skips_read_only_and_dead() { + let rows = [ + ("a", "active"), + ("b", "trial"), + ("c", "demo"), + ("d", "warning"), + ("e", "restricted"), + ("f", "frozen"), + ("g", "halted"), + ("h", "archived"), + ]; + let out: Vec<&str> = rows + .iter() + .filter(|(_, s)| scheduler_runs_for(s)) + .map(|(id, _)| *id) + .collect(); + assert_eq!(out, vec!["a", "b", "c", "d"]); + } +} diff --git a/compliance-agent/tests/c5_example2.rs b/compliance-agent/tests/c5_example2.rs index af02a93..6995744 100644 --- a/compliance-agent/tests/c5_example2.rs +++ b/compliance-agent/tests/c5_example2.rs @@ -4,6 +4,8 @@ //! export ... (LITELLM_* + BREAKPILOT_BASE_URL) //! cargo test -p compliance-agent --test c5_example2 -- --ignored --nocapture +#![allow(clippy::expect_used, clippy::unwrap_used)] + mod common; use std::sync::Arc; diff --git a/compliance-agent/tests/c5_semantic_live.rs b/compliance-agent/tests/c5_semantic_live.rs index 11b07f1..4a83706 100644 --- a/compliance-agent/tests/c5_semantic_live.rs +++ b/compliance-agent/tests/c5_semantic_live.rs @@ -9,6 +9,8 @@ //! couple of real vulnerable findings retrieves the nearest master controls and //! grounded-judges them, stamping master-control refs. +#![allow(clippy::expect_used, clippy::unwrap_used)] + mod common; use std::sync::Arc; diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index b5c94e7..ab60f2d 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -6,6 +6,8 @@ // Included via `mod common;` in several test binaries; not every binary uses // every helper, so allow dead code here. #![allow(dead_code)] +// A test helper that cannot set up the test fails it: panicking is the point. +#![allow(clippy::expect_used, clippy::unwrap_used)] use std::sync::Arc; diff --git a/compliance-agent/tests/demo_seed.rs b/compliance-agent/tests/demo_seed.rs index f4e9cf4..e78dca8 100644 --- a/compliance-agent/tests/demo_seed.rs +++ b/compliance-agent/tests/demo_seed.rs @@ -1,4 +1,6 @@ //! Demo-target seeding API (needs Mongo; not part of the CI `--lib` run). +#![allow(clippy::expect_used, clippy::unwrap_used)] + mod common; use common::TestServer; diff --git a/compliance-agent/tests/e2e.rs b/compliance-agent/tests/e2e.rs index 577acdf..0296476 100644 --- a/compliance-agent/tests/e2e.rs +++ b/compliance-agent/tests/e2e.rs @@ -3,5 +3,7 @@ // Run with: cargo test -p compliance-agent --test e2e // Requires: MongoDB running (set TEST_MONGODB_URI if not default) +#![allow(clippy::expect_used, clippy::unwrap_used)] + mod common; mod integration; diff --git a/compliance-agent/tests/grounded_surface_live.rs b/compliance-agent/tests/grounded_surface_live.rs index f1ee4e3..f5bb83f 100644 --- a/compliance-agent/tests/grounded_surface_live.rs +++ b/compliance-agent/tests/grounded_surface_live.rs @@ -7,6 +7,8 @@ //! (no rate limiting, no security logging, unverified update) and checks that the //! grounded checker produces control-tagged findings. +#![allow(clippy::expect_used, clippy::unwrap_used)] + mod common; use std::sync::Arc; diff --git a/compliance-agent/tests/integration/api/cascade_delete.rs b/compliance-agent/tests/integration/api/cascade_delete.rs index 07cb647..3208b20 100644 --- a/compliance-agent/tests/integration/api/cascade_delete.rs +++ b/compliance-agent/tests/integration/api/cascade_delete.rs @@ -6,7 +6,7 @@ async fn insert_dast_target(server: &TestServer, repo_id: &str, name: &str) -> S let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let result = db .collection::("dast_targets") @@ -30,7 +30,7 @@ async fn insert_pentest_session(server: &TestServer, target_id: &str, repo_id: & let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let result = db .collection::("pentest_sessions") @@ -54,7 +54,7 @@ async fn insert_attack_node(server: &TestServer, session_id: &str) { let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); db.collection::("attack_chain_nodes") .insert_one(mongodb::bson::doc! { @@ -73,7 +73,7 @@ async fn insert_dast_finding(server: &TestServer, target_id: &str, session_id: & let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); db.collection::("dast_findings") .insert_one(mongodb::bson::doc! { @@ -99,7 +99,7 @@ async fn count_docs(server: &TestServer, collection: &str) -> u64 { let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); db.collection::(collection) .count_documents(mongodb::bson::doc! {}) .await @@ -175,7 +175,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() { let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let now = mongodb::bson::DateTime::now(); db.collection::("findings") diff --git a/compliance-agent/tests/integration/api/findings.rs b/compliance-agent/tests/integration/api/findings.rs index ad747a9..3637ce8 100644 --- a/compliance-agent/tests/integration/api/findings.rs +++ b/compliance-agent/tests/integration/api/findings.rs @@ -14,7 +14,7 @@ async fn insert_finding(server: &TestServer, repo_id: &str, title: &str, severit // Get the DB name from the test server by parsing the health response // For now, we use a direct insert approach - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let now = mongodb::bson::DateTime::now(); db.collection::("findings") diff --git a/compliance-agent/tests/integration/api/stats.rs b/compliance-agent/tests/integration/api/stats.rs index 3997f8c..f66b5f1 100644 --- a/compliance-agent/tests/integration/api/stats.rs +++ b/compliance-agent/tests/integration/api/stats.rs @@ -21,7 +21,7 @@ async fn stats_overview_reflects_inserted_data() { let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let now = mongodb::bson::DateTime::now(); for (title, severity) in [ @@ -68,7 +68,7 @@ async fn stats_update_after_finding_status_change() { let mongodb_uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); - let db = client.database(&server.db_name()); + let db = client.database(server.db_name()); let now = mongodb::bson::DateTime::now(); let result = db diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 21fe9e1..e4ba427 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -158,6 +158,27 @@ impl SkippedStage { } } +impl ScanRun { + pub fn new(repo_id: String, trigger: ScanTrigger) -> Self { + Self { + id: None, + repo_id, + trigger, + commit_sha: None, + status: ScanRunStatus::Running, + current_phase: ScanPhase::ChangeDetection, + phases_completed: Vec::new(), + new_findings_count: 0, + error_message: None, + started_at: Utc::now(), + completed_at: None, + skipped_stages: Vec::new(), + languages: Vec::new(), + planned_phases: Vec::new(), + } + } +} + #[cfg(test)] mod skipped_stage_tests { use super::{ScanRun, ScanTrigger, SkippedStage}; @@ -199,24 +220,3 @@ mod skipped_stage_tests { assert!(back.skipped_stages.is_empty()); } } - -impl ScanRun { - pub fn new(repo_id: String, trigger: ScanTrigger) -> Self { - Self { - id: None, - repo_id, - trigger, - commit_sha: None, - status: ScanRunStatus::Running, - current_phase: ScanPhase::ChangeDetection, - phases_completed: Vec::new(), - new_findings_count: 0, - error_message: None, - started_at: Utc::now(), - completed_at: None, - skipped_stages: Vec::new(), - languages: Vec::new(), - planned_phases: Vec::new(), - } - } -} diff --git a/compliance-core/src/scan_matrix.rs b/compliance-core/src/scan_matrix.rs index e463494..5ce6b8d 100644 --- a/compliance-core/src/scan_matrix.rs +++ b/compliance-core/src/scan_matrix.rs @@ -451,7 +451,7 @@ mod tests { t } - fn option<'a>(opts: &'a [ScanOption], scan: ScanType) -> Option<&'a ScanOption> { + fn option(opts: &[ScanOption], scan: ScanType) -> Option<&ScanOption> { opts.iter().find(|o| o.scan == scan) } diff --git a/compliance-core/tests/models.rs b/compliance-core/tests/models.rs index d1702ba..b13679b 100644 --- a/compliance-core/tests/models.rs +++ b/compliance-core/tests/models.rs @@ -374,22 +374,6 @@ fn sbom_entry_new_defaults() { assert!(e.known_vulnerabilities.is_empty()); } -// ─── TrackedRepository ─── - -#[test] -fn tracked_repository_new_defaults() { - let r = TrackedRepository::new("My Repo".into(), "https://github.com/org/repo.git".into()); - assert_eq!(r.name, "My Repo"); - assert_eq!(r.git_url, "https://github.com/org/repo.git"); - assert_eq!(r.default_branch, "main"); - assert!(!r.webhook_enabled); - assert!(r.webhook_secret.is_some()); - // Webhook secret should be 32 hex chars (UUID without dashes) - assert_eq!(r.webhook_secret.as_ref().unwrap().len(), 32); - assert!(r.tracker_type.is_none()); - assert_eq!(r.findings_count, 0); -} - // ─── ScanTrigger ─── #[test] diff --git a/compliance-dashboard/src/infrastructure/session_store.rs b/compliance-dashboard/src/infrastructure/session_store.rs index a006d47..81471b6 100644 --- a/compliance-dashboard/src/infrastructure/session_store.rs +++ b/compliance-dashboard/src/infrastructure/session_store.rs @@ -210,9 +210,9 @@ mod tests { #[test] fn a_hardened_dashboard_needs_the_session_key() { - let err = parse_session_key("", AppEnv::Staging) - .err() - .expect("refused"); + let Err(err) = parse_session_key("", AppEnv::Staging) else { + panic!("a hardened dashboard must refuse to start without the key"); + }; assert!(err.to_string().contains("DASHBOARD_SESSION_KEY")); assert!(parse_session_key("", AppEnv::Dev).is_ok()); } -- 2.54.1