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, "use mock_server::{{MockRoute, MockServer}};");
160 }
161
162 let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
169 if file_needs_visitor {
170 let visitor_trait = resolve_visitor_trait(rust_call_override).unwrap_or_else(|| {
171 panic!(
172 "category '{}': fixture declares a visitor block but \
173 `[e2e.call.overrides.rust] visitor_trait` is not configured",
174 category
175 )
176 });
177 let _ = writeln!(
178 out,
179 "use {module}::visitor::{{{visitor_trait}, NodeContext, VisitResult}};"
180 );
181 }
182
183 if file_has_call_based {
188 let rust_options_type = e2e_config
189 .call
190 .overrides
191 .get("rust")
192 .and_then(|o| o.options_type.as_deref());
193 if let Some(opts_type) = rust_options_type {
194 let has_json_object_arg = e2e_config.call.args.iter().any(|a| a.arg_type == "json_object");
197 if has_json_object_arg {
198 let _ = writeln!(out, "use {module}::{opts_type};");
199 }
200 }
201 }
202
203 if file_has_call_based {
207 let mut element_types: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
208 for fixture in fixtures.iter().filter(|f| {
209 if f.mock_response.is_some() {
210 return true;
211 }
212 if f.http.is_none() && f.mock_response.is_none() {
213 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
214 let fn_name = resolve_function_name_for_call(call_config);
215 return !fn_name.is_empty();
216 }
217 false
218 }) {
219 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
220 for arg in &call_config.args {
221 if arg.arg_type == "json_object" {
222 if let Some(ref elem_type) = arg.element_type {
223 element_types.insert(elem_type.clone());
224 }
225 }
226 }
227 }
228 for elem_type in &element_types {
229 if matches!(
232 elem_type.as_str(),
233 "String"
234 | "str"
235 | "bool"
236 | "i8"
237 | "i16"
238 | "i32"
239 | "i64"
240 | "i128"
241 | "isize"
242 | "u8"
243 | "u16"
244 | "u32"
245 | "u64"
246 | "u128"
247 | "usize"
248 | "f32"
249 | "f64"
250 | "char"
251 ) {
252 continue;
253 }
254 let _ = writeln!(out, "use {module}::{elem_type};");
255 }
256 }
257
258 let _ = writeln!(out);
259
260 for fixture in fixtures {
261 render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver, client_factory);
262 let _ = writeln!(out);
263 }
264
265 if !out.ends_with('\n') {
266 out.push('\n');
267 }
268 out
269}
270
271pub fn render_test_function(
272 out: &mut String,
273 fixture: &Fixture,
274 e2e_config: &E2eConfig,
275 dep_name: &str,
276 field_resolver: &FieldResolver,
277 client_factory: Option<&str>,
278) {
279 if fixture.http.is_some() {
281 render_http_test_function(out, fixture, dep_name);
282 return;
283 }
284
285 if fixture.http.is_none() && fixture.mock_response.is_none() {
291 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
292 let resolved_fn_name = resolve_function_name_for_call(call_config);
293 if resolved_fn_name.is_empty() {
294 let fn_name = crate::escape::sanitize_ident(&fixture.id);
295 let description = &fixture.description;
296 let _ = writeln!(out, "#[tokio::test]");
297 let _ = writeln!(out, "async fn test_{fn_name}() {{");
298 let _ = writeln!(out, " // {description}");
299 let _ = writeln!(
300 out,
301 " // TODO: implement when a callable API is available for this fixture type."
302 );
303 let _ = writeln!(out, "}}");
304 return;
305 }
306 }
308
309 let fn_name = crate::escape::sanitize_ident(&fixture.id);
310 let description = &fixture.description;
311 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
312 let function_name = resolve_function_name_for_call(call_config);
313 let module = resolve_module_for_call(call_config, dep_name);
314 let result_var = &call_config.result_var;
315 let has_mock = fixture.mock_response.is_some();
316
317 let rust_overrides = call_config.overrides.get("rust");
319
320 let returns_result = rust_overrides
323 .and_then(|o| o.returns_result)
324 .unwrap_or(if client_factory.is_some() {
325 true
326 } else {
327 call_config.returns_result
328 });
329
330 let is_async = call_config.r#async || has_mock;
332 if is_async {
333 let _ = writeln!(out, "#[tokio::test]");
334 let _ = writeln!(out, "async fn test_{fn_name}() {{");
335 } else {
336 let _ = writeln!(out, "#[test]");
337 let _ = writeln!(out, "fn test_{fn_name}() {{");
338 }
339 let _ = writeln!(out, " // {description}");
340
341 if has_mock {
344 render_mock_server_setup(out, fixture, e2e_config);
345 }
346
347 let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");
349
350 let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
352 let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
353 let options_type: Option<String> = rust_overrides.and_then(|o| o.options_type.clone());
357
358 let visitor_via_options = fixture.visitor.is_some() && rust_overrides.is_none_or(|o| o.visitor_function.is_none());
363
364 let mut arg_exprs: Vec<String> = Vec::new();
366 let mut options_arg_name: Option<String> = None;
368 let mut error_context_handle_name: Option<String> = None;
371 for arg in &call_config.args {
372 let value = crate::codegen::resolve_field(&fixture.input, &arg.field);
373 let var_name = &arg.name;
374 let (mut bindings, expr) = render_rust_arg(
375 var_name,
376 value,
377 &arg.arg_type,
378 arg.optional,
379 &module,
380 &fixture.id,
381 if has_mock {
382 Some("mock_server.url.as_str()")
383 } else {
384 None
385 },
386 arg.owned,
387 arg.element_type.as_deref(),
388 &e2e_config.test_documents_dir,
389 has_error_assertion,
390 );
391 if arg.arg_type == "json_object" {
395 if let Some(ref opts_type) = options_type {
396 bindings = bindings
397 .into_iter()
398 .map(|b| {
399 let prefix = format!("let {var_name} = ");
401 if b.starts_with(&prefix) {
402 format!("let {var_name}: {opts_type} = {}", &b[prefix.len()..])
403 } else {
404 b
405 }
406 })
407 .collect();
408 }
409 }
410 if visitor_via_options && arg.arg_type == "json_object" {
413 options_arg_name = Some(var_name.clone());
414 bindings = bindings
415 .into_iter()
416 .map(|b| {
417 let prefix = format!("let {var_name}");
419 if b.starts_with(&prefix) {
420 format!("let mut {}", &b[4..])
421 } else {
422 b
423 }
424 })
425 .collect();
426 }
427 if has_error_assertion && arg.arg_type == "handle" {
431 error_context_handle_name = Some(var_name.clone());
432 }
433 for binding in &bindings {
434 let _ = writeln!(out, " {binding}");
435 }
436 let final_expr = if has_error_assertion && arg.arg_type == "handle" {
440 format!("&{var_name}")
444 } else if wrap_options_in_some && arg.arg_type == "json_object" {
445 if visitor_via_options {
446 let name = if let Some(rest) = expr.strip_prefix('&') {
449 rest.to_string()
450 } else {
451 expr.clone()
452 };
453 format!("Some({name})")
454 } else if let Some(rest) = expr.strip_prefix('&') {
455 format!("Some({rest}.clone())")
456 } else {
457 format!("Some({expr})")
458 }
459 } else {
460 expr
461 };
462 arg_exprs.push(final_expr);
463 }
464
465 if let Some(visitor_spec) = &fixture.visitor {
467 let visitor_trait = resolve_visitor_trait(rust_overrides)
470 .expect("visitor_trait must be set in [e2e.call.overrides.rust] when a fixture declares a visitor block");
471 let _ = writeln!(out, " #[derive(Debug)]");
473 let _ = writeln!(out, " struct _TestVisitor;");
474 let _ = writeln!(out, " impl {visitor_trait} for _TestVisitor {{");
475 for (method_name, action) in &visitor_spec.callbacks {
476 emit_rust_visitor_method(out, method_name, action);
477 }
478 let _ = writeln!(out, " }}");
479 let _ = writeln!(
480 out,
481 " let visitor = std::sync::Arc::new(std::sync::Mutex::new(_TestVisitor));"
482 );
483 if visitor_via_options {
484 let opts_name = options_arg_name.as_deref().unwrap_or("options");
486 let _ = writeln!(out, " {opts_name}.visitor = Some(visitor);");
487 } else {
488 arg_exprs.push("Some(visitor)".to_string());
490 }
491 } else {
492 arg_exprs.extend(extra_args);
495 }
496
497 let args_str = arg_exprs.join(", ");
498
499 let await_suffix = if is_async { ".await" } else { "" };
500
501 let call_expr = if let Some(factory) = client_factory {
505 let base_url_arg = if has_mock {
506 "Some(mock_server.url.clone())"
507 } else {
508 "None"
509 };
510 let _ = writeln!(
511 out,
512 " let client = {module}::{factory}(\"test-key\".to_string(), {base_url_arg}, None, None, None).unwrap();"
513 );
514 format!("client.{function_name}({args_str})")
515 } else {
516 format!("{function_name}({args_str})")
517 };
518
519 let result_is_tree = call_config.result_var == "tree";
520 let result_is_simple = call_config.result_is_simple || rust_overrides.is_some_and(|o| o.result_is_simple);
524 let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
527 let result_is_option = call_config.result_is_option || rust_overrides.is_some_and(|o| o.result_is_option);
530
531 if has_error_assertion {
532 if let Some(ref handle_name) = error_context_handle_name {
536 let _ = writeln!(out, " let {result_var} = match {handle_name}_result {{");
537 let _ = writeln!(out, " Err(e) => Err(e),");
538 let _ = writeln!(out, " Ok({handle_name}) => {{");
539 let _ = writeln!(out, " {call_expr}{await_suffix}");
540 let _ = writeln!(out, " }}");
541 let _ = writeln!(out, " }};");
542 } else {
543 let _ = writeln!(out, " let {result_var} = {call_expr}{await_suffix};");
544 }
545 let has_non_error_assertions = fixture.assertions.iter().any(|a| {
548 !matches!(a.assertion_type.as_str(), "error" | "not_error")
549 && !a.field.as_ref().is_some_and(|f| f.starts_with("error."))
550 });
551 if returns_result && has_non_error_assertions {
554 let _ = writeln!(out, " let {result_var}_ok = {result_var}.as_ref().ok();");
556 }
557 for assertion in &fixture.assertions {
559 render_assertion(
560 out,
561 assertion,
562 result_var,
563 &module,
564 dep_name,
565 true,
566 &[],
567 field_resolver,
568 result_is_tree,
569 result_is_simple,
570 false,
571 false,
572 returns_result,
573 );
574 }
575 let _ = writeln!(out, "}}");
576 return;
577 }
578
579 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
581
582 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
587 let stream_var = "stream";
589 let chunks_var = "chunks";
591
592 let has_usable_assertion = fixture.assertions.iter().any(|a| {
598 if a.assertion_type == "not_error" || a.assertion_type == "error" {
599 return false;
600 }
601 if a.assertion_type == "method_result" {
602 let supported_checks = [
605 "equals",
606 "is_true",
607 "is_false",
608 "greater_than_or_equal",
609 "count_min",
610 "is_error",
611 "contains",
612 "not_empty",
613 "is_empty",
614 ];
615 let check = a.check.as_deref().unwrap_or("is_true");
616 if a.method.is_none() || !supported_checks.contains(&check) {
617 return false;
618 }
619 }
620 match &a.field {
621 Some(f) if !f.is_empty() => {
622 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
623 return true;
624 }
625 field_resolver.is_valid_for_result(f)
626 }
627 _ => true,
628 }
629 });
630
631 let result_binding = if is_streaming {
634 stream_var.to_string()
635 } else if has_usable_assertion {
636 result_var.to_string()
637 } else {
638 "_".to_string()
639 };
640
641 let has_field_access = fixture
645 .assertions
646 .iter()
647 .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
648 let only_emptiness_checks = !has_field_access
649 && fixture.assertions.iter().all(|a| {
650 matches!(
651 a.assertion_type.as_str(),
652 "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
653 )
654 });
655
656 let unwrap_suffix = if returns_result {
657 ".expect(\"should succeed\")"
658 } else {
659 ""
660 };
661 if is_streaming {
662 let _ = writeln!(out, " let {stream_var} = {call_expr}{await_suffix}{unwrap_suffix};");
664 if let Some(collect) = crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(
665 "rust", stream_var, chunks_var,
666 ) {
667 let _ = writeln!(out, " {collect}");
668 }
669 } else if !returns_result || (only_emptiness_checks && !has_not_error) {
670 let _ = writeln!(out, " let {result_binding} = {call_expr}{await_suffix};");
673 } else if has_not_error || !fixture.assertions.is_empty() {
674 let _ = writeln!(
675 out,
676 " let {result_binding} = {call_expr}{await_suffix}{unwrap_suffix};"
677 );
678 } else {
679 let _ = writeln!(out, " let {result_binding} = {call_expr}{await_suffix};");
680 }
681
682 let string_assertion_types = [
688 "equals",
689 "contains",
690 "contains_all",
691 "contains_any",
692 "not_contains",
693 "starts_with",
694 "ends_with",
695 "min_length",
696 "max_length",
697 "matches_regex",
698 ];
699 let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); if !result_is_vec {
701 for assertion in &fixture.assertions {
702 if let Some(f) = &assertion.field {
703 if !f.is_empty()
704 && string_assertion_types.contains(&assertion.assertion_type.as_str())
705 && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
706 {
707 let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
710 if !is_string_assertion {
711 continue;
712 }
713 if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
714 let _ = writeln!(out, " {binding}");
715 unwrapped_fields.push((f.clone(), local_var));
716 }
717 }
718 }
719 }
720 }
721
722 for assertion in &fixture.assertions {
724 if assertion.assertion_type == "not_error" {
725 continue;
727 }
728 render_assertion(
729 out,
730 assertion,
731 result_var,
732 &module,
733 dep_name,
734 false,
735 &unwrapped_fields,
736 field_resolver,
737 result_is_tree,
738 result_is_simple,
739 result_is_vec,
740 result_is_option,
741 returns_result,
742 );
743 }
744
745 let _ = writeln!(out, "}}");
746}
747
748pub fn collect_test_filenames(groups: &[FixtureGroup]) -> Vec<String> {
750 groups
751 .iter()
752 .filter(|g| !g.fixtures.is_empty())
753 .map(|g| format!("{}_test.rs", sanitize_filename(&g.category)))
754 .collect()
755}
756
757#[cfg(test)]
758mod tests {
759 use super::*;
760
761 #[test]
762 fn resolve_module_for_call_prefers_crate_name_override() {
763 use crate::config::CallConfig;
764 use std::collections::HashMap;
765 let mut overrides = HashMap::new();
766 overrides.insert(
767 "rust".to_string(),
768 crate::config::CallOverride {
769 crate_name: Some("custom_crate".to_string()),
770 module: Some("ignored_module".to_string()),
771 ..Default::default()
772 },
773 );
774 let call = CallConfig {
775 overrides,
776 ..Default::default()
777 };
778 let result = resolve_module_for_call(&call, "dep_name");
779 assert_eq!(result, "custom_crate");
780 }
781}