1use std::fmt::Write as FmtWrite;
4
5use crate::config::E2eConfig;
6use crate::escape::sanitize_filename;
7use crate::field_access::FieldResolver;
8use crate::fixture::{Fixture, FixtureGroup};
9
10use super::args::{emit_rust_visitor_method, render_rust_arg, resolve_visitor_trait};
11use super::assertions::render_assertion;
12use super::http::render_http_test_function;
13use super::mock_server::render_mock_server_setup;
14
15pub(super) fn resolve_function_name_for_call(call_config: &crate::config::CallConfig) -> String {
16 call_config
17 .overrides
18 .get("rust")
19 .and_then(|o| o.function.clone())
20 .unwrap_or_else(|| call_config.function.clone())
21}
22
23pub(super) fn resolve_module(e2e_config: &E2eConfig, dep_name: &str) -> String {
24 resolve_module_for_call(&e2e_config.call, dep_name)
25}
26
27pub(super) fn resolve_module_for_call(call_config: &crate::config::CallConfig, dep_name: &str) -> String {
28 let overrides = call_config.overrides.get("rust");
31 overrides
32 .and_then(|o| o.crate_name.clone())
33 .or_else(|| overrides.and_then(|o| o.module.clone()))
34 .unwrap_or_else(|| dep_name.to_string())
35}
36
37pub(super) fn is_skipped(fixture: &Fixture, language: &str) -> bool {
38 fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
39}
40
41pub fn render_test_file(
42 category: &str,
43 fixtures: &[&Fixture],
44 e2e_config: &E2eConfig,
45 dep_name: &str,
46 needs_mock_server: bool,
47) -> String {
48 let mut out = String::new();
49 out.push_str(&alef_core::hash::header(alef_core::hash::CommentStyle::DoubleSlash));
50 let _ = writeln!(out, "//! E2e tests for category: {category}");
51 let _ = writeln!(out);
52
53 let module = resolve_module(e2e_config, dep_name);
54 let field_resolver = FieldResolver::new(
55 &e2e_config.fields,
56 &e2e_config.fields_optional,
57 &e2e_config.result_fields,
58 &e2e_config.fields_array,
59 &e2e_config.fields_method_calls,
60 );
61
62 let file_has_http = fixtures.iter().any(|f| f.http.is_some());
64 let file_has_call_based = fixtures.iter().any(|f| {
67 if f.mock_response.is_some() {
68 return true;
69 }
70 if f.http.is_none() && f.mock_response.is_none() {
71 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
72 let fn_name = resolve_function_name_for_call(call_config);
73 return !fn_name.is_empty();
74 }
75 false
76 });
77
78 let rust_call_override = e2e_config.call.overrides.get("rust");
83 let client_factory = rust_call_override.and_then(|o| o.client_factory.as_deref());
84
85 if file_has_call_based && client_factory.is_none() {
87 let mut imported: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
88 for fixture in fixtures.iter().filter(|f| {
89 if f.mock_response.is_some() {
90 return true;
91 }
92 if f.http.is_none() && f.mock_response.is_none() {
93 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
94 let fn_name = resolve_function_name_for_call(call_config);
95 return !fn_name.is_empty();
96 }
97 false
98 }) {
99 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
100 let fn_name = resolve_function_name_for_call(call_config);
101 let mod_name = resolve_module_for_call(call_config, dep_name);
102 imported.insert((mod_name, fn_name));
103 }
104 let mut by_module: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
106 for (mod_name, fn_name) in &imported {
107 by_module.entry(mod_name.clone()).or_default().push(fn_name.clone());
108 }
109 for (mod_name, fns) in &by_module {
110 if fns.len() == 1 {
111 let _ = writeln!(out, "use {mod_name}::{};", fns[0]);
112 } else {
113 let joined = fns.join(", ");
114 let _ = writeln!(out, "use {mod_name}::{{{joined}}};");
115 }
116 }
117 }
118
119 if file_has_http {
121 let _ = writeln!(out, "use {module}::{{App, RequestContext}};");
122 }
123
124 let has_handle_args = e2e_config.call.args.iter().any(|a| a.arg_type == "handle");
126 if has_handle_args {
127 let _ = writeln!(out, "use {module}::CrawlConfig;");
128 }
129 for arg in &e2e_config.call.args {
130 if arg.arg_type == "handle" {
131 use heck::ToSnakeCase;
132 let constructor_name = format!("create_{}", arg.name.to_snake_case());
133 let _ = writeln!(out, "use {module}::{constructor_name};");
134 }
135 }
136
137 if client_factory.is_some() && file_has_call_based {
140 let trait_imports: Vec<String> = e2e_config
141 .call
142 .overrides
143 .get("rust")
144 .map(|o| o.trait_imports.clone())
145 .unwrap_or_default();
146 for trait_name in &trait_imports {
147 let _ = writeln!(out, "use {module}::{trait_name};");
148 }
149 }
150
151 let file_needs_mock = needs_mock_server
153 && fixtures
154 .iter()
155 .any(|f| f.mock_response.is_some() || f.needs_mock_server());
156 if file_needs_mock {
157 let _ = writeln!(out, "mod common;");
158 let _ = writeln!(out, "mod mock_server;");
159 let _ = writeln!(out, "#[allow(unused_imports)]");
160 let _ = writeln!(out, "use mock_server::{{MockRoute, MockServer}};");
161 }
162
163 let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
170 if file_needs_visitor {
171 let visitor_trait = resolve_visitor_trait(rust_call_override).unwrap_or_else(|| {
172 panic!(
173 "category '{}': fixture declares a visitor block but \
174 `[e2e.call.overrides.rust] visitor_trait` is not configured",
175 category
176 )
177 });
178 let _ = writeln!(
179 out,
180 "use {module}::visitor::{{{visitor_trait}, NodeContext, VisitResult}};"
181 );
182 }
183
184 if file_has_call_based {
189 let rust_options_type = e2e_config
190 .call
191 .overrides
192 .get("rust")
193 .and_then(|o| o.options_type.as_deref());
194 if let Some(opts_type) = rust_options_type {
195 let has_json_object_arg = e2e_config.call.args.iter().any(|a| a.arg_type == "json_object");
198 if has_json_object_arg {
199 let _ = writeln!(out, "use {module}::{opts_type};");
200 }
201 }
202 }
203
204 if file_has_call_based {
208 let mut element_types: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
209 for fixture in fixtures.iter().filter(|f| {
210 if f.mock_response.is_some() {
211 return true;
212 }
213 if f.http.is_none() && f.mock_response.is_none() {
214 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
215 let fn_name = resolve_function_name_for_call(call_config);
216 return !fn_name.is_empty();
217 }
218 false
219 }) {
220 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
221 for arg in &call_config.args {
222 if arg.arg_type == "json_object" {
223 if let Some(ref elem_type) = arg.element_type {
224 element_types.insert(elem_type.clone());
225 }
226 }
227 }
228 }
229 for elem_type in &element_types {
230 if matches!(
233 elem_type.as_str(),
234 "String"
235 | "str"
236 | "bool"
237 | "i8"
238 | "i16"
239 | "i32"
240 | "i64"
241 | "i128"
242 | "isize"
243 | "u8"
244 | "u16"
245 | "u32"
246 | "u64"
247 | "u128"
248 | "usize"
249 | "f32"
250 | "f64"
251 | "char"
252 ) {
253 continue;
254 }
255 let _ = writeln!(out, "use {module}::{elem_type};");
256 }
257 }
258
259 let _ = writeln!(out);
260
261 for fixture in fixtures {
262 render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver, client_factory);
263 let _ = writeln!(out);
264 }
265
266 if !out.ends_with('\n') {
267 out.push('\n');
268 }
269 out
270}
271
272pub fn render_test_function(
273 out: &mut String,
274 fixture: &Fixture,
275 e2e_config: &E2eConfig,
276 dep_name: &str,
277 field_resolver: &FieldResolver,
278 client_factory: Option<&str>,
279) {
280 if fixture.http.is_some() {
282 render_http_test_function(out, fixture, dep_name);
283 return;
284 }
285
286 if fixture.http.is_none() && fixture.mock_response.is_none() {
292 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
293 let resolved_fn_name = resolve_function_name_for_call(call_config);
294 if resolved_fn_name.is_empty() {
295 let fn_name = crate::escape::sanitize_ident(&fixture.id);
296 let description = &fixture.description;
297 let _ = writeln!(out, "#[tokio::test]");
298 let _ = writeln!(out, "async fn test_{fn_name}() {{");
299 let _ = writeln!(out, " // {description}");
300 let _ = writeln!(
301 out,
302 " // TODO: implement when a callable API is available for this fixture type."
303 );
304 let _ = writeln!(out, "}}");
305 return;
306 }
307 }
309
310 let fn_name = crate::escape::sanitize_ident(&fixture.id);
311 let description = &fixture.description;
312 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
313 let function_name = resolve_function_name_for_call(call_config);
314 let module = resolve_module_for_call(call_config, dep_name);
315 let result_var = &call_config.result_var;
316 let has_mock = fixture.mock_response.is_some();
317
318 let rust_overrides = call_config.overrides.get("rust");
320
321 let returns_result = rust_overrides
324 .and_then(|o| o.returns_result)
325 .unwrap_or(if client_factory.is_some() {
326 true
327 } else {
328 call_config.returns_result
329 });
330
331 let is_async = call_config.r#async || has_mock;
333 if is_async {
334 let _ = writeln!(out, "#[tokio::test]");
335 let _ = writeln!(out, "async fn test_{fn_name}() {{");
336 } else {
337 let _ = writeln!(out, "#[test]");
338 let _ = writeln!(out, "fn test_{fn_name}() {{");
339 }
340 let _ = writeln!(out, " // {description}");
341
342 if has_mock {
345 render_mock_server_setup(out, fixture, e2e_config);
346 }
347
348 let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");
350
351 let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
353 let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
354 let options_type: Option<String> = rust_overrides.and_then(|o| o.options_type.clone());
358
359 let visitor_via_options = fixture.visitor.is_some() && rust_overrides.is_none_or(|o| o.visitor_function.is_none());
364
365 let mut arg_exprs: Vec<String> = Vec::new();
367 let mut options_arg_name: Option<String> = None;
369 let mut error_context_handle_name: Option<String> = None;
372 for arg in &call_config.args {
373 let value = crate::codegen::resolve_field(&fixture.input, &arg.field);
374 let var_name = &arg.name;
375 let (mut bindings, expr) = render_rust_arg(
376 var_name,
377 value,
378 &arg.arg_type,
379 arg.optional,
380 &module,
381 &fixture.id,
382 if has_mock {
383 Some("mock_server.url.as_str()")
384 } else {
385 None
386 },
387 arg.owned,
388 arg.element_type.as_deref(),
389 &e2e_config.test_documents_dir,
390 has_error_assertion,
391 );
392 if arg.arg_type == "json_object" {
396 if let Some(ref opts_type) = options_type {
397 bindings = bindings
398 .into_iter()
399 .map(|b| {
400 let prefix = format!("let {var_name} = ");
402 if b.starts_with(&prefix) {
403 format!("let {var_name}: {opts_type} = {}", &b[prefix.len()..])
404 } else {
405 b
406 }
407 })
408 .collect();
409 }
410 }
411 if visitor_via_options && arg.arg_type == "json_object" {
414 options_arg_name = Some(var_name.clone());
415 bindings = bindings
416 .into_iter()
417 .map(|b| {
418 let prefix = format!("let {var_name}");
420 if b.starts_with(&prefix) {
421 format!("let mut {}", &b[4..])
422 } else {
423 b
424 }
425 })
426 .collect();
427 }
428 if has_error_assertion && arg.arg_type == "handle" {
432 error_context_handle_name = Some(var_name.clone());
433 }
434 for binding in &bindings {
435 let _ = writeln!(out, " {binding}");
436 }
437 let final_expr = if has_error_assertion && arg.arg_type == "handle" {
441 format!("&{var_name}")
445 } else if wrap_options_in_some && arg.arg_type == "json_object" {
446 if visitor_via_options {
447 let name = if let Some(rest) = expr.strip_prefix('&') {
450 rest.to_string()
451 } else {
452 expr.clone()
453 };
454 format!("Some({name})")
455 } else if let Some(rest) = expr.strip_prefix('&') {
456 format!("Some({rest}.clone())")
457 } else {
458 format!("Some({expr})")
459 }
460 } else {
461 expr
462 };
463 arg_exprs.push(final_expr);
464 }
465
466 if let Some(visitor_spec) = &fixture.visitor {
468 let visitor_trait = resolve_visitor_trait(rust_overrides)
471 .expect("visitor_trait must be set in [e2e.call.overrides.rust] when a fixture declares a visitor block");
472 let _ = writeln!(out, " #[derive(Debug)]");
474 let _ = writeln!(out, " struct _TestVisitor;");
475 let _ = writeln!(out, " impl {visitor_trait} for _TestVisitor {{");
476 for (method_name, action) in &visitor_spec.callbacks {
477 emit_rust_visitor_method(out, method_name, action);
478 }
479 let _ = writeln!(out, " }}");
480 let _ = writeln!(
481 out,
482 " let visitor = std::sync::Arc::new(std::sync::Mutex::new(_TestVisitor));"
483 );
484 if visitor_via_options {
485 let opts_name = options_arg_name.as_deref().unwrap_or("options");
487 let _ = writeln!(out, " {opts_name}.visitor = Some(visitor);");
488 } else {
489 arg_exprs.push("Some(visitor)".to_string());
491 }
492 } else {
493 arg_exprs.extend(extra_args);
496 }
497
498 let args_str = arg_exprs.join(", ");
499
500 let await_suffix = if is_async { ".await" } else { "" };
501
502 let call_expr = if let Some(factory) = client_factory {
506 let base_url_arg = if has_mock {
507 "Some(mock_server.url.clone())"
508 } else {
509 "None"
510 };
511 let _ = writeln!(
512 out,
513 " let client = {module}::{factory}(\"test-key\".to_string(), {base_url_arg}, None, None, None).unwrap();"
514 );
515 format!("client.{function_name}({args_str})")
516 } else {
517 format!("{function_name}({args_str})")
518 };
519
520 let result_is_tree = call_config.result_var == "tree";
521 let result_is_simple = call_config.result_is_simple || rust_overrides.is_some_and(|o| o.result_is_simple);
525 let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
528 let result_is_option = call_config.result_is_option || rust_overrides.is_some_and(|o| o.result_is_option);
531
532 if has_error_assertion {
533 if let Some(ref handle_name) = error_context_handle_name {
537 let _ = writeln!(out, " let {result_var} = match {handle_name}_result {{");
538 let _ = writeln!(out, " Err(e) => Err(e),");
539 let _ = writeln!(out, " Ok({handle_name}) => {{");
540 let _ = writeln!(out, " {call_expr}{await_suffix}");
541 let _ = writeln!(out, " }}");
542 let _ = writeln!(out, " }};");
543 } else {
544 let _ = writeln!(out, " let {result_var} = {call_expr}{await_suffix};");
545 }
546 let has_non_error_assertions = fixture.assertions.iter().any(|a| {
549 !matches!(a.assertion_type.as_str(), "error" | "not_error")
550 && !a.field.as_ref().is_some_and(|f| f.starts_with("error."))
551 });
552 if returns_result && has_non_error_assertions {
555 let _ = writeln!(out, " let {result_var}_ok = {result_var}.as_ref().ok();");
557 }
558 for assertion in &fixture.assertions {
560 render_assertion(
561 out,
562 assertion,
563 result_var,
564 &module,
565 dep_name,
566 true,
567 &[],
568 field_resolver,
569 result_is_tree,
570 result_is_simple,
571 false,
572 false,
573 returns_result,
574 );
575 }
576 let _ = writeln!(out, "}}");
577 return;
578 }
579
580 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
582
583 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
588 let stream_var = "stream";
590 let chunks_var = "chunks";
592
593 let has_usable_assertion = fixture.assertions.iter().any(|a| {
599 if a.assertion_type == "not_error" || a.assertion_type == "error" {
600 return false;
601 }
602 if a.assertion_type == "method_result" {
603 let supported_checks = [
606 "equals",
607 "is_true",
608 "is_false",
609 "greater_than_or_equal",
610 "count_min",
611 "is_error",
612 "contains",
613 "not_empty",
614 "is_empty",
615 ];
616 let check = a.check.as_deref().unwrap_or("is_true");
617 if a.method.is_none() || !supported_checks.contains(&check) {
618 return false;
619 }
620 }
621 match &a.field {
622 Some(f) if !f.is_empty() => {
623 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
624 return true;
625 }
626 field_resolver.is_valid_for_result(f)
627 }
628 _ => true,
629 }
630 });
631
632 let result_binding = if is_streaming {
635 stream_var.to_string()
636 } else if has_usable_assertion {
637 result_var.to_string()
638 } else {
639 "_".to_string()
640 };
641
642 let has_field_access = fixture
646 .assertions
647 .iter()
648 .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
649 let only_emptiness_checks = !has_field_access
650 && fixture.assertions.iter().all(|a| {
651 matches!(
652 a.assertion_type.as_str(),
653 "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
654 )
655 });
656
657 let unwrap_suffix = if returns_result {
658 ".expect(\"should succeed\")"
659 } else {
660 ""
661 };
662 if is_streaming {
663 let _ = writeln!(out, " let {stream_var} = {call_expr}{await_suffix}{unwrap_suffix};");
665 if let Some(collect) = crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(
666 "rust", stream_var, chunks_var,
667 ) {
668 let _ = writeln!(out, " {collect}");
669 }
670 } else if !returns_result || (only_emptiness_checks && !has_not_error) {
671 let _ = writeln!(out, " let {result_binding} = {call_expr}{await_suffix};");
674 } else if has_not_error || !fixture.assertions.is_empty() {
675 let _ = writeln!(
676 out,
677 " let {result_binding} = {call_expr}{await_suffix}{unwrap_suffix};"
678 );
679 } else {
680 let _ = writeln!(out, " let {result_binding} = {call_expr}{await_suffix};");
681 }
682
683 let string_assertion_types = [
689 "equals",
690 "contains",
691 "contains_all",
692 "contains_any",
693 "not_contains",
694 "starts_with",
695 "ends_with",
696 "min_length",
697 "max_length",
698 "matches_regex",
699 ];
700 let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); if !result_is_vec {
702 for assertion in &fixture.assertions {
703 if let Some(f) = &assertion.field {
704 if !f.is_empty()
705 && string_assertion_types.contains(&assertion.assertion_type.as_str())
706 && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
707 {
708 let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
711 if !is_string_assertion {
712 continue;
713 }
714 if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
715 let _ = writeln!(out, " {binding}");
716 unwrapped_fields.push((f.clone(), local_var));
717 }
718 }
719 }
720 }
721 }
722
723 for assertion in &fixture.assertions {
725 if assertion.assertion_type == "not_error" {
726 continue;
728 }
729 render_assertion(
730 out,
731 assertion,
732 result_var,
733 &module,
734 dep_name,
735 false,
736 &unwrapped_fields,
737 field_resolver,
738 result_is_tree,
739 result_is_simple,
740 result_is_vec,
741 result_is_option,
742 returns_result,
743 );
744 }
745
746 let _ = writeln!(out, "}}");
747}
748
749pub fn collect_test_filenames(groups: &[FixtureGroup]) -> Vec<String> {
751 groups
752 .iter()
753 .filter(|g| !g.fixtures.is_empty())
754 .map(|g| format!("{}_test.rs", sanitize_filename(&g.category)))
755 .collect()
756}
757
758#[cfg(test)]
759mod tests {
760 use super::*;
761
762 #[test]
763 fn resolve_module_for_call_prefers_crate_name_override() {
764 use crate::config::CallConfig;
765 use std::collections::HashMap;
766 let mut overrides = HashMap::new();
767 overrides.insert(
768 "rust".to_string(),
769 crate::config::CallOverride {
770 crate_name: Some("custom_crate".to_string()),
771 module: Some("ignored_module".to_string()),
772 ..Default::default()
773 },
774 );
775 let call = CallConfig {
776 overrides,
777 ..Default::default()
778 };
779 let result = resolve_module_for_call(&call, "dep_name");
780 assert_eq!(result, "custom_crate");
781 }
782}