1use code_system_graph_model::{
2 Evidence, EvidenceId, Node, NodeId, NodeKind, Provenance, RepoId, stable_id
3};
4
5use crate::{CallScope, ContractImplementationConfig, IntegrationTestConfig, normalize_http_path};
6
7#[derive(Debug, Clone, PartialEq)]
9pub struct DeclaredTestCase {
10 pub node: Node,
12 pub method: String,
14 pub path: String,
16 pub scope: CallScope,
18 pub evidence: Evidence,
20}
21
22#[derive(Debug, Clone, PartialEq)]
24pub struct DeclaredImplementation {
25 pub node: Node,
27 pub method: String,
29 pub path: String,
31 pub evidence: Evidence,
33}
34
35#[must_use]
37pub fn declared_test_case(
38 repo_id: RepoId,
39 config: &IntegrationTestConfig,
40 content_hash: Option<String>,
41) -> DeclaredTestCase {
42 let method = config.validates.method.trim().to_ascii_uppercase();
43 let path = normalize_http_path(&config.validates.path);
44 let stable_key = format!(
45 "test:{}:{}:{}:{}:{}",
46 repo_id.as_str(),
47 config.language.trim().to_ascii_lowercase(),
48 config.framework.trim().to_ascii_lowercase(),
49 config.path,
50 config.name
51 );
52 let evidence_key = format!("{stable_key}:{method}:{path}");
53 DeclaredTestCase {
54 node: Node {
55 id: NodeId::new(stable_id("node", &stable_key)),
56 kind: NodeKind::TestCase,
57 repo_id: Some(repo_id.clone()),
58 stable_key,
59 label: format!("{}/{}::{}", config.language, config.framework, config.name),
60 },
61 method,
62 path,
63 scope: CallScope::Workspace,
64 evidence: Evidence {
65 id: EvidenceId::new(stable_id("evidence", &evidence_key)),
66 repo_id: Some(repo_id),
67 file_path: Some(config.path.clone()),
68 start_line: None,
69 end_line: None,
70 extractor: "code-system-graph.tests.declared".to_owned(),
71 extractor_version: env!("CARGO_PKG_VERSION").to_owned(),
72 provenance: Provenance::Declared,
73 confidence: 1.0,
74 observed_at_commit: None,
75 content_hash,
76 note: Some(format!(
77 "{} test declared with {}",
78 config.language, config.framework
79 )),
80 },
81 }
82}
83
84#[must_use]
86pub fn declared_implementation(
87 repo_id: RepoId,
88 config: &ContractImplementationConfig,
89 content_hash: Option<String>,
90) -> DeclaredImplementation {
91 let method = config.implements.method.trim().to_ascii_uppercase();
92 let path = normalize_http_path(&config.implements.path);
93 let identity = crate::SourceSymbolIdentity::new(
94 repo_id.clone(),
95 &config.language,
96 &config.path,
97 &config.symbol,
98 );
99 let stable_key = identity.stable_key();
100 let evidence_key = format!("{stable_key}:{method}:{path}");
101 DeclaredImplementation {
102 node: identity.node(format!("{}::{}", config.language, config.symbol)),
103 method,
104 path,
105 evidence: Evidence {
106 id: EvidenceId::new(stable_id("evidence", &evidence_key)),
107 repo_id: Some(repo_id),
108 file_path: Some(config.path.clone()),
109 start_line: None,
110 end_line: None,
111 extractor: "code-system-graph.implementations.declared".to_owned(),
112 extractor_version: env!("CARGO_PKG_VERSION").to_owned(),
113 provenance: Provenance::Declared,
114 confidence: 1.0,
115 observed_at_commit: None,
116 content_hash,
117 note: Some(format!(
118 "{} symbol declared as contract implementation",
119 config.language
120 )),
121 },
122 }
123}
124
125#[cfg(test)]
126mod tests {
127
128 use code_system_graph_model::{EdgeKind, EpistemicStatus, RepoId};
129
130 use super::declared_test_case;
131 use crate::{
132 AuthorityMap, HttpContractConfig, IntegrationTestConfig, extract_openapi, link_http_routes, parse_rust_source, source_observations_to_graph
133 };
134
135 #[test]
136 fn declared_python_test_should_validate_rust_provider_with_bilateral_evidence() {
137 let test = declared_test_case(
138 RepoId::new("repo:tests"),
139 &IntegrationTestConfig {
140 name: "test_create_order".to_owned(),
141 path: "tests/test_orders.py".to_owned(),
142 framework: "pytest".to_owned(),
143 language: "python".to_owned(),
144 validates: HttpContractConfig {
145 method: "POST".to_owned(),
146 path: "/api/orders".to_owned(),
147 },
148 },
149 Some("content:test".to_owned()),
150 );
151 let providers = extract_openapi(
152 &RepoId::new("repo:rust-api"),
153 "openapi.yaml",
154 "openapi: 3.1.0\npaths:\n /api/orders:\n post: {}\n",
155 );
156 let result = providers
157 .map_err(|error| error.to_string())
158 .map(|providers| {
159 link_http_routes(&providers, &[test], &[], &AuthorityMap::new()).edges
160 });
161
162 assert!(matches!(
163 result,
164 Ok(edges)
165 if edges.len() == 1
166 && edges[0].kind == EdgeKind::Validates
167 && edges[0].evidence.len() == 2
168 ));
169 }
170
171 #[test]
172 fn executable_route_should_outweigh_divergent_utoipa_advisory() {
173 let repo = RepoId::new("repo:rust-api");
174 let observations = parse_rust_source(
175 r#"
176use actix_web::get;
177
178#[utoipa::path(get, path = "/documented")]
179#[get("/runtime")]
180async fn handler() {}
181"#,
182 );
183 let facts =
184 source_observations_to_graph(&repo, "src/routes.rs", "content:routes", &observations);
185 let edges = link_http_routes(
186 &facts.boundaries,
187 &[],
188 &facts.implementations,
189 &AuthorityMap::new(),
190 )
191 .edges
192 .into_iter()
193 .filter(|edge| edge.kind == EdgeKind::ImplementedBy)
194 .collect::<Vec<_>>();
195 let mut consensus = edges
196 .iter()
197 .filter_map(|edge| {
198 let path = facts
199 .boundaries
200 .iter()
201 .find(|boundary| boundary.node.id == edge.source)?
202 .path
203 .clone();
204 Some((path, edge.confidence, edge.status))
205 })
206 .collect::<Vec<_>>();
207 consensus.sort_by(|left, right| left.0.cmp(&right.0));
208
209 assert_eq!(
210 consensus,
211 vec![
212 ("/documented".to_owned(), 0.75, EpistemicStatus::Inferred),
213 ("/runtime".to_owned(), 1.0, EpistemicStatus::Confirmed),
214 ]
215 );
216 }
217
218 #[test]
219 fn executable_route_should_merge_matching_utoipa_advisory() {
220 let repo = RepoId::new("repo:rust-api");
221 let observations = parse_rust_source(
222 r#"
223use actix_web::get;
224
225#[utoipa::path(get, path = "/payments")]
226#[get("/payments")]
227async fn handler() {}
228"#,
229 );
230 let facts =
231 source_observations_to_graph(&repo, "src/routes.rs", "content:routes", &observations);
232 let edges = link_http_routes(
233 &facts.boundaries,
234 &[],
235 &facts.implementations,
236 &AuthorityMap::new(),
237 )
238 .edges
239 .into_iter()
240 .filter(|edge| edge.kind == EdgeKind::ImplementedBy)
241 .collect::<Vec<_>>();
242
243 assert!(matches!(
244 edges.as_slice(),
245 [edge]
246 if edge.kind == EdgeKind::ImplementedBy
247 && (edge.confidence - 1.0).abs() < f32::EPSILON
248 && edge.status == EpistemicStatus::Confirmed
249 && edge.evidence.len() == 3
250 ));
251 }
252}