refactor(PR-02): protocol/reader architecture, /api/documents and reader IA
- migrate crate to RFC-0002 §5.3 Reader layout: src/protocol/{analysis_v2,
trace_v2,tool_v1}.rs, src/reader/{source,markdown,model,assemble,render,
assets}.rs, src/config.rs; lib.rs is the composition root; delete app/project/
semantic/trace/document/presentation/source_map/render/assets top-level files
- split presentation into model (types) and assemble (merge/stale/DocumentService)
- merge controlled project root/path boundary and UTF-8 byte spans into
reader/source.rs; move view.json config to config.rs
- replace GET /api/document with read-only GET /api/documents (documents list +
current outline/function/analysis summary) and add contract tests
- reading UI: drop variable/memory placeholder actions, keep one explicit
unsupported explanation, add simple dark theme toggle over the single token
layer; assert via rendering test
- reorganize tests into Cargo [[test]] suites tests/contract and
tests/integration; record docs/evidence/PR-02
- unit 41 + contract 41 + integration 33 all pass; clippy clean
This commit is contained in:
1 parent
5a61788bc9
commit
5c9a313424
43 files changed
+1222
-936
No files matched your search
@@ -0,0 +1,87 @@
|
||||
//! Asset provenance and integrity: the three reused legacy visual assets are
|
||||
//! pinned by SHA-256 in `assets/licenses/ASSETS.md` and embedded by
|
||||
//! `src/assets.rs` (ADR-0002).
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(bytes);
|
||||
let mut out = String::with_capacity(64);
|
||||
for byte in hasher.finalize() {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(out, "{byte:02x}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_assets_match_their_recorded_hashes() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
for (file, expected) in [
|
||||
(
|
||||
"assets/logo.svg",
|
||||
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
|
||||
),
|
||||
(
|
||||
"assets/blossom.webp",
|
||||
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
|
||||
),
|
||||
(
|
||||
"assets/feather.webp",
|
||||
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
|
||||
),
|
||||
] {
|
||||
let bytes =
|
||||
std::fs::read(root.join(file)).unwrap_or_else(|err| panic!("read {file}: {err}"));
|
||||
assert_eq!(sha256_hex(&bytes), expected, "{file} digest changed");
|
||||
}
|
||||
let licenses = std::fs::read_to_string(root.join("assets/licenses/ASSETS.md")).unwrap();
|
||||
for expected in [
|
||||
"52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe",
|
||||
"901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00",
|
||||
"fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de",
|
||||
"Apache-2.0",
|
||||
] {
|
||||
assert!(licenses.contains(expected), "ASSETS.md misses {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_asset_bundle_matches_disk_and_has_one_theme() {
|
||||
let bundle = marqdo_view::reader::assets::AssetBundle::get();
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let css = std::fs::read(root.join("assets/reader.css")).unwrap();
|
||||
assert_eq!(sha256_hex(&css), bundle.css().sha256);
|
||||
let js = std::fs::read(root.join("assets/reader.js")).unwrap();
|
||||
assert_eq!(sha256_hex(&js), bundle.js().sha256);
|
||||
assert_eq!(
|
||||
bundle
|
||||
.all()
|
||||
.iter()
|
||||
.filter(|asset| asset.extension == "css" || asset.extension == "js")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_has_one_token_layer_and_no_legacy_skin() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let css = std::fs::read_to_string(root.join("assets/reader.css")).unwrap();
|
||||
assert_eq!(css.matches("@layer tokens").count(), 1);
|
||||
assert!(css.contains(
|
||||
"@layer reset, tokens, layout, typography, semantics, overlays, interactions, responsive;"
|
||||
));
|
||||
for banned in ["notebook-page", "reader-page", "legacy.css", "new.css"] {
|
||||
assert!(!css.contains(banned), "legacy skin marker {banned} in CSS");
|
||||
}
|
||||
assert!(
|
||||
!css.contains("!important"),
|
||||
"the theme must not rely on !important overrides"
|
||||
);
|
||||
// No remote font/CDN requests.
|
||||
for banned in ["@font-face", "fonts.googleapis", "https://"] {
|
||||
assert!(!css.contains(banned), "remote resource marker {banned}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! CLI surface tests: this program owns its own help/subcommands and refuses
|
||||
//! unsafe defaults. Exit codes follow RFC-VIEW-0001 §10.2.
|
||||
|
||||
use crate::common;
|
||||
|
||||
use common::run_view;
|
||||
|
||||
fn clean_env() -> Vec<(&'static str, Option<&'static str>)> {
|
||||
vec![
|
||||
("MARQDO_BIN", None),
|
||||
("MARQDO_TOOL_PROTOCOL", None),
|
||||
("MARQDO_PROTOCOL_ANALYSIS", None),
|
||||
("MARQDO_PROTOCOL_TRACE", None),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_comes_from_view_not_core() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let output = run_view(&["--help"], &cwd, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
for needle in ["marqdo-view", "export", "verify", "PATH", "--marqdo-bin"] {
|
||||
assert!(
|
||||
stdout.contains(needle),
|
||||
"missing {needle} in help:\n{stdout}"
|
||||
);
|
||||
}
|
||||
// The Core's own help wording must not leak here.
|
||||
assert!(!stdout.contains("Statically check a document"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_is_the_tool_version() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let output = run_view(&["--version"], &cwd, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("marqdo-view 0.2.0"), "{stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_requires_an_output_directory() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let output = run_view(&["export", "example.mq.md"], &cwd, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_loopback_bind_is_refused_by_default() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let output = run_view(&["--host", "0.0.0.0"], &cwd, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stderr.contains("view.bind_denied"), "{stderr}");
|
||||
assert!(stderr.contains("--unsafe-expose"), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browse_on_missing_path_fails_without_starting_a_server() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let output = run_view(
|
||||
&["definitely-missing.mq.md", "--no-open"],
|
||||
&cwd,
|
||||
&clean_env(),
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("view.io"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degradation_without_core_keeps_prose_readable() {
|
||||
// The reader must degrade to prose-only with an explicit status, never
|
||||
// invent semantic annotations or a fake run state.
|
||||
let project = common::TempProject::new("cli-degrade-no-core");
|
||||
project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n");
|
||||
// Explicitly point at a missing core so the test is independent of the
|
||||
// caller environment (acceptance scripts export MARQDO_BIN).
|
||||
let context = marqdo_view::reader::assemble::DocumentService::open(
|
||||
&project.dir,
|
||||
Some(std::path::Path::new("/definitely/missing/marqdo-frozen")),
|
||||
)
|
||||
.unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
let model = context.load(&relative).unwrap();
|
||||
assert_eq!(model.source_status.data_value(), "core-unavailable");
|
||||
assert!(model.semantic.is_none());
|
||||
assert!(model.document.plain_text().contains("正文"));
|
||||
assert!(model.status_note.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_without_core_is_an_argument_error() {
|
||||
let project = common::TempProject::new("cli-verify-no-core");
|
||||
project.marqdo_project("# @knowledge fixture\n");
|
||||
let output = run_view(&["verify", "index.mq.md"], &project.dir, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stderr.contains("view.core_missing"), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_document_is_an_io_error() {
|
||||
let project = common::TempProject::new("cli-missing-doc");
|
||||
let output = run_view(&["verify", "missing.mq.md"], &project.dir, &clean_env());
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("view.io"));
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Contract tests against a real fake-core executable: argv shape, exit codes,
|
||||
//! stderr handling, temp artifacts and process-tree cleanup.
|
||||
//!
|
||||
//! The fake core is a shell script, not a mocked Rust trait, so everything at
|
||||
//! the process boundary is exercised for real.
|
||||
|
||||
use crate::common;
|
||||
|
||||
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
|
||||
use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions};
|
||||
use marqdo_view::reader::source::Project;
|
||||
|
||||
fn fixture(name: &str) -> (TempProject, FakeCore) {
|
||||
let project = TempProject::new(name);
|
||||
project.marqdo_project("# @knowledge fixture\n");
|
||||
let core = FakeCore::new(&format!("{name}-core"));
|
||||
(project, core)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_returns_exact_analysis_bytes_and_digest() {
|
||||
let (project, core) = fixture("check_ok");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
let analysis = minimal_analysis("index.mq.md", &sha256_hex(&source), 2);
|
||||
core.set_analysis(&analysis);
|
||||
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let output = expect_check_ok(
|
||||
client
|
||||
.check(&project, &entry, &CheckOptions::default())
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
assert_eq!(output.analysis_bytes, analysis.as_bytes());
|
||||
assert_eq!(output.analysis_sha256, sha256_hex(analysis.as_bytes()));
|
||||
assert_eq!(
|
||||
output.analysis_digest,
|
||||
format!("sha256:{}", sha256_hex(analysis.as_bytes()))
|
||||
);
|
||||
let args = core.last_args();
|
||||
assert_eq!(args[0], "check");
|
||||
assert!(args.contains(&"--emit".to_string()));
|
||||
// No `--refs` unless requested.
|
||||
assert!(!args.contains(&"--refs".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_refs_is_forwarded_as_a_stricter_flag() {
|
||||
let (project, core) = fixture("check_refs");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
expect_check_ok(
|
||||
client
|
||||
.check(
|
||||
&project,
|
||||
&entry,
|
||||
&CheckOptions {
|
||||
refs: true,
|
||||
timeout: None,
|
||||
},
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(core.last_args().contains(&"--refs".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_failure_preserves_core_stderr_and_code() {
|
||||
let (project, core) = fixture("check_fail");
|
||||
core.set_check(1, "index.mq.md:3:1: sem.unclosed_control\n");
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let response = client
|
||||
.check(&project, &entry, &CheckOptions::default())
|
||||
.unwrap();
|
||||
assert!(!response.success);
|
||||
assert_eq!(response.exit_code, 1);
|
||||
assert!(response.stderr.contains("sem.unclosed_control"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_returns_json_and_raw_trace() {
|
||||
let (project, core) = fixture("run_ok");
|
||||
core.set_run(
|
||||
0,
|
||||
r#"{"command":"run","success":true,"stdout":"ok","stderr":"","trace":[]}"#,
|
||||
Some(r#"{"schema":"marqdo.trace","schema_version":2,"events":[]}"#),
|
||||
);
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let output = client
|
||||
.run(&project, &entry, &RunOptions::default())
|
||||
.unwrap();
|
||||
assert_eq!(output.exit_code, 0);
|
||||
assert_eq!(output.json["success"], true);
|
||||
let trace = output.trace_bytes.expect("trace bytes");
|
||||
assert_eq!(output.trace_sha256.unwrap(), sha256_hex(&trace));
|
||||
// Mode is always explicit; pure is the View default.
|
||||
let args = core.last_args();
|
||||
assert!(args.contains(&"--mode".to_string()));
|
||||
let mode_index = args.iter().position(|a| a == "--mode").unwrap();
|
||||
assert_eq!(args[mode_index + 1], "pure");
|
||||
assert!(args.contains(&"--json".to_string()));
|
||||
assert!(args.contains(&"--trace-file".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_without_trace_file_reports_no_trace() {
|
||||
let (project, core) = fixture("run_no_trace");
|
||||
core.set_run(
|
||||
0,
|
||||
r#"{"command":"run","success":true,"stdout":"","stderr":"","trace":[]}"#,
|
||||
None,
|
||||
);
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let output = client
|
||||
.run(&project, &entry, &RunOptions::default())
|
||||
.unwrap();
|
||||
assert!(output.trace_bytes.is_none());
|
||||
assert!(output.trace_sha256.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_invalid_json_is_a_protocol_io_error() {
|
||||
let (project, core) = fixture("run_bad_json");
|
||||
core.set_run(0, "this is not json", None);
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let err = client
|
||||
.run(&project, &entry, &RunOptions::default())
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.io");
|
||||
assert!(err.to_string().contains("exactly one JSON"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_kills_the_process_group_and_reports_timeout() {
|
||||
let (project, core) = fixture("run_timeout");
|
||||
core.set_sleep_seconds(5);
|
||||
core.set_run(0, r#"{"command":"run","success":true}"#, None);
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let err = client
|
||||
.run(
|
||||
&project,
|
||||
&entry,
|
||||
&RunOptions {
|
||||
view_timeout: Some(std::time::Duration::from_millis(300)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(err.code(), "view.core_timeout");
|
||||
assert!(
|
||||
elapsed < std::time::Duration::from_secs(3),
|
||||
"timeout took {elapsed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_product_version_is_rejected_before_any_work() {
|
||||
let (project, core) = fixture("version_old");
|
||||
core.set_version("marqdo 2.9.1\n");
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let err = client.negotiate().unwrap_err();
|
||||
assert_eq!(err.code(), "view.protocol_incompatible");
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
// Only `--version` was invoked; no check/run happened.
|
||||
assert_eq!(core.last_args(), vec!["--version".to_string()]);
|
||||
let _ = project;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_emit_after_success_is_an_analysis_failure() {
|
||||
// Fake core exits 0 but writes nothing: never accept a phantom analysis.
|
||||
let (project, core) = fixture("check_no_emit");
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let err = client
|
||||
.check(&project, &entry, &CheckOptions::default())
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.analysis_failed");
|
||||
}
|
||||
|
||||
fn expect_check_ok(response: CheckResponse) -> marqdo_view::core_client::CheckOutput {
|
||||
assert!(response.success, "check failed: {:?}", response.diagnostics);
|
||||
response.analysis.expect("analysis on success")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_check_normalizes_diagnostics_without_absolute_paths() {
|
||||
let (project, core) = fixture("check_diagnostics");
|
||||
core.set_check(1, "");
|
||||
core.set_check_json(
|
||||
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/project/index.mq.md","hints":[],"line":5,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
|
||||
);
|
||||
let client = CoreClient::with_bin(&core.script).unwrap();
|
||||
let project = Project::open(&project.path("index.mq.md")).unwrap();
|
||||
let entry = project.entry().relative.clone();
|
||||
let response = client
|
||||
.check(&project, &entry, &CheckOptions::default())
|
||||
.unwrap();
|
||||
assert!(!response.success);
|
||||
assert_eq!(response.diagnostics.len(), 1);
|
||||
assert_eq!(response.diagnostics[0].code, "sem.unclosed_control");
|
||||
assert_eq!(response.diagnostics[0].line, Some(5));
|
||||
// The raw absolute `file` field is not part of the normalized type at all.
|
||||
let rendered = serde_json::to_string(&response.diagnostics).unwrap();
|
||||
assert!(!rendered.contains("/home/secret"), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_verify_end_to_end_against_fake_core() {
|
||||
let (project, core) = fixture("verify_cli");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
|
||||
let script = core.script.to_str().unwrap().to_string();
|
||||
let dir = project.dir.to_str().unwrap().to_string();
|
||||
let output = common::run_view(
|
||||
&["verify", "index.mq.md", "--marqdo-bin", &script],
|
||||
std::path::Path::new(&dir),
|
||||
&[
|
||||
("MARQDO_BIN", None),
|
||||
("MARQDO_TOOL_PROTOCOL", None),
|
||||
("MARQDO_PROTOCOL_ANALYSIS", None),
|
||||
("MARQDO_PROTOCOL_TRACE", None),
|
||||
],
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(0), "stderr: {stderr}");
|
||||
assert!(stdout.contains("result: PASS"), "{stdout}");
|
||||
assert!(stdout.contains("marqdo 3.0.0-beta.1"), "{stdout}");
|
||||
assert!(!stdout.contains(&dir), "absolute path leaked: {stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_verify_rejects_schema_v3_and_digest_mismatch() {
|
||||
let (project, core) = fixture("verify_negative");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
let script = core.script.to_str().unwrap().to_string();
|
||||
let dir = project.dir.to_str().unwrap().to_string();
|
||||
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3));
|
||||
let output = common::run_view(
|
||||
&["verify", "index.mq.md", "--marqdo-bin", &script],
|
||||
std::path::Path::new(&dir),
|
||||
&[("MARQDO_BIN", None)],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("view.protocol_incompatible"));
|
||||
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
|
||||
let output = common::run_view(
|
||||
&["verify", "index.mq.md", "--marqdo-bin", &script],
|
||||
std::path::Path::new(&dir),
|
||||
&[("MARQDO_BIN", None)],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("view.source_mismatch"));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Contract suite: the frozen CLI black-box process contract, Analysis v2 /
|
||||
//! Trace v2 validation, the View CLI surface, and architecture/asset gates.
|
||||
|
||||
#[path = "../common/mod.rs"]
|
||||
mod common;
|
||||
|
||||
mod asset_integrity;
|
||||
mod cli_surface;
|
||||
mod core_contract;
|
||||
mod no_coupling;
|
||||
mod presentation_states;
|
||||
mod trace_contract;
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Architectural gates (RFC-VIEW-0001 §17.2): no private Core crates, no
|
||||
//! source-tree reads of the legacy repositories, no second renderer, no shell
|
||||
//! execution, one CSS/JS entry point.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn manifest_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).unwrap_or_else(|err| panic!("read {}: {err}", path.display()))
|
||||
}
|
||||
|
||||
fn collect_files(dir: &Path, extension: &str, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_files(&path, extension, out);
|
||||
} else if path.extension().and_then(|e| e.to_str()) == Some(extension) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_private_core_crate_dependencies() {
|
||||
let root = manifest_dir();
|
||||
let forbidden = [
|
||||
"marqdo",
|
||||
"marqdo-cli",
|
||||
"marqdo-ir",
|
||||
"marqdo-runtime",
|
||||
"marqdo-frontend",
|
||||
"marqdo-host",
|
||||
"marqdo-markdown",
|
||||
"marqdo-span",
|
||||
"marqdo-expression",
|
||||
"marqdo-sema",
|
||||
];
|
||||
let mut in_dependency_section = false;
|
||||
for line in read(&root.join("Cargo.toml")).lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with('[') {
|
||||
in_dependency_section = trimmed.ends_with("dependencies]")
|
||||
|| trimmed.contains("dependencies.")
|
||||
|| trimmed.contains("dependencies]");
|
||||
continue;
|
||||
}
|
||||
if !in_dependency_section || trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((name, _)) = trimmed.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let name = name.trim().trim_matches('"');
|
||||
assert!(
|
||||
!forbidden.contains(&name),
|
||||
"Cargo.toml declares forbidden Core dependency {name:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let lock = read(&root.join("Cargo.lock"));
|
||||
for line in lock.lines() {
|
||||
let Some(rest) = line.trim().strip_prefix("name = \"") else {
|
||||
continue;
|
||||
};
|
||||
let name = rest.trim_end_matches('"');
|
||||
if name == "marqdo-view" {
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
!name.starts_with("marqdo") || name == "marqdo",
|
||||
"Cargo.lock contains suspicious package {name:?}"
|
||||
);
|
||||
assert!(
|
||||
!forbidden.contains(&name),
|
||||
"Cargo.lock contains forbidden Core package {name:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_never_reads_or_links_the_legacy_repositories() {
|
||||
let root = manifest_dir();
|
||||
let mut sources = Vec::new();
|
||||
collect_files(&root.join("src"), "rs", &mut sources);
|
||||
assert!(!sources.is_empty(), "src/ has no Rust sources");
|
||||
let needles = [
|
||||
["marqdo", "_ir"].concat(),
|
||||
["marqdo", "-ir"].concat(),
|
||||
["marqdo", "_runtime"].concat(),
|
||||
["marqdo", "-runtime"].concat(),
|
||||
["marqdo", "_frontend"].concat(),
|
||||
["marqdo", "-frontend"].concat(),
|
||||
["marqdo", "::"].concat(),
|
||||
["..", "/marqdo"].concat(),
|
||||
["..", "/marqdo-cli"].concat(),
|
||||
["inspect", " --ir"].concat(),
|
||||
["Command::new", "(\"sh\")"].concat(),
|
||||
["Command::new", "(\"bash\")"].concat(),
|
||||
["sh", " -c"].concat(),
|
||||
["bash", " -c"].concat(),
|
||||
];
|
||||
for path in sources {
|
||||
let text = read(&path);
|
||||
for (line_number, line) in text.lines().enumerate() {
|
||||
let trimmed = line.trim_start();
|
||||
// Documentation may *name* forbidden APIs when explaining what is
|
||||
// not used; the gate only scans executable source lines.
|
||||
if trimmed.starts_with("//") {
|
||||
continue;
|
||||
}
|
||||
for needle in &needles {
|
||||
assert!(
|
||||
!line.contains(needle.as_str()),
|
||||
"{}:{} contains forbidden reference {:?}",
|
||||
path.display(),
|
||||
line_number + 1,
|
||||
needle
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_one_reader_theme_and_script_entry() {
|
||||
let root = manifest_dir();
|
||||
let assets = root.join("assets");
|
||||
let mut css = Vec::new();
|
||||
let mut js = Vec::new();
|
||||
collect_files(&assets, "css", &mut css);
|
||||
collect_files(&assets, "js", &mut js);
|
||||
assert_eq!(css.len(), 1, "exactly one CSS entry: {css:?}");
|
||||
assert_eq!(js.len(), 1, "exactly one JS entry: {js:?}");
|
||||
for path in &css {
|
||||
assert_eq!(
|
||||
path.file_name().and_then(|n| n.to_str()),
|
||||
Some("reader.css"),
|
||||
"the only CSS entry must be assets/reader.css"
|
||||
);
|
||||
}
|
||||
for path in &js {
|
||||
assert_eq!(
|
||||
path.file_name().and_then(|n| n.to_str()),
|
||||
Some("reader.js"),
|
||||
"the only JS entry must be assets/reader.js"
|
||||
);
|
||||
}
|
||||
// The source tree must not reference legacy skin names at all.
|
||||
let mut sources = Vec::new();
|
||||
collect_files(&root.join("src"), "rs", &mut sources);
|
||||
for path in sources {
|
||||
let text = read(&path);
|
||||
for needle in ["notebook-page", "reader-page", "legacy.css", "new.css"] {
|
||||
assert!(
|
||||
!text.contains(needle),
|
||||
"{} references legacy skin marker {needle:?}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_manifest_matches_package_and_protocols() {
|
||||
let root = manifest_dir();
|
||||
let raw = read(&root.join("tool.json"));
|
||||
let tool: serde_json::Value = serde_json::from_str(&raw).expect("tool.json is JSON");
|
||||
assert_eq!(tool["schema"], "marqdo.cli-tool");
|
||||
assert_eq!(tool["schema_version"], 1);
|
||||
assert_eq!(tool["name"], "marqdo-view");
|
||||
assert_eq!(tool["command"], "view");
|
||||
assert_eq!(tool["entrypoint"], "bin/marqdo-view");
|
||||
assert_eq!(
|
||||
tool["version"],
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
"tool.json version must match Cargo package version"
|
||||
);
|
||||
assert_eq!(tool["compatibility"]["marqdo"], ">=3.0.0-beta.1,<4.0.0");
|
||||
assert_eq!(tool["compatibility"]["analysis"], serde_json::json!([2]));
|
||||
assert_eq!(tool["compatibility"]["trace"], serde_json::json!([2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_lockfile_is_committed() {
|
||||
let root = manifest_dir();
|
||||
assert!(
|
||||
root.join("Cargo.lock").is_file(),
|
||||
"Cargo.lock must be committed for --locked release builds"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Degradation/state matrix contract (RFC-VIEW-0001 S-05..S-07, §12.3):
|
||||
//! prose stays readable while semantics become explicitly unusable.
|
||||
|
||||
use crate::common;
|
||||
|
||||
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
|
||||
use marqdo_view::reader::assemble::DocumentService;
|
||||
use marqdo_view::reader::model::SourceStatus;
|
||||
|
||||
fn project(name: &str) -> (TempProject, FakeCore) {
|
||||
let project = TempProject::new(name);
|
||||
project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**,包含 `n`。\n");
|
||||
let core = FakeCore::new(&format!("{name}-core"));
|
||||
(project, core)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_check_keeps_prose_and_shows_core_diagnostics() {
|
||||
let (project, core) = project("state-check-fail");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
// Emit a broken analysis too; it must NOT be used after a failed check.
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
|
||||
core.set_check(1, "");
|
||||
core.set_check_json(
|
||||
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/index.mq.md","line":3,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
|
||||
);
|
||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
let model = context.load(&relative).unwrap();
|
||||
assert_eq!(model.source_status, SourceStatus::CoreError);
|
||||
assert!(
|
||||
model.semantic.is_none(),
|
||||
"failed check must revoke semantics"
|
||||
);
|
||||
assert!(model.document.plain_text().contains("正文"));
|
||||
assert!(model
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code == "sem.unclosed_control"));
|
||||
assert!(!model.source_status.semantics_usable());
|
||||
// Pending run state is explicit, never a success claim.
|
||||
assert_eq!(model.run_state().data_value(), "not-run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_digest_mismatch_degrades_instead_of_misbinding() {
|
||||
let (project, core) = project("state-source-mismatch");
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
|
||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
let model = context.load(&relative).unwrap();
|
||||
assert_eq!(model.source_status, SourceStatus::SourceMismatch);
|
||||
assert!(model.semantic.is_none());
|
||||
assert!(model.source_status.label().contains("不一致"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_analysis_schema_is_a_hard_protocol_error() {
|
||||
let (project, core) = project("state-protocol");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3));
|
||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
let err = context.load(&relative).unwrap_err();
|
||||
assert_eq!(err.code(), "view.protocol_incompatible");
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_core_span_is_dropped_with_an_explicit_warning() {
|
||||
let (project, core) = project("state-span-invalid");
|
||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||
let mut analysis: serde_json::Value =
|
||||
serde_json::from_str(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2)).unwrap();
|
||||
// A span in the middle of a multi-byte character / beyond EOF.
|
||||
analysis["modules"][0]["units"] = serde_json::json!([{
|
||||
"id": "x", "name": "坏", "level": 1, "kind": "namespace", "function": null,
|
||||
"span": {"start": 0, "end": 999_999}
|
||||
}]);
|
||||
core.set_analysis(&serde_json::to_string(&analysis).unwrap());
|
||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
let model = context.load(&relative).unwrap();
|
||||
assert_eq!(model.source_status, SourceStatus::StaticOk);
|
||||
assert!(model.semantic.as_ref().unwrap().units.is_empty());
|
||||
assert!(model
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|warning| warning.code == "view.source_span_invalid"));
|
||||
let _ = source;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_attached_to_changed_source_becomes_stale() {
|
||||
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let project = TempProject::new("state-stale-run");
|
||||
project.write(
|
||||
"marqdo.yaml",
|
||||
"project:\n name: control-flow\n version: 0.1.0\n",
|
||||
);
|
||||
let source =
|
||||
std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap();
|
||||
project.write("index.mq.md", &source);
|
||||
let core = FakeCore::new("state-stale-run-core");
|
||||
let analysis =
|
||||
std::fs::read(repo_root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
|
||||
core.set_analysis(std::str::from_utf8(&analysis).unwrap());
|
||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||
let relative = context.project().entry().relative.clone();
|
||||
|
||||
// Build a verified run directly from the golden trace + golden analysis.
|
||||
let source_index = marqdo_view::reader::source::SourceIndex::new(&source);
|
||||
let verified_analysis = marqdo_view::protocol::analysis_v2::verify_analysis(
|
||||
&analysis,
|
||||
&source,
|
||||
&source_index,
|
||||
"index.mq.md",
|
||||
)
|
||||
.unwrap();
|
||||
let trace =
|
||||
std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.trace.json")).unwrap();
|
||||
let run_json: serde_json::Value = serde_json::from_slice(
|
||||
&std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.run.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let run = marqdo_view::protocol::trace_v2::verify_trace(
|
||||
marqdo_view::protocol::trace_v2::TraceVerificationInput {
|
||||
trace_bytes: &trace,
|
||||
analysis_bytes: &analysis,
|
||||
semantic: &verified_analysis.projection,
|
||||
modules: &verified_analysis.projection.modules,
|
||||
source: &source,
|
||||
source_index: &source_index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let attached = context.load_with_run(&relative, Some(&run)).unwrap();
|
||||
assert_eq!(attached.run_state().data_value(), "succeeded");
|
||||
|
||||
// Change the source and rebuild through the same server path.
|
||||
std::fs::write(
|
||||
project.path("index.mq.md"),
|
||||
format!("{source}\n<!-- changed -->\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let changed = context.load_with_run(&relative, Some(&run)).unwrap();
|
||||
assert!(
|
||||
changed.run_state().data_value() == "stale"
|
||||
|| changed.source_status == SourceStatus::SourceMismatch,
|
||||
"expected stale/source-mismatch, got run={} source={}",
|
||||
changed.run_state().data_value(),
|
||||
changed.source_status.data_value()
|
||||
);
|
||||
if let Some(run) = &changed.run {
|
||||
assert!(run.events.iter().all(|event| event.anchor_span.is_none()));
|
||||
}
|
||||
let _ = core;
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Trace v2 contract tests against goldens emitted by the frozen CLI. The
|
||||
//! goldens bind to the committed Analysis v2 bytes by digest, so a changed
|
||||
//! source cannot silently reuse an old trace.
|
||||
|
||||
use marqdo_view::protocol::analysis_v2 as semantic;
|
||||
use marqdo_view::protocol::trace_v2::{verify_trace, RunDisplayState, TraceVerificationInput};
|
||||
use marqdo_view::reader::source::{sha256_prefixed, SourceIndex};
|
||||
use serde_json::Value;
|
||||
|
||||
struct Fixture {
|
||||
source: String,
|
||||
index: SourceIndex,
|
||||
analysis: Vec<u8>,
|
||||
semantic: semantic::VerifiedAnalysis,
|
||||
}
|
||||
|
||||
fn fixture(analysis_golden: &str, source_path: &str) -> Fixture {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let source = std::fs::read_to_string(root.join(source_path)).unwrap();
|
||||
let index = SourceIndex::new(&source);
|
||||
let analysis = std::fs::read(root.join(analysis_golden)).unwrap();
|
||||
let semantic = semantic::verify_analysis(&analysis, &source, &index, "index.mq.md").unwrap();
|
||||
Fixture {
|
||||
source,
|
||||
index,
|
||||
analysis,
|
||||
semantic,
|
||||
}
|
||||
}
|
||||
|
||||
fn golden_json(path: &str) -> Value {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
serde_json::from_slice(&std::fs::read(root.join(path)).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn golden_bytes(path: &str) -> Vec<u8> {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
std::fs::read(root.join(path)).unwrap()
|
||||
}
|
||||
|
||||
fn verify(
|
||||
fixture: &Fixture,
|
||||
trace_golden: &str,
|
||||
run_golden: &str,
|
||||
exit_code: i32,
|
||||
) -> marqdo_view::protocol::trace_v2::VerifiedRun {
|
||||
let trace = golden_bytes(trace_golden);
|
||||
let run_json = golden_json(run_golden);
|
||||
verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code,
|
||||
})
|
||||
.expect("trace verifies")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_control_flow_trace_binds_and_projects_events() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/control-flow.trace.json",
|
||||
"tests/golden/trace-v2/control-flow.run.json",
|
||||
0,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Succeeded);
|
||||
assert_eq!(projection.counts.total(), 285);
|
||||
assert_eq!(projection.entry_event_count, 18);
|
||||
assert_eq!(projection.other_event_count, 267);
|
||||
assert_eq!(projection.run_status, "ok");
|
||||
assert!(projection.truncated.is_none());
|
||||
assert_eq!(projection.stdout, "0\n0\n2\n");
|
||||
let value = projection.result_value.as_ref().expect("return value");
|
||||
assert_eq!(value.ty, "int");
|
||||
assert_eq!(value.display, "3");
|
||||
// Public JSON final value only; never a per-assignment value claim.
|
||||
assert!(projection.analysis_digest.starts_with("sha256:"));
|
||||
|
||||
// The loop header is evaluated four times (three iterations + exit).
|
||||
let loop_span = projection
|
||||
.events
|
||||
.iter()
|
||||
.find(|event| event.anchor_span.is_some() && event.detail.as_deref() == Some("exit"))
|
||||
.and_then(|event| event.anchor_span)
|
||||
.expect("loop anchor");
|
||||
let summary = projection.anchor_summary(loop_span).expect("loop summary");
|
||||
assert_eq!(summary.count, 4);
|
||||
assert_eq!(summary.detail, "loop exit");
|
||||
assert!(summary.kinds.contains(&"loop.iteration".to_string()));
|
||||
|
||||
let return_anchors: Vec<_> = projection
|
||||
.events
|
||||
.iter()
|
||||
.filter(|event| event.anchor_span.is_some())
|
||||
.collect();
|
||||
assert!(!return_anchors.is_empty());
|
||||
// Only entry-module events ever get statement anchors.
|
||||
for event in &projection.events {
|
||||
if event.anchor_span.is_some() {
|
||||
assert_eq!(
|
||||
event.module_id.as_deref(),
|
||||
Some(fixture.semantic.projection.module_id.as_str())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_trace_is_explicitly_marked() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/control-flow.truncated.trace.json",
|
||||
"tests/golden/trace-v2/control-flow.truncated.run.json",
|
||||
0,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Truncated);
|
||||
let truncated = projection.truncated.as_ref().expect("truncation");
|
||||
assert_eq!(truncated.reason, "event_budget");
|
||||
assert_eq!(truncated.limit, 5);
|
||||
assert_eq!(truncated.written, 5);
|
||||
assert!(truncated.label().contains("事件数量上限"));
|
||||
assert_ne!(projection.state, RunDisplayState::Succeeded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_keeps_the_core_error_code() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/mixed-modes.json",
|
||||
"examples/mixed-modes/index.mq.md",
|
||||
);
|
||||
let run = verify(
|
||||
&fixture,
|
||||
"tests/golden/trace-v2/mixed-modes.arity.trace.json",
|
||||
"tests/golden/trace-v2/mixed-modes.arity.run.json",
|
||||
1,
|
||||
);
|
||||
let projection = &run.projection;
|
||||
assert_eq!(projection.state, RunDisplayState::Failed);
|
||||
assert_eq!(projection.error_code.as_deref(), Some("call.arity"));
|
||||
assert_eq!(projection.run_status, "call.arity");
|
||||
assert!(projection.result_value.is_none());
|
||||
assert_eq!(projection.state.label(), "运行失败");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_analysis_bytes_are_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut tampered = fixture.analysis.clone();
|
||||
tampered.push(b' ');
|
||||
let trace = golden_bytes("tests/golden/trace-v2/control-flow.trace.json");
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace,
|
||||
analysis_bytes: &tampered,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
assert_eq!(err.exit_code(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_event_module_is_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["events"][0]["module_id"] = Value::String("rogue::module.mq.md".to_string());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_monotonic_sequence_is_rejected() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["events"][1]["seq"] = Value::Number(0.into());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.trace_stale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_schema_major_is_a_protocol_error_not_a_stale_trace() {
|
||||
let fixture = fixture(
|
||||
"tests/golden/analysis-v2/control-flow.json",
|
||||
"examples/control-flow/index.mq.md",
|
||||
);
|
||||
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
trace["schema_version"] = Value::Number(3.into());
|
||||
let trace_bytes = serde_json::to_vec(&trace).unwrap();
|
||||
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
|
||||
let err = verify_trace(TraceVerificationInput {
|
||||
trace_bytes: &trace_bytes,
|
||||
analysis_bytes: &fixture.analysis,
|
||||
semantic: &fixture.semantic.projection,
|
||||
modules: &fixture.semantic.projection.modules,
|
||||
source: &fixture.source,
|
||||
source_index: &fixture.index,
|
||||
run_json: &run_json,
|
||||
exit_code: 0,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.protocol_incompatible");
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golden_digest_is_really_sha256_of_analysis_bytes() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let analysis = std::fs::read(root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
|
||||
let trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
|
||||
assert_eq!(
|
||||
trace["source"]["analysis_digest"].as_str().unwrap(),
|
||||
sha256_prefixed(&analysis)
|
||||
);
|
||||
assert_eq!(
|
||||
trace["source"]["root_id"].as_str().unwrap(),
|
||||
"root:control-flow@0.1.0"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user