1use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{
11 Assertion, CallbackAction, Fixture, FixtureGroup, TemplateReturnForm, ValidationErrorExpectation,
12};
13use alef_core::backend::GeneratedFile;
14use alef_core::config::ResolvedCrateConfig;
15use alef_core::hash::{self, CommentStyle};
16use alef_core::template_versions as tv;
17use anyhow::Result;
18use heck::ToSnakeCase;
19use std::collections::HashMap;
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24use super::client;
25
26pub struct RubyCodegen;
28
29impl E2eCodegen for RubyCodegen {
30 fn generate(
31 &self,
32 groups: &[FixtureGroup],
33 e2e_config: &E2eConfig,
34 config: &ResolvedCrateConfig,
35 _type_defs: &[alef_core::ir::TypeDef],
36 ) -> Result<Vec<GeneratedFile>> {
37 let lang = self.language_name();
38 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
39
40 let mut files = Vec::new();
41
42 let call = &e2e_config.call;
44 let overrides = call.overrides.get(lang);
45 let module_path = overrides
46 .and_then(|o| o.module.as_ref())
47 .cloned()
48 .unwrap_or_else(|| call.module.clone());
49 let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
50 let options_type = overrides.and_then(|o| o.options_type.clone());
51 let empty_enum_fields = HashMap::new();
52 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
53 let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
54
55 let ruby_pkg = e2e_config.resolve_package("ruby");
57 let gem_name = ruby_pkg
58 .as_ref()
59 .and_then(|p| p.name.as_ref())
60 .cloned()
61 .unwrap_or_else(|| config.name.replace('-', "_"));
62 let gem_path = ruby_pkg
63 .as_ref()
64 .and_then(|p| p.path.as_ref())
65 .cloned()
66 .unwrap_or_else(|| "../../packages/ruby".to_string());
67 let gem_version = ruby_pkg
68 .as_ref()
69 .and_then(|p| p.version.as_ref())
70 .cloned()
71 .or_else(|| config.resolved_version())
72 .unwrap_or_else(|| "0.1.0".to_string());
73
74 files.push(GeneratedFile {
76 path: output_base.join("Gemfile"),
77 content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
78 generated_header: false,
79 });
80
81 files.push(GeneratedFile {
83 path: output_base.join(".rubocop.yaml"),
84 content: render_rubocop_yaml(),
85 generated_header: false,
86 });
87
88 let has_http_fixtures = groups
90 .iter()
91 .flat_map(|g| g.fixtures.iter())
92 .any(|f| f.needs_mock_server());
93
94 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
96 let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
97 cc.args
98 .iter()
99 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
100 });
101
102 if has_file_fixtures || has_http_fixtures {
104 files.push(GeneratedFile {
105 path: output_base.join("spec").join("spec_helper.rb"),
106 content: render_spec_helper(
107 has_file_fixtures,
108 has_http_fixtures,
109 &e2e_config.test_documents_relative_from(1),
110 ),
111 generated_header: true,
112 });
113 }
114
115 let spec_base = output_base.join("spec");
117
118 for group in groups {
119 let active: Vec<&Fixture> = group
120 .fixtures
121 .iter()
122 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
123 .collect();
124
125 if active.is_empty() {
126 continue;
127 }
128
129 let field_resolver_pre = FieldResolver::new(
130 &e2e_config.fields,
131 &e2e_config.fields_optional,
132 &e2e_config.result_fields,
133 &e2e_config.fields_array,
134 &std::collections::HashSet::new(),
135 );
136 let has_any_output = active.iter().any(|f| {
138 if f.is_http_test() {
140 return true;
141 }
142 let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
143 let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
144 expects_error || has_not_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
145 });
146 if !has_any_output {
147 continue;
148 }
149
150 let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
151 let field_resolver = FieldResolver::new(
152 &e2e_config.fields,
153 &e2e_config.fields_optional,
154 &e2e_config.result_fields,
155 &e2e_config.fields_array,
156 &std::collections::HashSet::new(),
157 );
158 let content = render_spec_file(
159 &group.category,
160 &active,
161 &module_path,
162 class_name.as_deref(),
163 &gem_name,
164 &field_resolver,
165 options_type.as_deref(),
166 enum_fields,
167 result_is_simple,
168 e2e_config,
169 has_file_fixtures || has_http_fixtures,
170 );
171 files.push(GeneratedFile {
172 path: spec_base.join(filename),
173 content,
174 generated_header: true,
175 });
176 }
177
178 Ok(files)
179 }
180
181 fn language_name(&self) -> &'static str {
182 "ruby"
183 }
184}
185
186fn render_gemfile(
191 gem_name: &str,
192 gem_path: &str,
193 gem_version: &str,
194 dep_mode: crate::config::DependencyMode,
195) -> String {
196 let gem_line = match dep_mode {
197 crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
198 crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
199 };
200 crate::template_env::render(
201 "ruby/Gemfile.jinja",
202 minijinja::context! {
203 gem_line => gem_line,
204 rspec => tv::gem::RSPEC_E2E,
205 rubocop => tv::gem::RUBOCOP_E2E,
206 rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
207 faraday => tv::gem::FARADAY,
208 },
209 )
210}
211
212fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
213 let header = hash::header(CommentStyle::Hash);
214 let mut out = header;
215 out.push_str("# frozen_string_literal: true\n");
216
217 if has_file_fixtures {
218 let _ = writeln!(out);
219 let _ = writeln!(
220 out,
221 "# Change to the configured test-documents directory so that fixture file paths like"
222 );
223 let _ = writeln!(
224 out,
225 "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
226 );
227 let _ = writeln!(
228 out,
229 "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
230 );
231 let _ = writeln!(
232 out,
233 "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
234 );
235 let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
236 }
237
238 if has_http_fixtures {
239 out.push_str(
240 r#"
241require 'json'
242require 'open3'
243
244# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
245RSpec.configure do |config|
246 config.before(:suite) do
247 bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
248 fixtures_dir = File.expand_path('../../../fixtures', __dir__)
249 unless File.exist?(bin)
250 warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
251 end
252 stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
253 # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
254 url = nil
255 8.times do
256 line = stdout.readline.strip rescue break
257 if line.start_with?('MOCK_SERVER_URL=')
258 url = line.split('=', 2).last
259 ENV['MOCK_SERVER_URL'] = url
260 elsif line.start_with?('MOCK_SERVERS=')
261 json_val = line.split('=', 2).last
262 ENV['MOCK_SERVERS'] = json_val
263 JSON.parse(json_val).each do |fid, furl|
264 ENV["MOCK_SERVER_#{fid.upcase}"] = furl
265 end
266 break
267 elsif url
268 break
269 end
270 end
271 # Drain stdout in background.
272 Thread.new { stdout.read }
273 # Store stdin so we can close it on teardown.
274 @_mock_server_stdin = stdin
275 end
276
277 config.after(:suite) do
278 @_mock_server_stdin&.close
279 end
280end
281"#,
282 );
283 }
284
285 out
286}
287
288fn render_rubocop_yaml() -> String {
289 crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
290}
291
292#[allow(clippy::too_many_arguments)]
293fn render_spec_file(
294 category: &str,
295 fixtures: &[&Fixture],
296 module_path: &str,
297 class_name: Option<&str>,
298 gem_name: &str,
299 field_resolver: &FieldResolver,
300 options_type: Option<&str>,
301 enum_fields: &HashMap<String, String>,
302 result_is_simple: bool,
303 e2e_config: &E2eConfig,
304 needs_spec_helper: bool,
305) -> String {
306 let client_factory = e2e_config
308 .call
309 .overrides
310 .get("ruby")
311 .and_then(|o| o.client_factory.as_deref());
312
313 let require_name = if module_path.is_empty() { gem_name } else { module_path };
315 let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
316
317 let has_http = fixtures.iter().any(|f| f.is_http_test());
318 if needs_spec_helper || has_http {
319 requires.push("spec_helper".to_string());
320 }
321
322 let call_receiver = class_name
324 .map(|s| s.to_string())
325 .unwrap_or_else(|| ruby_module_name(module_path));
326
327 let has_array_contains = fixtures.iter().any(|fixture| {
329 fixture.assertions.iter().any(|a| {
330 matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
331 && a.field
332 .as_deref()
333 .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
334 })
335 });
336
337 let mut examples = Vec::new();
339 for fixture in fixtures {
340 if fixture.http.is_some() {
341 let mut out = String::new();
343 render_http_example(&mut out, fixture);
344 examples.push(out);
345 } else {
346 let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
348 let fixture_call_overrides = fixture_call.overrides.get("ruby");
349 let raw_function_name = fixture_call_overrides
350 .and_then(|o| o.function.as_ref())
351 .cloned()
352 .unwrap_or_else(|| fixture_call.function.clone());
353
354 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
355 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
356 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
357 let is_streaming = raw_function_name == "chat_stream";
358
359 if !expects_error && !has_usable && !has_not_error && !is_streaming {
363 let test_name = sanitize_ident(&fixture.id);
364 let description = fixture.description.replace('\'', "\\'");
365 let mut out = String::new();
366 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
367 out.push_str(" skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
368 out.push_str(" end\n");
369 examples.push(out);
370 } else {
371 let fixture_function_name = if is_streaming {
375 raw_function_name
376 } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
377 format!("{raw_function_name}_async")
378 } else {
379 raw_function_name
380 };
381 let fixture_result_var = &fixture_call.result_var;
382 let fixture_args = &fixture_call.args;
383 let fixture_client_factory = fixture_call_overrides
384 .and_then(|o| o.client_factory.as_deref())
385 .or(client_factory);
386 let fixture_options_type = fixture_call_overrides
387 .and_then(|o| o.options_type.as_deref())
388 .or(options_type);
389
390 let fixture_extra_args: Vec<String> =
391 fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
392 let fixture_result_is_simple =
395 fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
396 let fixture_enum_fields: &HashMap<String, String> =
400 fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
401 let example = if is_streaming {
402 render_chat_stream_example(
403 fixture,
404 &fixture_function_name,
405 &call_receiver,
406 fixture_args,
407 fixture_options_type,
408 fixture_enum_fields,
409 e2e_config,
410 fixture_client_factory,
411 &fixture_extra_args,
412 )
413 } else {
414 render_example(
415 fixture,
416 &fixture_function_name,
417 &call_receiver,
418 fixture_result_var,
419 fixture_args,
420 field_resolver,
421 fixture_options_type,
422 fixture_enum_fields,
423 fixture_result_is_simple,
424 e2e_config,
425 fixture_client_factory,
426 &fixture_extra_args,
427 )
428 };
429 examples.push(example);
430 }
431 }
432 }
433
434 let header = hash::header(CommentStyle::Hash);
435 crate::template_env::render(
436 "ruby/test_file.jinja",
437 minijinja::context! {
438 category => category,
439 requires => requires,
440 has_array_contains => has_array_contains,
441 has_http => has_http,
442 examples => examples,
443 header => header,
444 },
445 )
446}
447
448fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
451 fixture.assertions.iter().any(|a| {
452 if a.assertion_type == "not_error" || a.assertion_type == "error" {
454 return false;
455 }
456 if let Some(f) = &a.field {
458 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
459 return false;
460 }
461 if result_is_simple {
463 let f_lower = f.to_lowercase();
464 if !f.is_empty()
465 && f_lower != "content"
466 && (f_lower.starts_with("metadata")
467 || f_lower.starts_with("document")
468 || f_lower.starts_with("structure"))
469 {
470 return false;
471 }
472 }
473 }
474 true
475 })
476}
477
478struct RubyTestClientRenderer;
486
487impl client::TestClientRenderer for RubyTestClientRenderer {
488 fn language_name(&self) -> &'static str {
489 "ruby"
490 }
491
492 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
498 let escaped_description = description.replace('\'', "\\'");
499 let rendered = crate::template_env::render(
500 "ruby/http_test.jinja",
501 minijinja::context! {
502 fn_name => fn_name,
503 description => escaped_description,
504 skip_reason => skip_reason,
505 },
506 );
507 out.push_str(&rendered);
508 }
509
510 fn render_test_close(&self, out: &mut String) {
512 let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
513 out.push_str(&rendered);
514 }
515
516 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
518 let method = ctx.method.to_uppercase();
519 let method_class = http_method_class(&method);
520
521 let has_body = ctx
522 .body
523 .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
524
525 let ruby_body = if has_body {
526 json_to_ruby(ctx.body.unwrap())
527 } else {
528 String::new()
529 };
530
531 let headers: Vec<minijinja::Value> = ctx
532 .headers
533 .iter()
534 .filter(|(k, _)| {
535 !(has_body && k.to_lowercase() == "content-type")
537 })
538 .map(|(k, v)| {
539 minijinja::context! {
540 key_literal => ruby_string_literal(k),
541 value_literal => ruby_string_literal(v),
542 }
543 })
544 .collect();
545
546 let rendered = crate::template_env::render(
547 "ruby/http_request.jinja",
548 minijinja::context! {
549 method_class => method_class,
550 path => ctx.path,
551 has_body => has_body,
552 ruby_body => ruby_body,
553 headers => headers,
554 response_var => ctx.response_var,
555 },
556 );
557 out.push_str(&rendered);
558 }
559
560 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
565 out.push_str(&format!(" expect({response_var}.code.to_i).to eq({status})\n"));
566 }
567
568 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
572 let header_key = name.to_lowercase();
573 let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
574 let assertion = match expected {
575 "<<present>>" => {
576 format!(" expect({header_expr}).not_to be_nil\n")
577 }
578 "<<absent>>" => {
579 format!(" expect({header_expr}).to be_nil\n")
580 }
581 "<<uuid>>" => {
582 format!(
583 " expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
584 )
585 }
586 literal => {
587 let ruby_val = ruby_string_literal(literal);
588 format!(" expect({header_expr}).to eq({ruby_val})\n")
589 }
590 };
591 out.push_str(&assertion);
592 }
593
594 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
599 match expected {
600 serde_json::Value::String(s) => {
601 let ruby_val = ruby_string_literal(s);
602 out.push_str(&format!(" expect({response_var}.body).to eq({ruby_val})\n"));
603 }
604 _ => {
605 let ruby_val = json_to_ruby(expected);
606 out.push_str(&format!(
607 " _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
608 ));
609 out.push_str(&format!(" expect(_body).to eq({ruby_val})\n"));
610 }
611 }
612 }
613
614 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
616 if let Some(obj) = expected.as_object() {
617 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
618 for (key, val) in obj {
619 let ruby_key = ruby_string_literal(key);
620 let ruby_val = json_to_ruby(val);
621 out.push_str(&format!(" expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
622 }
623 }
624 }
625
626 fn render_assert_validation_errors(
629 &self,
630 out: &mut String,
631 response_var: &str,
632 errors: &[ValidationErrorExpectation],
633 ) {
634 for err in errors {
635 let msg_lit = ruby_string_literal(&err.msg);
636 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
637 out.push_str(" _errors = _body['errors'] || []\n");
638 out.push_str(&format!(
639 " expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
640 ));
641 }
642 }
643}
644
645fn render_http_example(out: &mut String, fixture: &Fixture) {
651 if fixture
655 .http
656 .as_ref()
657 .is_some_and(|h| h.expected_response.status_code == 101)
658 {
659 if let Some(http) = fixture.http.as_ref() {
660 let description = fixture.description.replace('\'', "\\'");
661 let method = http.request.method.to_uppercase();
662 let path = &http.request.path;
663 let rendered = crate::template_env::render(
664 "ruby/http_101_skip.jinja",
665 minijinja::context! {
666 method => method,
667 path => path,
668 description => description,
669 },
670 );
671 out.push_str(&rendered);
672 }
673 return;
674 }
675
676 client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
677}
678
679fn http_method_class(method: &str) -> String {
682 let mut chars = method.chars();
683 match chars.next() {
684 None => String::new(),
685 Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
686 }
687}
688
689#[allow(clippy::too_many_arguments)]
701fn render_chat_stream_example(
702 fixture: &Fixture,
703 function_name: &str,
704 call_receiver: &str,
705 args: &[crate::config::ArgMapping],
706 options_type: Option<&str>,
707 enum_fields: &HashMap<String, String>,
708 e2e_config: &E2eConfig,
709 client_factory: Option<&str>,
710 extra_args: &[String],
711) -> String {
712 let test_name = sanitize_ident(&fixture.id);
713 let description = fixture.description.replace('\'', "\\'");
714 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
715 let fixture_id = fixture.id.clone();
716
717 let (mut setup_lines, args_str) = build_args_and_setup(
718 &fixture.input,
719 args,
720 call_receiver,
721 options_type,
722 enum_fields,
723 false,
724 fixture,
725 );
726
727 let mut final_args = args_str;
728 if !extra_args.is_empty() {
729 let extra_str = extra_args.join(", ");
730 if final_args.is_empty() {
731 final_args = extra_str;
732 } else {
733 final_args = format!("{final_args}, {extra_str}");
734 }
735 }
736
737 let mut needs_finish_reason = false;
740 let mut needs_tool_calls_json = false;
741 let mut needs_tool_calls_0_function_name = false;
742 let mut needs_total_tokens = false;
743 for a in &fixture.assertions {
744 if let Some(f) = a.field.as_deref() {
745 match f {
746 "finish_reason" => needs_finish_reason = true,
747 "tool_calls" => needs_tool_calls_json = true,
748 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
749 "usage.total_tokens" => needs_total_tokens = true,
750 _ => {}
751 }
752 }
753 }
754
755 let mut out = String::new();
756 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
757
758 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
760 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
761 if let Some(cf) = client_factory {
762 if has_mock && let Some(key_var) = api_key_var {
763 let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
764 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
765 out.push_str(" if api_key && !api_key.empty?\n");
766 out.push_str(&format!(
767 " warn \"{test_name}: using real API ({key_var} is set)\"\n"
768 ));
769 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
770 out.push_str(" else\n");
771 out.push_str(&format!(
772 " warn \"{test_name}: using mock server ({key_var} not set)\"\n"
773 ));
774 out.push_str(&format!(" mock_url = {mock_url_expr}\n"));
775 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key', mock_url)\n"));
776 out.push_str(" end\n");
777 } else if has_mock {
778 let base_url_expr = if fixture.has_host_root_route() {
779 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
780 format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
781 } else {
782 format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
783 };
784 out.push_str(&format!(
785 " client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
786 ));
787 } else if let Some(key_var) = api_key_var {
788 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
789 out.push_str(&format!(" skip '{key_var} not set' unless api_key\n"));
790 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
791 } else {
792 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key')\n"));
793 }
794 }
795
796 if let Some(visitor_spec) = &fixture.visitor {
798 let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
799 }
800 for line in &setup_lines {
801 out.push_str(&format!(" {line}\n"));
802 }
803
804 let call_expr = if client_factory.is_some() {
805 format!("client.{function_name}({final_args})")
806 } else {
807 format!("{call_receiver}.{function_name}({final_args})")
808 };
809
810 if expects_error {
811 out.push_str(&format!(" expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
812 out.push_str(" end\n");
813 return out;
814 }
815
816 out.push_str(" chunks = []\n");
818 out.push_str(" stream_content = ''.dup\n");
819 out.push_str(" stream_complete = false\n");
820 if needs_finish_reason {
821 out.push_str(" last_finish_reason = nil\n");
822 }
823 if needs_tool_calls_json {
824 out.push_str(" tool_calls_json = nil\n");
825 }
826 if needs_tool_calls_0_function_name {
827 out.push_str(" tool_calls_0_function_name = nil\n");
828 }
829 if needs_total_tokens {
830 out.push_str(" total_tokens = nil\n");
831 }
832 out.push_str(&format!(" {call_expr} do |chunk|\n"));
833 out.push_str(" chunks << chunk\n");
834 out.push_str(" choice = chunk.choices && chunk.choices[0]\n");
835 out.push_str(" if choice\n");
836 out.push_str(" delta = choice.delta\n");
837 out.push_str(" if delta && delta.content\n");
838 out.push_str(" stream_content << delta.content\n");
839 out.push_str(" end\n");
840 if needs_finish_reason {
841 out.push_str(" if choice.finish_reason\n");
842 out.push_str(" last_finish_reason = choice.finish_reason.to_s\n");
843 out.push_str(" end\n");
844 }
845 if needs_tool_calls_json || needs_tool_calls_0_function_name {
846 out.push_str(" tcs = delta && delta.tool_calls\n");
847 out.push_str(" if tcs && !tcs.empty?\n");
848 if needs_tool_calls_json {
849 out.push_str(
850 " tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
851 );
852 }
853 if needs_tool_calls_0_function_name {
854 out.push_str(
855 " tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
856 );
857 }
858 out.push_str(" end\n");
859 }
860 out.push_str(" end\n");
861 if needs_total_tokens {
862 out.push_str(" if chunk.usage && chunk.usage.total_tokens\n");
863 out.push_str(" total_tokens = chunk.usage.total_tokens\n");
864 out.push_str(" end\n");
865 }
866 out.push_str(" end\n");
867 out.push_str(" stream_complete = true\n");
868
869 for assertion in &fixture.assertions {
871 emit_chat_stream_assertion(&mut out, assertion, e2e_config);
872 }
873
874 if !fixture
877 .assertions
878 .iter()
879 .any(|a| a.field.as_deref() == Some("stream_complete"))
880 {
881 out.push_str(" expect(stream_complete).to be(true)\n");
882 }
883
884 out.push_str(" end\n");
885 out
886}
887
888fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
893 let atype = assertion.assertion_type.as_str();
894 if atype == "not_error" || atype == "error" {
895 return;
896 }
897 let field = assertion.field.as_deref().unwrap_or("");
898
899 enum Kind {
900 Chunks,
901 Bool,
902 Str,
903 IntTokens,
904 Json,
905 Unsupported,
906 }
907
908 let (expr, kind) = match field {
909 "chunks" => ("chunks", Kind::Chunks),
910 "stream_content" => ("stream_content", Kind::Str),
911 "stream_complete" => ("stream_complete", Kind::Bool),
912 "no_chunks_after_done" => ("stream_complete", Kind::Bool),
913 "finish_reason" => ("last_finish_reason", Kind::Str),
914 "tool_calls" => ("tool_calls_json", Kind::Json),
915 "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
916 "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
917 _ => ("", Kind::Unsupported),
918 };
919
920 if matches!(kind, Kind::Unsupported) {
921 out.push_str(&format!(
922 " # skipped: streaming assertion on unsupported field '{field}'\n"
923 ));
924 return;
925 }
926
927 match (atype, &kind) {
928 ("count_min", Kind::Chunks) => {
929 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
930 out.push_str(&format!(" expect({expr}.length).to be >= {n}\n"));
931 }
932 }
933 ("count_equals", Kind::Chunks) => {
934 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
935 out.push_str(&format!(" expect({expr}.length).to eq({n})\n"));
936 }
937 }
938 ("equals", Kind::Str) => {
939 if let Some(val) = &assertion.value {
940 let rb_val = json_to_ruby(val);
941 out.push_str(&format!(" expect({expr}.to_s).to eq({rb_val})\n"));
942 }
943 }
944 ("contains", Kind::Str) => {
945 if let Some(val) = &assertion.value {
946 let rb_val = json_to_ruby(val);
947 out.push_str(&format!(" expect({expr}.to_s).to include({rb_val})\n"));
948 }
949 }
950 ("not_empty", Kind::Str) => {
951 out.push_str(&format!(" expect({expr}.to_s).not_to be_empty\n"));
952 }
953 ("not_empty", Kind::Json) => {
954 out.push_str(&format!(" expect({expr}).not_to be_nil\n"));
955 }
956 ("is_empty", Kind::Str) => {
957 out.push_str(&format!(" expect({expr}.to_s).to be_empty\n"));
958 }
959 ("is_true", Kind::Bool) => {
960 out.push_str(&format!(" expect({expr}).to be(true)\n"));
961 }
962 ("is_false", Kind::Bool) => {
963 out.push_str(&format!(" expect({expr}).to be(false)\n"));
964 }
965 ("greater_than_or_equal", Kind::IntTokens) => {
966 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
967 out.push_str(&format!(" expect({expr}).to be >= {n}\n"));
968 }
969 }
970 ("equals", Kind::IntTokens) => {
971 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
972 out.push_str(&format!(" expect({expr}).to eq({n})\n"));
973 }
974 }
975 _ => {
976 out.push_str(&format!(
977 " # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
978 ));
979 }
980 }
981}
982
983#[allow(clippy::too_many_arguments)]
988fn render_example(
989 fixture: &Fixture,
990 function_name: &str,
991 call_receiver: &str,
992 result_var: &str,
993 args: &[crate::config::ArgMapping],
994 field_resolver: &FieldResolver,
995 options_type: Option<&str>,
996 enum_fields: &HashMap<String, String>,
997 result_is_simple: bool,
998 e2e_config: &E2eConfig,
999 client_factory: Option<&str>,
1000 extra_args: &[String],
1001) -> String {
1002 let test_name = sanitize_ident(&fixture.id);
1003 let description = fixture.description.replace('\'', "\\'");
1004 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1005 let fixture_id = fixture.id.clone();
1006
1007 let (mut setup_lines, args_str) = build_args_and_setup(
1008 &fixture.input,
1009 args,
1010 call_receiver,
1011 options_type,
1012 enum_fields,
1013 result_is_simple,
1014 fixture,
1015 );
1016
1017 let mut visitor_arg = String::new();
1019 if let Some(visitor_spec) = &fixture.visitor {
1020 visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1021 }
1022
1023 let mut final_args = if visitor_arg.is_empty() {
1024 args_str
1025 } else if args_str.is_empty() {
1026 visitor_arg
1027 } else {
1028 format!("{args_str}, {visitor_arg}")
1029 };
1030
1031 if !extra_args.is_empty() {
1033 let extra_str = extra_args.join(", ");
1034 if final_args.is_empty() {
1035 final_args = extra_str;
1036 } else {
1037 final_args = format!("{final_args}, {extra_str}");
1038 }
1039 }
1040
1041 let call_expr = if client_factory.is_some() {
1043 format!("client.{function_name}({final_args})")
1044 } else {
1045 format!("{call_receiver}.{function_name}({final_args})")
1046 };
1047
1048 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1050
1051 let mut assertions_rendered = String::new();
1053 for assertion in &fixture.assertions {
1054 render_assertion(
1055 &mut assertions_rendered,
1056 assertion,
1057 result_var,
1058 field_resolver,
1059 result_is_simple,
1060 e2e_config,
1061 enum_fields,
1062 );
1063 }
1064
1065 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1066 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1067 let has_mock_and_key = has_mock && api_key_var.is_some();
1068 crate::template_env::render(
1069 "ruby/test_function.jinja",
1070 minijinja::context! {
1071 test_name => test_name,
1072 description => description,
1073 expects_error => expects_error,
1074 setup_lines => setup_lines,
1075 call_expr => call_expr,
1076 result_var => result_var,
1077 assertions_rendered => assertions_rendered,
1078 has_usable => has_usable,
1079 client_factory => client_factory,
1080 fixture_id => fixture_id,
1081 call_receiver => call_receiver,
1082 has_mock => has_mock,
1083 api_key_var => api_key_var,
1084 has_mock_and_key => has_mock_and_key,
1085 },
1086 )
1087}
1088
1089fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1094 if let Some(items) = arr.as_array() {
1095 let item_strs: Vec<String> = items
1096 .iter()
1097 .filter_map(|item| {
1098 if let Some(obj) = item.as_object() {
1099 match elem_type {
1100 "BatchBytesItem" => {
1101 let content = obj.get("content").and_then(|v| v.as_array());
1102 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1103 let config = obj.get("config");
1104 let content_code = if let Some(arr) = content {
1105 let bytes: Vec<String> =
1106 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1107 format!("[{}]", bytes.join(", "))
1109 } else {
1110 "[]".to_string()
1111 };
1112 let config_arg = if let Some(cfg) = config {
1113 if cfg.is_null() {
1114 "nil".to_string()
1115 } else {
1116 json_to_ruby(cfg)
1117 }
1118 } else {
1119 "nil".to_string()
1120 };
1121 Some(format!(
1122 "Kreuzberg::{}.new(content: {}, mime_type: \"{}\", config: {})",
1123 elem_type, content_code, mime_type, config_arg
1124 ))
1125 }
1126 "BatchFileItem" => {
1127 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1128 let config = obj.get("config");
1129 let config_arg = if let Some(cfg) = config {
1130 if cfg.is_null() {
1131 "nil".to_string()
1132 } else {
1133 json_to_ruby(cfg)
1134 }
1135 } else {
1136 "nil".to_string()
1137 };
1138 Some(format!(
1139 "Kreuzberg::{}.new(path: \"{}\", config: {})",
1140 elem_type, path, config_arg
1141 ))
1142 }
1143 _ => None,
1144 }
1145 } else {
1146 None
1147 }
1148 })
1149 .collect();
1150 format!("[{}]", item_strs.join(", "))
1151 } else {
1152 "[]".to_string()
1153 }
1154}
1155
1156fn build_args_and_setup(
1157 input: &serde_json::Value,
1158 args: &[crate::config::ArgMapping],
1159 call_receiver: &str,
1160 options_type: Option<&str>,
1161 enum_fields: &HashMap<String, String>,
1162 result_is_simple: bool,
1163 fixture: &crate::fixture::Fixture,
1164) -> (Vec<String>, String) {
1165 let fixture_id = &fixture.id;
1166 if args.is_empty() {
1167 let is_empty_input = match input {
1171 serde_json::Value::Null => true,
1172 serde_json::Value::Object(m) => m.is_empty(),
1173 _ => false,
1174 };
1175 if is_empty_input {
1176 return (Vec::new(), String::new());
1177 }
1178 return (Vec::new(), json_to_ruby(input));
1179 }
1180
1181 let mut setup_lines: Vec<String> = Vec::new();
1182 let mut parts: Vec<String> = Vec::new();
1183 let mut skipped_optional_count: usize = 0;
1186
1187 for arg in args {
1188 if arg.arg_type == "mock_url" {
1189 for _ in 0..skipped_optional_count {
1191 parts.push("nil".to_string());
1192 }
1193 skipped_optional_count = 0;
1194 if fixture.has_host_root_route() {
1195 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1196 setup_lines.push(format!(
1197 "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1198 arg.name,
1199 ));
1200 } else {
1201 setup_lines.push(format!(
1202 "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1203 arg.name,
1204 ));
1205 }
1206 parts.push(arg.name.clone());
1207 continue;
1208 }
1209
1210 if arg.arg_type == "bytes" {
1212 for _ in 0..skipped_optional_count {
1214 parts.push("nil".to_string());
1215 }
1216 skipped_optional_count = 0;
1217 let resolved = resolve_field(input, &arg.field);
1218 if let Some(s) = resolved.as_str() {
1219 if is_file_path(s) {
1220 setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1222 } else if is_base64(s) {
1223 setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1225 } else {
1226 let escaped = ruby_string_literal(s);
1228 setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1229 }
1230 parts.push(arg.name.clone());
1231 } else {
1232 parts.push("nil".to_string());
1233 }
1234 continue;
1235 }
1236
1237 if arg.arg_type == "file_path" {
1239 for _ in 0..skipped_optional_count {
1241 parts.push("nil".to_string());
1242 }
1243 skipped_optional_count = 0;
1244 let resolved = resolve_field(input, &arg.field);
1245 if let Some(s) = resolved.as_str() {
1246 let escaped = ruby_string_literal(s);
1247 parts.push(escaped);
1248 } else if arg.optional {
1249 skipped_optional_count += 1;
1250 continue;
1251 } else {
1252 parts.push("''".to_string());
1253 }
1254 continue;
1255 }
1256
1257 if arg.arg_type == "handle" {
1258 for _ in 0..skipped_optional_count {
1260 parts.push("nil".to_string());
1261 }
1262 skipped_optional_count = 0;
1263 let constructor_name = format!("create_{}", arg.name.to_snake_case());
1265 let config_value = resolve_field(input, &arg.field);
1266 if config_value.is_null()
1267 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1268 {
1269 setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1270 } else {
1271 let literal = json_to_ruby(config_value);
1272 let name = &arg.name;
1273 setup_lines.push(format!("{name}_config = {literal}"));
1274 setup_lines.push(format!(
1275 "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1276 arg.name,
1277 name = name,
1278 ));
1279 }
1280 parts.push(arg.name.clone());
1281 continue;
1282 }
1283
1284 let resolved = resolve_field(input, &arg.field);
1285 let val = if resolved.is_null() { None } else { Some(resolved) };
1286 match val {
1287 None | Some(serde_json::Value::Null) if arg.optional => {
1288 skipped_optional_count += 1;
1290 continue;
1291 }
1292 None | Some(serde_json::Value::Null) => {
1293 for _ in 0..skipped_optional_count {
1295 parts.push("nil".to_string());
1296 }
1297 skipped_optional_count = 0;
1298 let default_val = match arg.arg_type.as_str() {
1299 "string" => "''".to_string(),
1300 "int" | "integer" => "0".to_string(),
1301 "float" | "number" => "0.0".to_string(),
1302 "bool" | "boolean" => "false".to_string(),
1303 _ => "nil".to_string(),
1304 };
1305 parts.push(default_val);
1306 }
1307 Some(v) => {
1308 for _ in 0..skipped_optional_count {
1310 parts.push("nil".to_string());
1311 }
1312 skipped_optional_count = 0;
1313 if arg.arg_type == "json_object" && !v.is_null() {
1316 if let Some(elem_type) = &arg.element_type {
1318 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1319 parts.push(emit_ruby_batch_item_array(v, elem_type));
1320 continue;
1321 }
1322 }
1323 if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1325 let kwargs: Vec<String> = obj
1326 .iter()
1327 .map(|(k, vv)| {
1328 let snake_key = k.to_snake_case();
1329 let rb_val = if enum_fields.contains_key(k) {
1330 if let Some(s) = vv.as_str() {
1331 let snake_val = s.to_snake_case();
1332 format!("'{snake_val}'")
1333 } else {
1334 json_to_ruby(vv)
1335 }
1336 } else {
1337 json_to_ruby(vv)
1338 };
1339 format!("{snake_key}: {rb_val}")
1340 })
1341 .collect();
1342 if result_is_simple {
1343 parts.push(format!("{{{}}}", kwargs.join(", ")));
1344 } else {
1345 parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1346 }
1347 continue;
1348 }
1349 }
1350 parts.push(json_to_ruby(v));
1351 }
1352 }
1353 }
1354
1355 (setup_lines, parts.join(", "))
1356}
1357
1358fn render_assertion(
1359 out: &mut String,
1360 assertion: &Assertion,
1361 result_var: &str,
1362 field_resolver: &FieldResolver,
1363 result_is_simple: bool,
1364 e2e_config: &E2eConfig,
1365 per_call_enum_fields: &HashMap<String, String>,
1366) {
1367 if result_is_simple {
1371 if let Some(f) = &assertion.field {
1372 if !f.is_empty() {
1373 match assertion.assertion_type.as_str() {
1374 "not_empty" => {
1375 out.push_str(&format!(" expect({result_var}.to_s).not_to be_empty\n"));
1376 return;
1377 }
1378 "is_empty" => {
1379 out.push_str(&format!(" expect({result_var}.to_s).to be_empty\n"));
1380 return;
1381 }
1382 "count_equals" => {
1383 if let Some(val) = &assertion.value {
1384 let rb_val = json_to_ruby(val);
1385 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1386 }
1387 return;
1388 }
1389 "count_min" => {
1390 if let Some(val) = &assertion.value {
1391 let rb_val = json_to_ruby(val);
1392 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1393 }
1394 return;
1395 }
1396 _ => {
1397 out.push_str(&format!(
1398 " # skipped: field '{f}' not applicable for simple result type\n"
1399 ));
1400 return;
1401 }
1402 }
1403 }
1404 }
1405 }
1406 if let Some(f) = &assertion.field {
1409 match f.as_str() {
1410 "chunks_have_content" => {
1411 let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1412 match assertion.assertion_type.as_str() {
1413 "is_true" => {
1414 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1415 }
1416 "is_false" => {
1417 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1418 }
1419 _ => {
1420 out.push_str(&format!(
1421 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1422 ));
1423 }
1424 }
1425 return;
1426 }
1427 "chunks_have_embeddings" => {
1428 let pred =
1429 format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1430 match assertion.assertion_type.as_str() {
1431 "is_true" => {
1432 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1433 }
1434 "is_false" => {
1435 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1436 }
1437 _ => {
1438 out.push_str(&format!(
1439 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1440 ));
1441 }
1442 }
1443 return;
1444 }
1445 "embeddings" => {
1449 match assertion.assertion_type.as_str() {
1450 "count_equals" => {
1451 if let Some(val) = &assertion.value {
1452 let rb_val = json_to_ruby(val);
1453 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1454 }
1455 }
1456 "count_min" => {
1457 if let Some(val) = &assertion.value {
1458 let rb_val = json_to_ruby(val);
1459 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1460 }
1461 }
1462 "not_empty" => {
1463 out.push_str(&format!(" expect({result_var}).not_to be_empty\n"));
1464 }
1465 "is_empty" => {
1466 out.push_str(&format!(" expect({result_var}).to be_empty\n"));
1467 }
1468 _ => {
1469 out.push_str(" # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1470 }
1471 }
1472 return;
1473 }
1474 "embedding_dimensions" => {
1475 let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1476 match assertion.assertion_type.as_str() {
1477 "equals" => {
1478 if let Some(val) = &assertion.value {
1479 let rb_val = json_to_ruby(val);
1480 out.push_str(&format!(" expect({expr}).to eq({rb_val})\n"));
1481 }
1482 }
1483 "greater_than" => {
1484 if let Some(val) = &assertion.value {
1485 let rb_val = json_to_ruby(val);
1486 out.push_str(&format!(" expect({expr}).to be > {rb_val}\n"));
1487 }
1488 }
1489 _ => {
1490 out.push_str(
1491 " # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1492 );
1493 }
1494 }
1495 return;
1496 }
1497 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1498 let pred = match f.as_str() {
1499 "embeddings_valid" => {
1500 format!("{result_var}.all? {{ |e| !e.empty? }}")
1501 }
1502 "embeddings_finite" => {
1503 format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1504 }
1505 "embeddings_non_zero" => {
1506 format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1507 }
1508 "embeddings_normalized" => {
1509 format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1510 }
1511 _ => unreachable!(),
1512 };
1513 match assertion.assertion_type.as_str() {
1514 "is_true" => {
1515 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1516 }
1517 "is_false" => {
1518 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1519 }
1520 _ => {
1521 out.push_str(&format!(
1522 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1523 ));
1524 }
1525 }
1526 return;
1527 }
1528 "keywords" | "keywords_count" => {
1531 out.push_str(&format!(
1532 " # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1533 ));
1534 return;
1535 }
1536 _ => {}
1537 }
1538 }
1539
1540 if let Some(f) = &assertion.field {
1542 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1543 out.push_str(&format!(" # skipped: field '{f}' not available on result type\n"));
1544 return;
1545 }
1546 }
1547
1548 if result_is_simple {
1550 if let Some(f) = &assertion.field {
1551 let f_lower = f.to_lowercase();
1552 if !f.is_empty()
1553 && f_lower != "content"
1554 && (f_lower.starts_with("metadata")
1555 || f_lower.starts_with("document")
1556 || f_lower.starts_with("structure"))
1557 {
1558 return;
1559 }
1560 }
1561 }
1562
1563 let field_expr = match &assertion.field {
1567 Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1568 field_resolver.accessor(f, "ruby", result_var)
1569 }
1570 _ => result_var.to_string(),
1571 };
1572
1573 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1581 let resolved = field_resolver.resolve(f);
1582 e2e_config.fields_enum.contains(f)
1583 || e2e_config.fields_enum.contains(resolved)
1584 || per_call_enum_fields.contains_key(f)
1585 || per_call_enum_fields.contains_key(resolved)
1586 });
1587 let stripped_field_expr = if result_is_simple {
1588 format!("{field_expr}.to_s.strip")
1589 } else if field_is_enum {
1590 format!("{field_expr}.to_s")
1591 } else {
1592 field_expr.clone()
1593 };
1594
1595 let field_is_array = assertion
1598 .field
1599 .as_deref()
1600 .filter(|f| !f.is_empty())
1601 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1602
1603 match assertion.assertion_type.as_str() {
1604 "equals" => {
1605 if let Some(expected) = &assertion.value {
1606 let is_boolean_val = expected.as_bool().is_some();
1607 let bool_val = expected
1608 .as_bool()
1609 .map(|b| if b { "true" } else { "false" })
1610 .unwrap_or("");
1611 let rb_val = json_to_ruby(expected);
1612
1613 let rendered = crate::template_env::render(
1614 "ruby/assertion.jinja",
1615 minijinja::context! {
1616 assertion_type => "equals",
1617 stripped_field_expr => stripped_field_expr.clone(),
1618 is_boolean_val => is_boolean_val,
1619 bool_val => bool_val,
1620 expected_val => rb_val,
1621 },
1622 );
1623 out.push_str(&rendered);
1624 }
1625 }
1626 "contains" => {
1627 if let Some(expected) = &assertion.value {
1628 let rb_val = json_to_ruby(expected);
1629 let rendered = crate::template_env::render(
1630 "ruby/assertion.jinja",
1631 minijinja::context! {
1632 assertion_type => "contains",
1633 field_expr => field_expr.clone(),
1634 field_is_array => field_is_array && expected.is_string(),
1635 expected_val => rb_val,
1636 },
1637 );
1638 out.push_str(&rendered);
1639 }
1640 }
1641 "contains_all" => {
1642 if let Some(values) = &assertion.values {
1643 let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1644 let rendered = crate::template_env::render(
1645 "ruby/assertion.jinja",
1646 minijinja::context! {
1647 assertion_type => "contains_all",
1648 field_expr => field_expr.clone(),
1649 field_is_array => field_is_array,
1650 values_list => values_list,
1651 },
1652 );
1653 out.push_str(&rendered);
1654 }
1655 }
1656 "not_contains" => {
1657 if let Some(expected) = &assertion.value {
1658 let rb_val = json_to_ruby(expected);
1659 let rendered = crate::template_env::render(
1660 "ruby/assertion.jinja",
1661 minijinja::context! {
1662 assertion_type => "not_contains",
1663 field_expr => field_expr.clone(),
1664 field_is_array => field_is_array && expected.is_string(),
1665 expected_val => rb_val,
1666 },
1667 );
1668 out.push_str(&rendered);
1669 }
1670 }
1671 "not_empty" => {
1672 let rendered = crate::template_env::render(
1673 "ruby/assertion.jinja",
1674 minijinja::context! {
1675 assertion_type => "not_empty",
1676 field_expr => field_expr.clone(),
1677 },
1678 );
1679 out.push_str(&rendered);
1680 }
1681 "is_empty" => {
1682 let rendered = crate::template_env::render(
1683 "ruby/assertion.jinja",
1684 minijinja::context! {
1685 assertion_type => "is_empty",
1686 field_expr => field_expr.clone(),
1687 },
1688 );
1689 out.push_str(&rendered);
1690 }
1691 "contains_any" => {
1692 if let Some(values) = &assertion.values {
1693 let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1694 let rendered = crate::template_env::render(
1695 "ruby/assertion.jinja",
1696 minijinja::context! {
1697 assertion_type => "contains_any",
1698 field_expr => field_expr.clone(),
1699 values_list => items,
1700 },
1701 );
1702 out.push_str(&rendered);
1703 }
1704 }
1705 "greater_than" => {
1706 if let Some(val) = &assertion.value {
1707 let rb_val = json_to_ruby(val);
1708 let rendered = crate::template_env::render(
1709 "ruby/assertion.jinja",
1710 minijinja::context! {
1711 assertion_type => "greater_than",
1712 field_expr => field_expr.clone(),
1713 expected_val => rb_val,
1714 },
1715 );
1716 out.push_str(&rendered);
1717 }
1718 }
1719 "less_than" => {
1720 if let Some(val) = &assertion.value {
1721 let rb_val = json_to_ruby(val);
1722 let rendered = crate::template_env::render(
1723 "ruby/assertion.jinja",
1724 minijinja::context! {
1725 assertion_type => "less_than",
1726 field_expr => field_expr.clone(),
1727 expected_val => rb_val,
1728 },
1729 );
1730 out.push_str(&rendered);
1731 }
1732 }
1733 "greater_than_or_equal" => {
1734 if let Some(val) = &assertion.value {
1735 let rb_val = json_to_ruby(val);
1736 let rendered = crate::template_env::render(
1737 "ruby/assertion.jinja",
1738 minijinja::context! {
1739 assertion_type => "greater_than_or_equal",
1740 field_expr => field_expr.clone(),
1741 expected_val => rb_val,
1742 },
1743 );
1744 out.push_str(&rendered);
1745 }
1746 }
1747 "less_than_or_equal" => {
1748 if let Some(val) = &assertion.value {
1749 let rb_val = json_to_ruby(val);
1750 let rendered = crate::template_env::render(
1751 "ruby/assertion.jinja",
1752 minijinja::context! {
1753 assertion_type => "less_than_or_equal",
1754 field_expr => field_expr.clone(),
1755 expected_val => rb_val,
1756 },
1757 );
1758 out.push_str(&rendered);
1759 }
1760 }
1761 "starts_with" => {
1762 if let Some(expected) = &assertion.value {
1763 let rb_val = json_to_ruby(expected);
1764 let rendered = crate::template_env::render(
1765 "ruby/assertion.jinja",
1766 minijinja::context! {
1767 assertion_type => "starts_with",
1768 field_expr => field_expr.clone(),
1769 expected_val => rb_val,
1770 },
1771 );
1772 out.push_str(&rendered);
1773 }
1774 }
1775 "ends_with" => {
1776 if let Some(expected) = &assertion.value {
1777 let rb_val = json_to_ruby(expected);
1778 let rendered = crate::template_env::render(
1779 "ruby/assertion.jinja",
1780 minijinja::context! {
1781 assertion_type => "ends_with",
1782 field_expr => field_expr.clone(),
1783 expected_val => rb_val,
1784 },
1785 );
1786 out.push_str(&rendered);
1787 }
1788 }
1789 "min_length" | "max_length" | "count_min" | "count_equals" => {
1790 if let Some(val) = &assertion.value {
1791 if let Some(n) = val.as_u64() {
1792 let rendered = crate::template_env::render(
1793 "ruby/assertion.jinja",
1794 minijinja::context! {
1795 assertion_type => assertion.assertion_type.as_str(),
1796 field_expr => field_expr.clone(),
1797 check_n => n,
1798 },
1799 );
1800 out.push_str(&rendered);
1801 }
1802 }
1803 }
1804 "is_true" => {
1805 let rendered = crate::template_env::render(
1806 "ruby/assertion.jinja",
1807 minijinja::context! {
1808 assertion_type => "is_true",
1809 field_expr => field_expr.clone(),
1810 },
1811 );
1812 out.push_str(&rendered);
1813 }
1814 "is_false" => {
1815 let rendered = crate::template_env::render(
1816 "ruby/assertion.jinja",
1817 minijinja::context! {
1818 assertion_type => "is_false",
1819 field_expr => field_expr.clone(),
1820 },
1821 );
1822 out.push_str(&rendered);
1823 }
1824 "method_result" => {
1825 if let Some(method_name) = &assertion.method {
1826 let lang = "ruby";
1828 let call = &e2e_config.call;
1829 let overrides = call.overrides.get(lang);
1830 let module_path = overrides
1831 .and_then(|o| o.module.as_ref())
1832 .cloned()
1833 .unwrap_or_else(|| call.module.clone());
1834 let call_receiver = ruby_module_name(&module_path);
1835
1836 let call_expr =
1837 build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1838 let check = assertion.check.as_deref().unwrap_or("is_true");
1839
1840 let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1841 "equals" => {
1842 if let Some(val) = &assertion.value {
1843 let is_bool = val.as_bool().is_some();
1844 let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1845 let rb_val = json_to_ruby(val);
1846 (rb_val, is_bool, bool_str.to_string(), 0)
1847 } else {
1848 (String::new(), false, String::new(), 0)
1849 }
1850 }
1851 "greater_than_or_equal" => {
1852 if let Some(val) = &assertion.value {
1853 (json_to_ruby(val), false, String::new(), 0)
1854 } else {
1855 (String::new(), false, String::new(), 0)
1856 }
1857 }
1858 "count_min" => {
1859 if let Some(val) = &assertion.value {
1860 let n = val.as_u64().unwrap_or(0);
1861 (String::new(), false, String::new(), n)
1862 } else {
1863 (String::new(), false, String::new(), 0)
1864 }
1865 }
1866 "contains" => {
1867 if let Some(val) = &assertion.value {
1868 (json_to_ruby(val), false, String::new(), 0)
1869 } else {
1870 (String::new(), false, String::new(), 0)
1871 }
1872 }
1873 _ => (String::new(), false, String::new(), 0),
1874 };
1875
1876 let rendered = crate::template_env::render(
1877 "ruby/assertion.jinja",
1878 minijinja::context! {
1879 assertion_type => "method_result",
1880 call_expr => call_expr,
1881 check => check,
1882 check_val => check_val_str,
1883 is_boolean_check => is_boolean_check,
1884 bool_check_val => bool_check_val,
1885 check_n => check_n_val,
1886 },
1887 );
1888 out.push_str(&rendered);
1889 } else {
1890 panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1891 }
1892 }
1893 "matches_regex" => {
1894 if let Some(expected) = &assertion.value {
1895 let rb_val = json_to_ruby(expected);
1896 let rendered = crate::template_env::render(
1897 "ruby/assertion.jinja",
1898 minijinja::context! {
1899 assertion_type => "matches_regex",
1900 field_expr => field_expr.clone(),
1901 expected_val => rb_val,
1902 },
1903 );
1904 out.push_str(&rendered);
1905 }
1906 }
1907 "not_error" => {
1908 }
1910 "error" => {
1911 }
1913 other => {
1914 panic!("Ruby e2e generator: unsupported assertion type: {other}");
1915 }
1916 }
1917}
1918
1919fn build_ruby_method_call(
1922 call_receiver: &str,
1923 result_var: &str,
1924 method_name: &str,
1925 args: Option<&serde_json::Value>,
1926) -> String {
1927 match method_name {
1928 "root_child_count" => format!("{result_var}.root_node.child_count"),
1929 "root_node_type" => format!("{result_var}.root_node.type"),
1930 "named_children_count" => format!("{result_var}.root_node.named_child_count"),
1931 "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
1932 "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
1933 "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
1934 "contains_node_type" => {
1935 let node_type = args
1936 .and_then(|a| a.get("node_type"))
1937 .and_then(|v| v.as_str())
1938 .unwrap_or("");
1939 format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
1940 }
1941 "find_nodes_by_type" => {
1942 let node_type = args
1943 .and_then(|a| a.get("node_type"))
1944 .and_then(|v| v.as_str())
1945 .unwrap_or("");
1946 format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
1947 }
1948 "run_query" => {
1949 let query_source = args
1950 .and_then(|a| a.get("query_source"))
1951 .and_then(|v| v.as_str())
1952 .unwrap_or("");
1953 let language = args
1954 .and_then(|a| a.get("language"))
1955 .and_then(|v| v.as_str())
1956 .unwrap_or("");
1957 format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1958 }
1959 _ => format!("{result_var}.{method_name}"),
1960 }
1961}
1962
1963fn ruby_module_name(module_path: &str) -> String {
1966 use heck::ToUpperCamelCase;
1967 module_path.to_upper_camel_case()
1968}
1969
1970fn json_to_ruby(value: &serde_json::Value) -> String {
1972 match value {
1973 serde_json::Value::String(s) => ruby_string_literal(s),
1974 serde_json::Value::Bool(true) => "true".to_string(),
1975 serde_json::Value::Bool(false) => "false".to_string(),
1976 serde_json::Value::Number(n) => n.to_string(),
1977 serde_json::Value::Null => "nil".to_string(),
1978 serde_json::Value::Array(arr) => {
1979 let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
1980 format!("[{}]", items.join(", "))
1981 }
1982 serde_json::Value::Object(map) => {
1983 let items: Vec<String> = map
1984 .iter()
1985 .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
1986 .collect();
1987 format!("{{ {} }}", items.join(", "))
1988 }
1989 }
1990}
1991
1992fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
1998 setup_lines.push("visitor = Class.new do".to_string());
1999 for (method_name, action) in &visitor_spec.callbacks {
2000 emit_ruby_visitor_method(setup_lines, method_name, action);
2001 }
2002 setup_lines.push("end.new".to_string());
2003 "visitor".to_string()
2004}
2005
2006fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2008 let params = match method_name {
2009 "visit_link" => "ctx, href, text, title",
2010 "visit_image" => "ctx, src, alt, title",
2011 "visit_heading" => "ctx, level, text, id",
2012 "visit_code_block" => "ctx, lang, code",
2013 "visit_code_inline"
2014 | "visit_strong"
2015 | "visit_emphasis"
2016 | "visit_strikethrough"
2017 | "visit_underline"
2018 | "visit_subscript"
2019 | "visit_superscript"
2020 | "visit_mark"
2021 | "visit_button"
2022 | "visit_summary"
2023 | "visit_figcaption"
2024 | "visit_definition_term"
2025 | "visit_definition_description" => "ctx, text",
2026 "visit_text" => "ctx, text",
2027 "visit_list_item" => "ctx, ordered, marker, text",
2028 "visit_blockquote" => "ctx, content, depth",
2029 "visit_table_row" => "ctx, cells, is_header",
2030 "visit_custom_element" => "ctx, tag_name, html",
2031 "visit_form" => "ctx, action_url, method",
2032 "visit_input" => "ctx, input_type, name, value",
2033 "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2034 "visit_details" => "ctx, is_open",
2035 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2036 "visit_list_start" => "ctx, ordered",
2037 "visit_list_end" => "ctx, ordered, output",
2038 _ => "ctx",
2039 };
2040
2041 let (action_type, action_value, return_form) = match action {
2043 CallbackAction::Skip => ("skip", String::new(), "dict"),
2044 CallbackAction::Continue => ("continue", String::new(), "dict"),
2045 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2046 CallbackAction::Custom { output } => {
2047 let escaped = ruby_string_literal(output);
2048 ("custom", escaped, "dict")
2049 }
2050 CallbackAction::CustomTemplate { template, return_form } => {
2051 let interpolated = ruby_template_to_interpolation(template);
2052 let form = match return_form {
2053 TemplateReturnForm::Dict => "dict",
2054 TemplateReturnForm::BareString => "bare_string",
2055 };
2056 ("custom_template", format!("\"{interpolated}\""), form)
2057 }
2058 };
2059
2060 let rendered = crate::template_env::render(
2061 "ruby/visitor_method.jinja",
2062 minijinja::context! {
2063 method_name => method_name,
2064 params => params,
2065 action_type => action_type,
2066 action_value => action_value,
2067 return_form => return_form,
2068 },
2069 );
2070 for line in rendered.lines() {
2071 setup_lines.push(line.to_string());
2072 }
2073}
2074
2075fn is_file_path(s: &str) -> bool {
2080 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2081 return false;
2082 }
2083
2084 let first = s.chars().next().unwrap_or('\0');
2085 if first.is_ascii_alphanumeric() || first == '_' {
2086 if let Some(slash_pos) = s.find('/') {
2087 if slash_pos > 0 {
2088 let after_slash = &s[slash_pos + 1..];
2089 if after_slash.contains('.') && !after_slash.is_empty() {
2090 return true;
2091 }
2092 }
2093 }
2094 }
2095
2096 false
2097}
2098
2099fn is_base64(s: &str) -> bool {
2102 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2103 return false;
2104 }
2105
2106 if is_file_path(s) {
2107 return false;
2108 }
2109
2110 true
2111}