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::{Assertion, CallbackAction, Fixture, FixtureGroup, ValidationErrorExpectation};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions as tv;
15use anyhow::Result;
16use heck::ToSnakeCase;
17use std::collections::HashMap;
18use std::fmt::Write as FmtWrite;
19use std::path::PathBuf;
20
21use super::E2eCodegen;
22use super::client;
23
24pub struct RubyCodegen;
26
27impl E2eCodegen for RubyCodegen {
28 fn generate(
29 &self,
30 groups: &[FixtureGroup],
31 e2e_config: &E2eConfig,
32 config: &ResolvedCrateConfig,
33 _type_defs: &[alef_core::ir::TypeDef],
34 ) -> Result<Vec<GeneratedFile>> {
35 let lang = self.language_name();
36 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38 let mut files = Vec::new();
39
40 let call = &e2e_config.call;
42 let overrides = call.overrides.get(lang);
43 let module_path = overrides
44 .and_then(|o| o.module.as_ref())
45 .cloned()
46 .unwrap_or_else(|| call.module.clone());
47 let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
48 let options_type = overrides.and_then(|o| o.options_type.clone());
49 let empty_enum_fields = HashMap::new();
50 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
51 let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
52
53 let ruby_pkg = e2e_config.resolve_package("ruby");
55 let gem_name = ruby_pkg
56 .as_ref()
57 .and_then(|p| p.name.as_ref())
58 .cloned()
59 .unwrap_or_else(|| config.name.replace('-', "_"));
60 let gem_path = ruby_pkg
61 .as_ref()
62 .and_then(|p| p.path.as_ref())
63 .cloned()
64 .unwrap_or_else(|| "../../packages/ruby".to_string());
65 let gem_version = ruby_pkg
66 .as_ref()
67 .and_then(|p| p.version.as_ref())
68 .cloned()
69 .or_else(|| config.resolved_version())
70 .unwrap_or_else(|| "0.1.0".to_string());
71
72 files.push(GeneratedFile {
74 path: output_base.join("Gemfile"),
75 content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
76 generated_header: false,
77 });
78
79 files.push(GeneratedFile {
81 path: output_base.join(".rubocop.yaml"),
82 content: render_rubocop_yaml(),
83 generated_header: false,
84 });
85
86 let has_http_fixtures = groups
88 .iter()
89 .flat_map(|g| g.fixtures.iter())
90 .any(|f| f.needs_mock_server());
91
92 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
94 let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
95 cc.args
96 .iter()
97 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
98 });
99
100 if has_file_fixtures || has_http_fixtures {
102 files.push(GeneratedFile {
103 path: output_base.join("spec").join("spec_helper.rb"),
104 content: render_spec_helper(
105 has_file_fixtures,
106 has_http_fixtures,
107 &e2e_config.test_documents_relative_from(1),
108 ),
109 generated_header: true,
110 });
111 }
112
113 let spec_base = output_base.join("spec");
115
116 for group in groups {
117 let active: Vec<&Fixture> = group
118 .fixtures
119 .iter()
120 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
121 .collect();
122
123 if active.is_empty() {
124 continue;
125 }
126
127 let field_resolver_pre = FieldResolver::new(
128 &e2e_config.fields,
129 &e2e_config.fields_optional,
130 &e2e_config.result_fields,
131 &e2e_config.fields_array,
132 &std::collections::HashSet::new(),
133 );
134 let has_any_output = active.iter().any(|f| {
136 if f.is_http_test() {
138 return true;
139 }
140 let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
141 let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
142 expects_error || has_not_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
143 });
144 if !has_any_output {
145 continue;
146 }
147
148 let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
149 let field_resolver = FieldResolver::new(
150 &e2e_config.fields,
151 &e2e_config.fields_optional,
152 &e2e_config.result_fields,
153 &e2e_config.fields_array,
154 &std::collections::HashSet::new(),
155 );
156 let content = render_spec_file(
157 &group.category,
158 &active,
159 &module_path,
160 class_name.as_deref(),
161 &gem_name,
162 &field_resolver,
163 options_type.as_deref(),
164 enum_fields,
165 result_is_simple,
166 e2e_config,
167 has_file_fixtures || has_http_fixtures,
168 );
169 files.push(GeneratedFile {
170 path: spec_base.join(filename),
171 content,
172 generated_header: true,
173 });
174 }
175
176 Ok(files)
177 }
178
179 fn language_name(&self) -> &'static str {
180 "ruby"
181 }
182}
183
184fn render_gemfile(
189 gem_name: &str,
190 gem_path: &str,
191 gem_version: &str,
192 dep_mode: crate::config::DependencyMode,
193) -> String {
194 let gem_line = match dep_mode {
195 crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
196 crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
197 };
198 crate::template_env::render(
199 "ruby/Gemfile.jinja",
200 minijinja::context! {
201 gem_line => gem_line,
202 rspec => tv::gem::RSPEC_E2E,
203 rubocop => tv::gem::RUBOCOP_E2E,
204 rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
205 faraday => tv::gem::FARADAY,
206 },
207 )
208}
209
210fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
211 let header = hash::header(CommentStyle::Hash);
212 let mut out = header;
213 out.push_str("# frozen_string_literal: true\n");
214
215 if has_file_fixtures {
216 let _ = writeln!(out);
217 let _ = writeln!(
218 out,
219 "# Change to the configured test-documents directory so that fixture file paths like"
220 );
221 let _ = writeln!(
222 out,
223 "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
224 );
225 let _ = writeln!(
226 out,
227 "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
228 );
229 let _ = writeln!(
230 out,
231 "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
232 );
233 let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
234 }
235
236 if has_http_fixtures {
237 out.push_str(
238 r#"
239require 'json'
240require 'open3'
241
242# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
243RSpec.configure do |config|
244 config.before(:suite) do
245 bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
246 fixtures_dir = File.expand_path('../../../fixtures', __dir__)
247 unless File.exist?(bin)
248 warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
249 end
250 stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
251 # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
252 url = nil
253 8.times do
254 line = stdout.readline.strip rescue break
255 if line.start_with?('MOCK_SERVER_URL=')
256 url = line.split('=', 2).last
257 ENV['MOCK_SERVER_URL'] = url
258 elsif line.start_with?('MOCK_SERVERS=')
259 json_val = line.split('=', 2).last
260 ENV['MOCK_SERVERS'] = json_val
261 JSON.parse(json_val).each do |fid, furl|
262 ENV["MOCK_SERVER_#{fid.upcase}"] = furl
263 end
264 break
265 elsif url
266 break
267 end
268 end
269 # Drain stdout in background.
270 Thread.new { stdout.read }
271 # Store stdin so we can close it on teardown.
272 @_mock_server_stdin = stdin
273 end
274
275 config.after(:suite) do
276 @_mock_server_stdin&.close
277 end
278end
279"#,
280 );
281 }
282
283 out
284}
285
286fn render_rubocop_yaml() -> String {
287 crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
288}
289
290#[allow(clippy::too_many_arguments)]
291fn render_spec_file(
292 category: &str,
293 fixtures: &[&Fixture],
294 module_path: &str,
295 class_name: Option<&str>,
296 gem_name: &str,
297 field_resolver: &FieldResolver,
298 options_type: Option<&str>,
299 enum_fields: &HashMap<String, String>,
300 result_is_simple: bool,
301 e2e_config: &E2eConfig,
302 needs_spec_helper: bool,
303) -> String {
304 let client_factory = e2e_config
306 .call
307 .overrides
308 .get("ruby")
309 .and_then(|o| o.client_factory.as_deref());
310
311 let require_name = if module_path.is_empty() { gem_name } else { module_path };
313 let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
314
315 let has_http = fixtures.iter().any(|f| f.is_http_test());
316 if needs_spec_helper || has_http {
317 requires.push("spec_helper".to_string());
318 }
319
320 let call_receiver = class_name
322 .map(|s| s.to_string())
323 .unwrap_or_else(|| ruby_module_name(module_path));
324
325 let has_array_contains = fixtures.iter().any(|fixture| {
327 fixture.assertions.iter().any(|a| {
328 matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
329 && a.field
330 .as_deref()
331 .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
332 })
333 });
334
335 let mut examples = Vec::new();
337 for fixture in fixtures {
338 if fixture.http.is_some() {
339 let mut out = String::new();
341 render_http_example(&mut out, fixture);
342 examples.push(out);
343 } else {
344 let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
346 let fixture_call_overrides = fixture_call.overrides.get("ruby");
347 let raw_function_name = fixture_call_overrides
348 .and_then(|o| o.function.as_ref())
349 .cloned()
350 .unwrap_or_else(|| fixture_call.function.clone());
351
352 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
353 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
354 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
355 let is_streaming = raw_function_name == "chat_stream";
356
357 if !expects_error && !has_usable && !has_not_error && !is_streaming {
361 let test_name = sanitize_ident(&fixture.id);
362 let description = fixture.description.replace('\'', "\\'");
363 let mut out = String::new();
364 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
365 out.push_str(" skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
366 out.push_str(" end\n");
367 examples.push(out);
368 } else {
369 let fixture_function_name = if is_streaming {
373 raw_function_name
374 } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
375 format!("{raw_function_name}_async")
376 } else {
377 raw_function_name
378 };
379 let fixture_result_var = &fixture_call.result_var;
380 let fixture_args = &fixture_call.args;
381 let fixture_client_factory = fixture_call_overrides
382 .and_then(|o| o.client_factory.as_deref())
383 .or(client_factory);
384 let fixture_options_type = fixture_call_overrides
385 .and_then(|o| o.options_type.as_deref())
386 .or(options_type);
387
388 let fixture_extra_args: Vec<String> =
389 fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
390 let fixture_result_is_simple =
393 fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
394 let fixture_enum_fields: &HashMap<String, String> =
398 fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
399 let example = if is_streaming {
400 render_chat_stream_example(
401 fixture,
402 &fixture_function_name,
403 &call_receiver,
404 fixture_args,
405 fixture_options_type,
406 fixture_enum_fields,
407 e2e_config,
408 fixture_client_factory,
409 &fixture_extra_args,
410 )
411 } else {
412 render_example(
413 fixture,
414 &fixture_function_name,
415 &call_receiver,
416 fixture_result_var,
417 fixture_args,
418 field_resolver,
419 fixture_options_type,
420 fixture_enum_fields,
421 fixture_result_is_simple,
422 e2e_config,
423 fixture_client_factory,
424 &fixture_extra_args,
425 )
426 };
427 examples.push(example);
428 }
429 }
430 }
431
432 let header = hash::header(CommentStyle::Hash);
433 crate::template_env::render(
434 "ruby/test_file.jinja",
435 minijinja::context! {
436 category => category,
437 requires => requires,
438 has_array_contains => has_array_contains,
439 has_http => has_http,
440 examples => examples,
441 header => header,
442 },
443 )
444}
445
446fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
449 fixture.assertions.iter().any(|a| {
450 if a.assertion_type == "not_error" || a.assertion_type == "error" {
452 return false;
453 }
454 if let Some(f) = &a.field {
456 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
457 return false;
458 }
459 if result_is_simple {
461 let f_lower = f.to_lowercase();
462 if !f.is_empty()
463 && f_lower != "content"
464 && (f_lower.starts_with("metadata")
465 || f_lower.starts_with("document")
466 || f_lower.starts_with("structure"))
467 {
468 return false;
469 }
470 }
471 }
472 true
473 })
474}
475
476struct RubyTestClientRenderer;
484
485impl client::TestClientRenderer for RubyTestClientRenderer {
486 fn language_name(&self) -> &'static str {
487 "ruby"
488 }
489
490 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
496 let escaped_description = description.replace('\'', "\\'");
497 let rendered = crate::template_env::render(
498 "ruby/http_test.jinja",
499 minijinja::context! {
500 fn_name => fn_name,
501 description => escaped_description,
502 skip_reason => skip_reason,
503 },
504 );
505 out.push_str(&rendered);
506 }
507
508 fn render_test_close(&self, out: &mut String) {
510 let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
511 out.push_str(&rendered);
512 }
513
514 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
516 let method = ctx.method.to_uppercase();
517 let method_class = http_method_class(&method);
518
519 let has_body = ctx
520 .body
521 .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
522
523 let ruby_body = if has_body {
524 json_to_ruby(ctx.body.unwrap())
525 } else {
526 String::new()
527 };
528
529 let headers: Vec<minijinja::Value> = ctx
530 .headers
531 .iter()
532 .filter(|(k, _)| {
533 !(has_body && k.to_lowercase() == "content-type")
535 })
536 .map(|(k, v)| {
537 minijinja::context! {
538 key_literal => ruby_string_literal(k),
539 value_literal => ruby_string_literal(v),
540 }
541 })
542 .collect();
543
544 let rendered = crate::template_env::render(
545 "ruby/http_request.jinja",
546 minijinja::context! {
547 method_class => method_class,
548 path => ctx.path,
549 has_body => has_body,
550 ruby_body => ruby_body,
551 headers => headers,
552 response_var => ctx.response_var,
553 },
554 );
555 out.push_str(&rendered);
556 }
557
558 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
563 out.push_str(&format!(" expect({response_var}.code.to_i).to eq({status})\n"));
564 }
565
566 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
570 let header_key = name.to_lowercase();
571 let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
572 let assertion = match expected {
573 "<<present>>" => {
574 format!(" expect({header_expr}).not_to be_nil\n")
575 }
576 "<<absent>>" => {
577 format!(" expect({header_expr}).to be_nil\n")
578 }
579 "<<uuid>>" => {
580 format!(
581 " 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"
582 )
583 }
584 literal => {
585 let ruby_val = ruby_string_literal(literal);
586 format!(" expect({header_expr}).to eq({ruby_val})\n")
587 }
588 };
589 out.push_str(&assertion);
590 }
591
592 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
597 match expected {
598 serde_json::Value::String(s) => {
599 let ruby_val = ruby_string_literal(s);
600 out.push_str(&format!(" expect({response_var}.body).to eq({ruby_val})\n"));
601 }
602 _ => {
603 let ruby_val = json_to_ruby(expected);
604 out.push_str(&format!(
605 " _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
606 ));
607 out.push_str(&format!(" expect(_body).to eq({ruby_val})\n"));
608 }
609 }
610 }
611
612 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
614 if let Some(obj) = expected.as_object() {
615 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
616 for (key, val) in obj {
617 let ruby_key = ruby_string_literal(key);
618 let ruby_val = json_to_ruby(val);
619 out.push_str(&format!(" expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
620 }
621 }
622 }
623
624 fn render_assert_validation_errors(
627 &self,
628 out: &mut String,
629 response_var: &str,
630 errors: &[ValidationErrorExpectation],
631 ) {
632 for err in errors {
633 let msg_lit = ruby_string_literal(&err.msg);
634 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
635 out.push_str(" _errors = _body['errors'] || []\n");
636 out.push_str(&format!(
637 " expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
638 ));
639 }
640 }
641}
642
643fn render_http_example(out: &mut String, fixture: &Fixture) {
649 if fixture
653 .http
654 .as_ref()
655 .is_some_and(|h| h.expected_response.status_code == 101)
656 {
657 if let Some(http) = fixture.http.as_ref() {
658 let description = fixture.description.replace('\'', "\\'");
659 let method = http.request.method.to_uppercase();
660 let path = &http.request.path;
661 let rendered = crate::template_env::render(
662 "ruby/http_101_skip.jinja",
663 minijinja::context! {
664 method => method,
665 path => path,
666 description => description,
667 },
668 );
669 out.push_str(&rendered);
670 }
671 return;
672 }
673
674 client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
675}
676
677fn http_method_class(method: &str) -> String {
680 let mut chars = method.chars();
681 match chars.next() {
682 None => String::new(),
683 Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
684 }
685}
686
687#[allow(clippy::too_many_arguments)]
699fn render_chat_stream_example(
700 fixture: &Fixture,
701 function_name: &str,
702 call_receiver: &str,
703 args: &[crate::config::ArgMapping],
704 options_type: Option<&str>,
705 enum_fields: &HashMap<String, String>,
706 e2e_config: &E2eConfig,
707 client_factory: Option<&str>,
708 extra_args: &[String],
709) -> String {
710 let test_name = sanitize_ident(&fixture.id);
711 let description = fixture.description.replace('\'', "\\'");
712 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
713 let fixture_id = fixture.id.clone();
714
715 let (mut setup_lines, args_str) = build_args_and_setup(
716 &fixture.input,
717 args,
718 call_receiver,
719 options_type,
720 enum_fields,
721 false,
722 fixture,
723 );
724
725 let mut final_args = args_str;
726 if !extra_args.is_empty() {
727 let extra_str = extra_args.join(", ");
728 if final_args.is_empty() {
729 final_args = extra_str;
730 } else {
731 final_args = format!("{final_args}, {extra_str}");
732 }
733 }
734
735 let mut needs_finish_reason = false;
738 let mut needs_tool_calls_json = false;
739 let mut needs_tool_calls_0_function_name = false;
740 let mut needs_total_tokens = false;
741 for a in &fixture.assertions {
742 if let Some(f) = a.field.as_deref() {
743 match f {
744 "finish_reason" => needs_finish_reason = true,
745 "tool_calls" => needs_tool_calls_json = true,
746 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
747 "usage.total_tokens" => needs_total_tokens = true,
748 _ => {}
749 }
750 }
751 }
752
753 let mut out = String::new();
754 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
755
756 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
758 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
759 if let Some(cf) = client_factory {
760 if has_mock && let Some(key_var) = api_key_var {
761 let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
762 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
763 out.push_str(&format!(" if api_key && !api_key.empty?\n"));
764 out.push_str(&format!(
765 " warn \"{test_name}: using real API ({key_var} is set)\"\n"
766 ));
767 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key: api_key)\n"));
768 out.push_str(" else\n");
769 out.push_str(&format!(
770 " warn \"{test_name}: using mock server ({key_var} not set)\"\n"
771 ));
772 out.push_str(&format!(" mock_url = {mock_url_expr}\n"));
773 out.push_str(&format!(
774 " client = {call_receiver}.{cf}(api_key: 'test-key', base_url: mock_url)\n"
775 ));
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) = match action {
2043 CallbackAction::Skip => ("skip", String::new()),
2044 CallbackAction::Continue => ("continue", String::new()),
2045 CallbackAction::PreserveHtml => ("preserve_html", String::new()),
2046 CallbackAction::Custom { output } => {
2047 let escaped = ruby_string_literal(output);
2048 ("custom", escaped)
2049 }
2050 CallbackAction::CustomTemplate { template } => {
2051 let interpolated = ruby_template_to_interpolation(template);
2052 ("custom", format!("\"{interpolated}\""))
2053 }
2054 };
2055
2056 let rendered = crate::template_env::render(
2057 "ruby/visitor_method.jinja",
2058 minijinja::context! {
2059 method_name => method_name,
2060 params => params,
2061 action_type => action_type,
2062 action_value => action_value,
2063 },
2064 );
2065 for line in rendered.lines() {
2066 setup_lines.push(line.to_string());
2067 }
2068}
2069
2070fn is_file_path(s: &str) -> bool {
2075 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2076 return false;
2077 }
2078
2079 let first = s.chars().next().unwrap_or('\0');
2080 if first.is_ascii_alphanumeric() || first == '_' {
2081 if let Some(slash_pos) = s.find('/') {
2082 if slash_pos > 0 {
2083 let after_slash = &s[slash_pos + 1..];
2084 if after_slash.contains('.') && !after_slash.is_empty() {
2085 return true;
2086 }
2087 }
2088 }
2089 }
2090
2091 false
2092}
2093
2094fn is_base64(s: &str) -> bool {
2097 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2098 return false;
2099 }
2100
2101 if is_file_path(s) {
2102 return false;
2103 }
2104
2105 true
2106}