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 ruby_module = ruby_module_name(module_path);
324 let call_receiver = class_name.map(|s| s.to_string()).unwrap_or_else(|| ruby_module.clone());
325
326 let has_array_contains = fixtures.iter().any(|fixture| {
328 fixture.assertions.iter().any(|a| {
329 matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
330 && a.field
331 .as_deref()
332 .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
333 })
334 });
335
336 let mut examples = Vec::new();
338 for fixture in fixtures {
339 if fixture.http.is_some() {
340 let mut out = String::new();
342 render_http_example(&mut out, fixture);
343 examples.push(out);
344 } else {
345 let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
347 let fixture_call_overrides = fixture_call.overrides.get("ruby");
348 let raw_function_name = fixture_call_overrides
349 .and_then(|o| o.function.as_ref())
350 .cloned()
351 .unwrap_or_else(|| fixture_call.function.clone());
352
353 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
354 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
355 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
356 let is_streaming = raw_function_name == "chat_stream";
357
358 if !expects_error && !has_usable && !has_not_error && !is_streaming {
362 let test_name = sanitize_ident(&fixture.id);
363 let description = fixture.description.replace('\'', "\\'");
364 let mut out = String::new();
365 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
366 out.push_str(" skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
367 out.push_str(" end\n");
368 examples.push(out);
369 } else {
370 let fixture_function_name = if is_streaming {
374 raw_function_name
375 } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
376 format!("{raw_function_name}_async")
377 } else {
378 raw_function_name
379 };
380 let fixture_result_var = &fixture_call.result_var;
381 let fixture_args = &fixture_call.args;
382 let fixture_client_factory = fixture_call_overrides
383 .and_then(|o| o.client_factory.as_deref())
384 .or(client_factory);
385 let fixture_options_type = fixture_call_overrides
386 .and_then(|o| o.options_type.as_deref())
387 .or(options_type);
388
389 let fixture_extra_args: Vec<String> =
390 fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
391 let fixture_result_is_simple =
394 fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
395 let fixture_enum_fields: &HashMap<String, String> =
399 fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
400 let example = if is_streaming {
401 render_chat_stream_example(
402 fixture,
403 &fixture_function_name,
404 &call_receiver,
405 &ruby_module,
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 &ruby_module,
419 fixture_result_var,
420 fixture_args,
421 field_resolver,
422 fixture_options_type,
423 fixture_enum_fields,
424 fixture_result_is_simple,
425 e2e_config,
426 fixture_client_factory,
427 &fixture_extra_args,
428 )
429 };
430 examples.push(example);
431 }
432 }
433 }
434
435 let header = hash::header(CommentStyle::Hash);
436 crate::template_env::render(
437 "ruby/test_file.jinja",
438 minijinja::context! {
439 category => category,
440 requires => requires,
441 has_array_contains => has_array_contains,
442 has_http => has_http,
443 examples => examples,
444 header => header,
445 },
446 )
447}
448
449fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
452 fixture.assertions.iter().any(|a| {
453 if a.assertion_type == "not_error" || a.assertion_type == "error" {
455 return false;
456 }
457 if let Some(f) = &a.field {
459 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
460 return false;
461 }
462 if result_is_simple {
464 let f_lower = f.to_lowercase();
465 if !f.is_empty()
466 && f_lower != "content"
467 && (f_lower.starts_with("metadata")
468 || f_lower.starts_with("document")
469 || f_lower.starts_with("structure"))
470 {
471 return false;
472 }
473 }
474 }
475 true
476 })
477}
478
479struct RubyTestClientRenderer;
487
488impl client::TestClientRenderer for RubyTestClientRenderer {
489 fn language_name(&self) -> &'static str {
490 "ruby"
491 }
492
493 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
499 let escaped_description = description.replace('\'', "\\'");
500 let rendered = crate::template_env::render(
501 "ruby/http_test.jinja",
502 minijinja::context! {
503 fn_name => fn_name,
504 description => escaped_description,
505 skip_reason => skip_reason,
506 },
507 );
508 out.push_str(&rendered);
509 }
510
511 fn render_test_close(&self, out: &mut String) {
513 let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
514 out.push_str(&rendered);
515 }
516
517 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
519 let method = ctx.method.to_uppercase();
520 let method_class = http_method_class(&method);
521
522 let has_body = ctx
523 .body
524 .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
525
526 let ruby_body = if has_body {
527 json_to_ruby(ctx.body.unwrap())
528 } else {
529 String::new()
530 };
531
532 let headers: Vec<minijinja::Value> = ctx
533 .headers
534 .iter()
535 .filter(|(k, _)| {
536 !(has_body && k.to_lowercase() == "content-type")
538 })
539 .map(|(k, v)| {
540 minijinja::context! {
541 key_literal => ruby_string_literal(k),
542 value_literal => ruby_string_literal(v),
543 }
544 })
545 .collect();
546
547 let rendered = crate::template_env::render(
548 "ruby/http_request.jinja",
549 minijinja::context! {
550 method_class => method_class,
551 path => ctx.path,
552 has_body => has_body,
553 ruby_body => ruby_body,
554 headers => headers,
555 response_var => ctx.response_var,
556 },
557 );
558 out.push_str(&rendered);
559 }
560
561 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
566 out.push_str(&format!(" expect({response_var}.code.to_i).to eq({status})\n"));
567 }
568
569 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
573 let header_key = name.to_lowercase();
574 let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
575 let assertion = match expected {
576 "<<present>>" => {
577 format!(" expect({header_expr}).not_to be_nil\n")
578 }
579 "<<absent>>" => {
580 format!(" expect({header_expr}).to be_nil\n")
581 }
582 "<<uuid>>" => {
583 format!(
584 " 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"
585 )
586 }
587 literal => {
588 let ruby_val = ruby_string_literal(literal);
589 format!(" expect({header_expr}).to eq({ruby_val})\n")
590 }
591 };
592 out.push_str(&assertion);
593 }
594
595 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
600 match expected {
601 serde_json::Value::String(s) => {
602 let ruby_val = ruby_string_literal(s);
603 out.push_str(&format!(" expect({response_var}.body).to eq({ruby_val})\n"));
604 }
605 _ => {
606 let ruby_val = json_to_ruby(expected);
607 out.push_str(&format!(
608 " _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
609 ));
610 out.push_str(&format!(" expect(_body).to eq({ruby_val})\n"));
611 }
612 }
613 }
614
615 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
617 if let Some(obj) = expected.as_object() {
618 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
619 for (key, val) in obj {
620 let ruby_key = ruby_string_literal(key);
621 let ruby_val = json_to_ruby(val);
622 out.push_str(&format!(" expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
623 }
624 }
625 }
626
627 fn render_assert_validation_errors(
630 &self,
631 out: &mut String,
632 response_var: &str,
633 errors: &[ValidationErrorExpectation],
634 ) {
635 for err in errors {
636 let msg_lit = ruby_string_literal(&err.msg);
637 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
638 out.push_str(" _errors = _body['errors'] || []\n");
639 out.push_str(&format!(
640 " expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
641 ));
642 }
643 }
644}
645
646fn render_http_example(out: &mut String, fixture: &Fixture) {
652 if fixture
656 .http
657 .as_ref()
658 .is_some_and(|h| h.expected_response.status_code == 101)
659 {
660 if let Some(http) = fixture.http.as_ref() {
661 let description = fixture.description.replace('\'', "\\'");
662 let method = http.request.method.to_uppercase();
663 let path = &http.request.path;
664 let rendered = crate::template_env::render(
665 "ruby/http_101_skip.jinja",
666 minijinja::context! {
667 method => method,
668 path => path,
669 description => description,
670 },
671 );
672 out.push_str(&rendered);
673 }
674 return;
675 }
676
677 client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
678}
679
680fn http_method_class(method: &str) -> String {
683 let mut chars = method.chars();
684 match chars.next() {
685 None => String::new(),
686 Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
687 }
688}
689
690#[allow(clippy::too_many_arguments)]
702fn render_chat_stream_example(
703 fixture: &Fixture,
704 function_name: &str,
705 call_receiver: &str,
706 module_name: &str,
707 args: &[crate::config::ArgMapping],
708 options_type: Option<&str>,
709 enum_fields: &HashMap<String, String>,
710 e2e_config: &E2eConfig,
711 client_factory: Option<&str>,
712 extra_args: &[String],
713) -> String {
714 let test_name = sanitize_ident(&fixture.id);
715 let description = fixture.description.replace('\'', "\\'");
716 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
717 let fixture_id = fixture.id.clone();
718
719 let (mut setup_lines, args_str) = build_args_and_setup(
720 &fixture.input,
721 args,
722 call_receiver,
723 module_name,
724 options_type,
725 enum_fields,
726 false,
727 fixture,
728 );
729
730 let mut final_args = args_str;
731 if !extra_args.is_empty() {
732 let extra_str = extra_args.join(", ");
733 if final_args.is_empty() {
734 final_args = extra_str;
735 } else {
736 final_args = format!("{final_args}, {extra_str}");
737 }
738 }
739
740 let mut needs_finish_reason = false;
743 let mut needs_tool_calls_json = false;
744 let mut needs_tool_calls_0_function_name = false;
745 let mut needs_total_tokens = false;
746 for a in &fixture.assertions {
747 if let Some(f) = a.field.as_deref() {
748 match f {
749 "finish_reason" => needs_finish_reason = true,
750 "tool_calls" => needs_tool_calls_json = true,
751 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
752 "usage.total_tokens" => needs_total_tokens = true,
753 _ => {}
754 }
755 }
756 }
757
758 let mut out = String::new();
759 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
760
761 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
763 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
764 if let Some(cf) = client_factory {
765 if has_mock && let Some(key_var) = api_key_var {
766 let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
767 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
768 out.push_str(" if api_key && !api_key.empty?\n");
769 out.push_str(&format!(
770 " warn \"{test_name}: using real API ({key_var} is set)\"\n"
771 ));
772 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
773 out.push_str(" else\n");
774 out.push_str(&format!(
775 " warn \"{test_name}: using mock server ({key_var} not set)\"\n"
776 ));
777 out.push_str(&format!(" mock_url = {mock_url_expr}\n"));
778 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key', mock_url)\n"));
779 out.push_str(" end\n");
780 } else if has_mock {
781 let base_url_expr = if fixture.has_host_root_route() {
782 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
783 format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
784 } else {
785 format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
786 };
787 out.push_str(&format!(
788 " client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
789 ));
790 } else if let Some(key_var) = api_key_var {
791 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
792 out.push_str(&format!(" skip '{key_var} not set' unless api_key\n"));
793 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
794 } else {
795 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key')\n"));
796 }
797 }
798
799 if let Some(visitor_spec) = &fixture.visitor {
801 let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
802 }
803 for line in &setup_lines {
804 out.push_str(&format!(" {line}\n"));
805 }
806
807 let call_expr = if client_factory.is_some() {
808 format!("client.{function_name}({final_args})")
809 } else {
810 format!("{call_receiver}.{function_name}({final_args})")
811 };
812
813 if expects_error {
814 out.push_str(&format!(" expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
815 out.push_str(" end\n");
816 return out;
817 }
818
819 out.push_str(" chunks = []\n");
821 out.push_str(" stream_content = ''.dup\n");
822 out.push_str(" stream_complete = false\n");
823 if needs_finish_reason {
824 out.push_str(" last_finish_reason = nil\n");
825 }
826 if needs_tool_calls_json {
827 out.push_str(" tool_calls_json = nil\n");
828 }
829 if needs_tool_calls_0_function_name {
830 out.push_str(" tool_calls_0_function_name = nil\n");
831 }
832 if needs_total_tokens {
833 out.push_str(" total_tokens = nil\n");
834 }
835 out.push_str(&format!(" {call_expr} do |chunk|\n"));
836 out.push_str(" chunks << chunk\n");
837 out.push_str(" choice = chunk.choices && chunk.choices[0]\n");
838 out.push_str(" if choice\n");
839 out.push_str(" delta = choice.delta\n");
840 out.push_str(" if delta && delta.content\n");
841 out.push_str(" stream_content << delta.content\n");
842 out.push_str(" end\n");
843 if needs_finish_reason {
844 out.push_str(" if choice.finish_reason\n");
845 out.push_str(" last_finish_reason = choice.finish_reason.to_s\n");
846 out.push_str(" end\n");
847 }
848 if needs_tool_calls_json || needs_tool_calls_0_function_name {
849 out.push_str(" tcs = delta && delta.tool_calls\n");
850 out.push_str(" if tcs && !tcs.empty?\n");
851 if needs_tool_calls_json {
852 out.push_str(
853 " tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
854 );
855 }
856 if needs_tool_calls_0_function_name {
857 out.push_str(
858 " tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
859 );
860 }
861 out.push_str(" end\n");
862 }
863 out.push_str(" end\n");
864 if needs_total_tokens {
865 out.push_str(" if chunk.usage && chunk.usage.total_tokens\n");
866 out.push_str(" total_tokens = chunk.usage.total_tokens\n");
867 out.push_str(" end\n");
868 }
869 out.push_str(" end\n");
870 out.push_str(" stream_complete = true\n");
871
872 for assertion in &fixture.assertions {
874 emit_chat_stream_assertion(&mut out, assertion, e2e_config);
875 }
876
877 if !fixture
880 .assertions
881 .iter()
882 .any(|a| a.field.as_deref() == Some("stream_complete"))
883 {
884 out.push_str(" expect(stream_complete).to be(true)\n");
885 }
886
887 out.push_str(" end\n");
888 out
889}
890
891fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
896 let atype = assertion.assertion_type.as_str();
897 if atype == "not_error" || atype == "error" {
898 return;
899 }
900 let field = assertion.field.as_deref().unwrap_or("");
901
902 enum Kind {
903 Chunks,
904 Bool,
905 Str,
906 IntTokens,
907 Json,
908 Unsupported,
909 }
910
911 let (expr, kind) = match field {
912 "chunks" => ("chunks", Kind::Chunks),
913 "stream_content" => ("stream_content", Kind::Str),
914 "stream_complete" => ("stream_complete", Kind::Bool),
915 "no_chunks_after_done" => ("stream_complete", Kind::Bool),
916 "finish_reason" => ("last_finish_reason", Kind::Str),
917 "tool_calls" => ("tool_calls_json", Kind::Json),
918 "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
919 "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
920 _ => ("", Kind::Unsupported),
921 };
922
923 if matches!(kind, Kind::Unsupported) {
924 out.push_str(&format!(
925 " # skipped: streaming assertion on unsupported field '{field}'\n"
926 ));
927 return;
928 }
929
930 match (atype, &kind) {
931 ("count_min", Kind::Chunks) => {
932 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
933 out.push_str(&format!(" expect({expr}.length).to be >= {n}\n"));
934 }
935 }
936 ("count_equals", Kind::Chunks) => {
937 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
938 out.push_str(&format!(" expect({expr}.length).to eq({n})\n"));
939 }
940 }
941 ("equals", Kind::Str) => {
942 if let Some(val) = &assertion.value {
943 let rb_val = json_to_ruby(val);
944 out.push_str(&format!(" expect({expr}.to_s.strip).to eq({rb_val}.strip)\n"));
948 }
949 }
950 ("contains", Kind::Str) => {
951 if let Some(val) = &assertion.value {
952 let rb_val = json_to_ruby(val);
953 out.push_str(&format!(" expect({expr}.to_s).to include({rb_val})\n"));
954 }
955 }
956 ("not_empty", Kind::Str) => {
957 out.push_str(&format!(" expect({expr}.to_s).not_to be_empty\n"));
958 }
959 ("not_empty", Kind::Json) => {
960 out.push_str(&format!(" expect({expr}).not_to be_nil\n"));
961 }
962 ("is_empty", Kind::Str) => {
963 out.push_str(&format!(" expect({expr}.to_s).to be_empty\n"));
964 }
965 ("is_true", Kind::Bool) => {
966 out.push_str(&format!(" expect({expr}).to be(true)\n"));
967 }
968 ("is_false", Kind::Bool) => {
969 out.push_str(&format!(" expect({expr}).to be(false)\n"));
970 }
971 ("greater_than_or_equal", Kind::IntTokens) => {
972 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
973 out.push_str(&format!(" expect({expr}).to be >= {n}\n"));
974 }
975 }
976 ("equals", Kind::IntTokens) => {
977 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
978 out.push_str(&format!(" expect({expr}).to eq({n})\n"));
979 }
980 }
981 _ => {
982 out.push_str(&format!(
983 " # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
984 ));
985 }
986 }
987}
988
989#[allow(clippy::too_many_arguments)]
994fn render_example(
995 fixture: &Fixture,
996 function_name: &str,
997 call_receiver: &str,
998 module_name: &str,
999 result_var: &str,
1000 args: &[crate::config::ArgMapping],
1001 field_resolver: &FieldResolver,
1002 options_type: Option<&str>,
1003 enum_fields: &HashMap<String, String>,
1004 result_is_simple: bool,
1005 e2e_config: &E2eConfig,
1006 client_factory: Option<&str>,
1007 extra_args: &[String],
1008) -> String {
1009 let test_name = sanitize_ident(&fixture.id);
1010 let description = fixture.description.replace('\'', "\\'");
1011 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1012 let fixture_id = fixture.id.clone();
1013
1014 let (mut setup_lines, args_str) = build_args_and_setup(
1015 &fixture.input,
1016 args,
1017 call_receiver,
1018 module_name,
1019 options_type,
1020 enum_fields,
1021 result_is_simple,
1022 fixture,
1023 );
1024
1025 let mut visitor_arg = String::new();
1027 if let Some(visitor_spec) = &fixture.visitor {
1028 visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1029 }
1030
1031 let mut final_args = if visitor_arg.is_empty() {
1032 args_str
1033 } else if args_str.is_empty() {
1034 visitor_arg
1035 } else {
1036 format!("{args_str}, {visitor_arg}")
1037 };
1038
1039 if !extra_args.is_empty() {
1041 let extra_str = extra_args.join(", ");
1042 if final_args.is_empty() {
1043 final_args = extra_str;
1044 } else {
1045 final_args = format!("{final_args}, {extra_str}");
1046 }
1047 }
1048
1049 let call_expr = if client_factory.is_some() {
1051 format!("client.{function_name}({final_args})")
1052 } else {
1053 format!("{call_receiver}.{function_name}({final_args})")
1054 };
1055
1056 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1058
1059 let mut assertions_rendered = String::new();
1061 for assertion in &fixture.assertions {
1062 render_assertion(
1063 &mut assertions_rendered,
1064 assertion,
1065 result_var,
1066 field_resolver,
1067 result_is_simple,
1068 e2e_config,
1069 enum_fields,
1070 );
1071 }
1072
1073 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1074 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1075 let has_mock_and_key = has_mock && api_key_var.is_some();
1076 crate::template_env::render(
1077 "ruby/test_function.jinja",
1078 minijinja::context! {
1079 test_name => test_name,
1080 description => description,
1081 expects_error => expects_error,
1082 setup_lines => setup_lines,
1083 call_expr => call_expr,
1084 result_var => result_var,
1085 assertions_rendered => assertions_rendered,
1086 has_usable => has_usable,
1087 client_factory => client_factory,
1088 fixture_id => fixture_id,
1089 call_receiver => call_receiver,
1090 has_mock => has_mock,
1091 api_key_var => api_key_var,
1092 has_mock_and_key => has_mock_and_key,
1093 },
1094 )
1095}
1096
1097fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str, module_name: &str) -> String {
1102 if let Some(items) = arr.as_array() {
1103 let item_strs: Vec<String> = items
1104 .iter()
1105 .filter_map(|item| {
1106 if let Some(obj) = item.as_object() {
1107 match elem_type {
1108 "BatchBytesItem" => {
1109 let content = obj.get("content").and_then(|v| v.as_array());
1110 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1111 let config = obj.get("config");
1112 let content_code = if let Some(arr) = content {
1113 let bytes: Vec<String> =
1114 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1115 format!("[{}]", bytes.join(", "))
1117 } else {
1118 "[]".to_string()
1119 };
1120 let config_arg = if let Some(cfg) = config {
1121 if cfg.is_null() {
1122 "nil".to_string()
1123 } else {
1124 json_to_ruby(cfg)
1125 }
1126 } else {
1127 "nil".to_string()
1128 };
1129 Some(format!(
1130 "{}::{}.new(content: {}, mime_type: \"{}\", config: {})",
1131 module_name, elem_type, content_code, mime_type, config_arg
1132 ))
1133 }
1134 "BatchFileItem" => {
1135 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1136 let config = obj.get("config");
1137 let config_arg = if let Some(cfg) = config {
1138 if cfg.is_null() {
1139 "nil".to_string()
1140 } else {
1141 json_to_ruby(cfg)
1142 }
1143 } else {
1144 "nil".to_string()
1145 };
1146 Some(format!(
1147 "{}::{}.new(path: \"{}\", config: {})",
1148 module_name, elem_type, path, config_arg
1149 ))
1150 }
1151 _ => None,
1152 }
1153 } else {
1154 None
1155 }
1156 })
1157 .collect();
1158 format!("[{}]", item_strs.join(", "))
1159 } else {
1160 "[]".to_string()
1161 }
1162}
1163
1164#[allow(clippy::too_many_arguments)]
1165fn build_args_and_setup(
1166 input: &serde_json::Value,
1167 args: &[crate::config::ArgMapping],
1168 call_receiver: &str,
1169 module_name: &str,
1170 options_type: Option<&str>,
1171 enum_fields: &HashMap<String, String>,
1172 result_is_simple: bool,
1173 fixture: &crate::fixture::Fixture,
1174) -> (Vec<String>, String) {
1175 let fixture_id = &fixture.id;
1176 if args.is_empty() {
1177 let is_empty_input = match input {
1181 serde_json::Value::Null => true,
1182 serde_json::Value::Object(m) => m.is_empty(),
1183 _ => false,
1184 };
1185 if is_empty_input {
1186 return (Vec::new(), String::new());
1187 }
1188 return (Vec::new(), json_to_ruby(input));
1189 }
1190
1191 let mut setup_lines: Vec<String> = Vec::new();
1192 let mut parts: Vec<String> = Vec::new();
1193 let mut skipped_optional_count: usize = 0;
1196
1197 for arg in args {
1198 if arg.arg_type == "mock_url" {
1199 for _ in 0..skipped_optional_count {
1201 parts.push("nil".to_string());
1202 }
1203 skipped_optional_count = 0;
1204 if fixture.has_host_root_route() {
1205 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1206 setup_lines.push(format!(
1207 "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1208 arg.name,
1209 ));
1210 } else {
1211 setup_lines.push(format!(
1212 "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1213 arg.name,
1214 ));
1215 }
1216 parts.push(arg.name.clone());
1217 continue;
1218 }
1219
1220 if arg.arg_type == "bytes" {
1222 for _ in 0..skipped_optional_count {
1224 parts.push("nil".to_string());
1225 }
1226 skipped_optional_count = 0;
1227 let resolved = resolve_field(input, &arg.field);
1228 if let Some(s) = resolved.as_str() {
1229 if is_file_path(s) {
1230 setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1232 } else if is_base64(s) {
1233 setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1235 } else {
1236 let escaped = ruby_string_literal(s);
1238 setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1239 }
1240 parts.push(arg.name.clone());
1241 } else {
1242 parts.push("nil".to_string());
1243 }
1244 continue;
1245 }
1246
1247 if arg.arg_type == "file_path" {
1249 for _ in 0..skipped_optional_count {
1251 parts.push("nil".to_string());
1252 }
1253 skipped_optional_count = 0;
1254 let resolved = resolve_field(input, &arg.field);
1255 if let Some(s) = resolved.as_str() {
1256 let escaped = ruby_string_literal(s);
1257 parts.push(escaped);
1258 } else if arg.optional {
1259 skipped_optional_count += 1;
1260 continue;
1261 } else {
1262 parts.push("''".to_string());
1263 }
1264 continue;
1265 }
1266
1267 if arg.arg_type == "handle" {
1268 for _ in 0..skipped_optional_count {
1270 parts.push("nil".to_string());
1271 }
1272 skipped_optional_count = 0;
1273 let constructor_name = format!("create_{}", arg.name.to_snake_case());
1275 let config_value = resolve_field(input, &arg.field);
1276 if config_value.is_null()
1277 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1278 {
1279 setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1280 } else {
1281 let literal = json_to_ruby(config_value);
1282 let name = &arg.name;
1283 setup_lines.push(format!("{name}_config = {literal}"));
1284 setup_lines.push(format!(
1285 "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1286 arg.name,
1287 name = name,
1288 ));
1289 }
1290 parts.push(arg.name.clone());
1291 continue;
1292 }
1293
1294 let resolved = resolve_field(input, &arg.field);
1295 let val = if resolved.is_null() { None } else { Some(resolved) };
1296 match val {
1297 None | Some(serde_json::Value::Null) if arg.optional => {
1298 skipped_optional_count += 1;
1300 continue;
1301 }
1302 None | Some(serde_json::Value::Null) => {
1303 for _ in 0..skipped_optional_count {
1305 parts.push("nil".to_string());
1306 }
1307 skipped_optional_count = 0;
1308 let default_val = match arg.arg_type.as_str() {
1309 "string" => "''".to_string(),
1310 "int" | "integer" => "0".to_string(),
1311 "float" | "number" => "0.0".to_string(),
1312 "bool" | "boolean" => "false".to_string(),
1313 _ => "nil".to_string(),
1314 };
1315 parts.push(default_val);
1316 }
1317 Some(v) => {
1318 for _ in 0..skipped_optional_count {
1320 parts.push("nil".to_string());
1321 }
1322 skipped_optional_count = 0;
1323 if arg.arg_type == "json_object" && !v.is_null() {
1326 if let Some(elem_type) = &arg.element_type {
1328 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1329 parts.push(emit_ruby_batch_item_array(v, elem_type, module_name));
1330 continue;
1331 }
1332 }
1333 if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1335 let kwargs: Vec<String> = obj
1336 .iter()
1337 .map(|(k, vv)| {
1338 let snake_key = k.to_snake_case();
1339 let rb_val = if enum_fields.contains_key(k) {
1340 if let Some(s) = vv.as_str() {
1341 let snake_val = s.to_snake_case();
1342 format!("'{snake_val}'")
1343 } else {
1344 json_to_ruby(vv)
1345 }
1346 } else {
1347 json_to_ruby(vv)
1348 };
1349 format!("{snake_key}: {rb_val}")
1350 })
1351 .collect();
1352 if result_is_simple {
1353 parts.push(format!("{{{}}}", kwargs.join(", ")));
1354 } else {
1355 parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1356 }
1357 continue;
1358 }
1359 }
1360 parts.push(json_to_ruby(v));
1361 }
1362 }
1363 }
1364
1365 (setup_lines, parts.join(", "))
1366}
1367
1368fn render_assertion(
1369 out: &mut String,
1370 assertion: &Assertion,
1371 result_var: &str,
1372 field_resolver: &FieldResolver,
1373 result_is_simple: bool,
1374 e2e_config: &E2eConfig,
1375 per_call_enum_fields: &HashMap<String, String>,
1376) {
1377 if result_is_simple {
1381 if let Some(f) = &assertion.field {
1382 if !f.is_empty() {
1383 match assertion.assertion_type.as_str() {
1384 "not_empty" => {
1385 out.push_str(&format!(" expect({result_var}.to_s).not_to be_empty\n"));
1386 return;
1387 }
1388 "is_empty" => {
1389 out.push_str(&format!(" expect({result_var}.to_s).to be_empty\n"));
1390 return;
1391 }
1392 "count_equals" => {
1393 if let Some(val) = &assertion.value {
1394 let rb_val = json_to_ruby(val);
1395 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1396 }
1397 return;
1398 }
1399 "count_min" => {
1400 if let Some(val) = &assertion.value {
1401 let rb_val = json_to_ruby(val);
1402 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1403 }
1404 return;
1405 }
1406 _ => {
1407 out.push_str(&format!(
1408 " # skipped: field '{f}' not applicable for simple result type\n"
1409 ));
1410 return;
1411 }
1412 }
1413 }
1414 }
1415 }
1416 if let Some(f) = &assertion.field {
1419 match f.as_str() {
1420 "chunks_have_content" => {
1421 let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1422 match assertion.assertion_type.as_str() {
1423 "is_true" => {
1424 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1425 }
1426 "is_false" => {
1427 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1428 }
1429 _ => {
1430 out.push_str(&format!(
1431 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1432 ));
1433 }
1434 }
1435 return;
1436 }
1437 "chunks_have_embeddings" => {
1438 let pred =
1439 format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1440 match assertion.assertion_type.as_str() {
1441 "is_true" => {
1442 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1443 }
1444 "is_false" => {
1445 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1446 }
1447 _ => {
1448 out.push_str(&format!(
1449 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1450 ));
1451 }
1452 }
1453 return;
1454 }
1455 "embeddings" => {
1459 match assertion.assertion_type.as_str() {
1460 "count_equals" => {
1461 if let Some(val) = &assertion.value {
1462 let rb_val = json_to_ruby(val);
1463 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1464 }
1465 }
1466 "count_min" => {
1467 if let Some(val) = &assertion.value {
1468 let rb_val = json_to_ruby(val);
1469 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1470 }
1471 }
1472 "not_empty" => {
1473 out.push_str(&format!(" expect({result_var}).not_to be_empty\n"));
1474 }
1475 "is_empty" => {
1476 out.push_str(&format!(" expect({result_var}).to be_empty\n"));
1477 }
1478 _ => {
1479 out.push_str(" # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1480 }
1481 }
1482 return;
1483 }
1484 "embedding_dimensions" => {
1485 let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1486 match assertion.assertion_type.as_str() {
1487 "equals" => {
1488 if let Some(val) = &assertion.value {
1489 let rb_val = json_to_ruby(val);
1490 out.push_str(&format!(" expect({expr}).to eq({rb_val})\n"));
1491 }
1492 }
1493 "greater_than" => {
1494 if let Some(val) = &assertion.value {
1495 let rb_val = json_to_ruby(val);
1496 out.push_str(&format!(" expect({expr}).to be > {rb_val}\n"));
1497 }
1498 }
1499 _ => {
1500 out.push_str(
1501 " # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1502 );
1503 }
1504 }
1505 return;
1506 }
1507 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1508 let pred = match f.as_str() {
1509 "embeddings_valid" => {
1510 format!("{result_var}.all? {{ |e| !e.empty? }}")
1511 }
1512 "embeddings_finite" => {
1513 format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1514 }
1515 "embeddings_non_zero" => {
1516 format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1517 }
1518 "embeddings_normalized" => {
1519 format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1520 }
1521 _ => unreachable!(),
1522 };
1523 match assertion.assertion_type.as_str() {
1524 "is_true" => {
1525 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1526 }
1527 "is_false" => {
1528 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1529 }
1530 _ => {
1531 out.push_str(&format!(
1532 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1533 ));
1534 }
1535 }
1536 return;
1537 }
1538 "keywords" | "keywords_count" => {
1541 out.push_str(&format!(
1542 " # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1543 ));
1544 return;
1545 }
1546 _ => {}
1547 }
1548 }
1549
1550 if let Some(f) = &assertion.field {
1552 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1553 out.push_str(&format!(" # skipped: field '{f}' not available on result type\n"));
1554 return;
1555 }
1556 }
1557
1558 if result_is_simple {
1560 if let Some(f) = &assertion.field {
1561 let f_lower = f.to_lowercase();
1562 if !f.is_empty()
1563 && f_lower != "content"
1564 && (f_lower.starts_with("metadata")
1565 || f_lower.starts_with("document")
1566 || f_lower.starts_with("structure"))
1567 {
1568 return;
1569 }
1570 }
1571 }
1572
1573 let field_expr = match &assertion.field {
1577 Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1578 field_resolver.accessor(f, "ruby", result_var)
1579 }
1580 _ => result_var.to_string(),
1581 };
1582
1583 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1591 let resolved = field_resolver.resolve(f);
1592 e2e_config.fields_enum.contains(f)
1593 || e2e_config.fields_enum.contains(resolved)
1594 || per_call_enum_fields.contains_key(f)
1595 || per_call_enum_fields.contains_key(resolved)
1596 });
1597 let stripped_field_expr = if result_is_simple {
1598 format!("{field_expr}.to_s.strip")
1599 } else if field_is_enum {
1600 format!("{field_expr}.to_s")
1601 } else {
1602 field_expr.clone()
1603 };
1604
1605 let field_is_array = assertion
1608 .field
1609 .as_deref()
1610 .filter(|f| !f.is_empty())
1611 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1612
1613 match assertion.assertion_type.as_str() {
1614 "equals" => {
1615 if let Some(expected) = &assertion.value {
1616 let is_boolean_val = expected.as_bool().is_some();
1617 let bool_val = expected
1618 .as_bool()
1619 .map(|b| if b { "true" } else { "false" })
1620 .unwrap_or("");
1621 let rb_val = json_to_ruby(expected);
1622 let cmp_expr = if expected.is_string() && !field_is_enum {
1626 format!("{stripped_field_expr}.to_s.strip")
1627 } else {
1628 stripped_field_expr.clone()
1629 };
1630 let cmp_expected = if expected.is_string() && !field_is_enum {
1631 format!("{rb_val}.strip")
1632 } else {
1633 rb_val
1634 };
1635
1636 let rendered = crate::template_env::render(
1637 "ruby/assertion.jinja",
1638 minijinja::context! {
1639 assertion_type => "equals",
1640 stripped_field_expr => cmp_expr,
1641 is_boolean_val => is_boolean_val,
1642 bool_val => bool_val,
1643 expected_val => cmp_expected,
1644 },
1645 );
1646 out.push_str(&rendered);
1647 }
1648 }
1649 "contains" => {
1650 if let Some(expected) = &assertion.value {
1651 let rb_val = json_to_ruby(expected);
1652 let rendered = crate::template_env::render(
1653 "ruby/assertion.jinja",
1654 minijinja::context! {
1655 assertion_type => "contains",
1656 field_expr => field_expr.clone(),
1657 field_is_array => field_is_array && expected.is_string(),
1658 expected_val => rb_val,
1659 },
1660 );
1661 out.push_str(&rendered);
1662 }
1663 }
1664 "contains_all" => {
1665 if let Some(values) = &assertion.values {
1666 let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1667 let rendered = crate::template_env::render(
1668 "ruby/assertion.jinja",
1669 minijinja::context! {
1670 assertion_type => "contains_all",
1671 field_expr => field_expr.clone(),
1672 field_is_array => field_is_array,
1673 values_list => values_list,
1674 },
1675 );
1676 out.push_str(&rendered);
1677 }
1678 }
1679 "not_contains" => {
1680 if let Some(expected) = &assertion.value {
1681 let rb_val = json_to_ruby(expected);
1682 let rendered = crate::template_env::render(
1683 "ruby/assertion.jinja",
1684 minijinja::context! {
1685 assertion_type => "not_contains",
1686 field_expr => field_expr.clone(),
1687 field_is_array => field_is_array && expected.is_string(),
1688 expected_val => rb_val,
1689 },
1690 );
1691 out.push_str(&rendered);
1692 }
1693 }
1694 "not_empty" => {
1695 let rendered = crate::template_env::render(
1696 "ruby/assertion.jinja",
1697 minijinja::context! {
1698 assertion_type => "not_empty",
1699 field_expr => field_expr.clone(),
1700 },
1701 );
1702 out.push_str(&rendered);
1703 }
1704 "is_empty" => {
1705 let rendered = crate::template_env::render(
1706 "ruby/assertion.jinja",
1707 minijinja::context! {
1708 assertion_type => "is_empty",
1709 field_expr => field_expr.clone(),
1710 },
1711 );
1712 out.push_str(&rendered);
1713 }
1714 "contains_any" => {
1715 if let Some(values) = &assertion.values {
1716 let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1717 let rendered = crate::template_env::render(
1718 "ruby/assertion.jinja",
1719 minijinja::context! {
1720 assertion_type => "contains_any",
1721 field_expr => field_expr.clone(),
1722 values_list => items,
1723 },
1724 );
1725 out.push_str(&rendered);
1726 }
1727 }
1728 "greater_than" => {
1729 if let Some(val) = &assertion.value {
1730 let rb_val = json_to_ruby(val);
1731 let rendered = crate::template_env::render(
1732 "ruby/assertion.jinja",
1733 minijinja::context! {
1734 assertion_type => "greater_than",
1735 field_expr => field_expr.clone(),
1736 expected_val => rb_val,
1737 },
1738 );
1739 out.push_str(&rendered);
1740 }
1741 }
1742 "less_than" => {
1743 if let Some(val) = &assertion.value {
1744 let rb_val = json_to_ruby(val);
1745 let rendered = crate::template_env::render(
1746 "ruby/assertion.jinja",
1747 minijinja::context! {
1748 assertion_type => "less_than",
1749 field_expr => field_expr.clone(),
1750 expected_val => rb_val,
1751 },
1752 );
1753 out.push_str(&rendered);
1754 }
1755 }
1756 "greater_than_or_equal" => {
1757 if let Some(val) = &assertion.value {
1758 let rb_val = json_to_ruby(val);
1759 let rendered = crate::template_env::render(
1760 "ruby/assertion.jinja",
1761 minijinja::context! {
1762 assertion_type => "greater_than_or_equal",
1763 field_expr => field_expr.clone(),
1764 expected_val => rb_val,
1765 },
1766 );
1767 out.push_str(&rendered);
1768 }
1769 }
1770 "less_than_or_equal" => {
1771 if let Some(val) = &assertion.value {
1772 let rb_val = json_to_ruby(val);
1773 let rendered = crate::template_env::render(
1774 "ruby/assertion.jinja",
1775 minijinja::context! {
1776 assertion_type => "less_than_or_equal",
1777 field_expr => field_expr.clone(),
1778 expected_val => rb_val,
1779 },
1780 );
1781 out.push_str(&rendered);
1782 }
1783 }
1784 "starts_with" => {
1785 if let Some(expected) = &assertion.value {
1786 let rb_val = json_to_ruby(expected);
1787 let rendered = crate::template_env::render(
1788 "ruby/assertion.jinja",
1789 minijinja::context! {
1790 assertion_type => "starts_with",
1791 field_expr => field_expr.clone(),
1792 expected_val => rb_val,
1793 },
1794 );
1795 out.push_str(&rendered);
1796 }
1797 }
1798 "ends_with" => {
1799 if let Some(expected) = &assertion.value {
1800 let rb_val = json_to_ruby(expected);
1801 let rendered = crate::template_env::render(
1802 "ruby/assertion.jinja",
1803 minijinja::context! {
1804 assertion_type => "ends_with",
1805 field_expr => field_expr.clone(),
1806 expected_val => rb_val,
1807 },
1808 );
1809 out.push_str(&rendered);
1810 }
1811 }
1812 "min_length" | "max_length" | "count_min" | "count_equals" => {
1813 if let Some(val) = &assertion.value {
1814 if let Some(n) = val.as_u64() {
1815 let rendered = crate::template_env::render(
1816 "ruby/assertion.jinja",
1817 minijinja::context! {
1818 assertion_type => assertion.assertion_type.as_str(),
1819 field_expr => field_expr.clone(),
1820 check_n => n,
1821 },
1822 );
1823 out.push_str(&rendered);
1824 }
1825 }
1826 }
1827 "is_true" => {
1828 let rendered = crate::template_env::render(
1829 "ruby/assertion.jinja",
1830 minijinja::context! {
1831 assertion_type => "is_true",
1832 field_expr => field_expr.clone(),
1833 },
1834 );
1835 out.push_str(&rendered);
1836 }
1837 "is_false" => {
1838 let rendered = crate::template_env::render(
1839 "ruby/assertion.jinja",
1840 minijinja::context! {
1841 assertion_type => "is_false",
1842 field_expr => field_expr.clone(),
1843 },
1844 );
1845 out.push_str(&rendered);
1846 }
1847 "method_result" => {
1848 if let Some(method_name) = &assertion.method {
1849 let lang = "ruby";
1851 let call = &e2e_config.call;
1852 let overrides = call.overrides.get(lang);
1853 let module_path = overrides
1854 .and_then(|o| o.module.as_ref())
1855 .cloned()
1856 .unwrap_or_else(|| call.module.clone());
1857 let call_receiver = ruby_module_name(&module_path);
1858
1859 let call_expr =
1860 build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1861 let check = assertion.check.as_deref().unwrap_or("is_true");
1862
1863 let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1864 "equals" => {
1865 if let Some(val) = &assertion.value {
1866 let is_bool = val.as_bool().is_some();
1867 let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1868 let rb_val = json_to_ruby(val);
1869 (rb_val, is_bool, bool_str.to_string(), 0)
1870 } else {
1871 (String::new(), false, String::new(), 0)
1872 }
1873 }
1874 "greater_than_or_equal" => {
1875 if let Some(val) = &assertion.value {
1876 (json_to_ruby(val), false, String::new(), 0)
1877 } else {
1878 (String::new(), false, String::new(), 0)
1879 }
1880 }
1881 "count_min" => {
1882 if let Some(val) = &assertion.value {
1883 let n = val.as_u64().unwrap_or(0);
1884 (String::new(), false, String::new(), n)
1885 } else {
1886 (String::new(), false, String::new(), 0)
1887 }
1888 }
1889 "contains" => {
1890 if let Some(val) = &assertion.value {
1891 (json_to_ruby(val), false, String::new(), 0)
1892 } else {
1893 (String::new(), false, String::new(), 0)
1894 }
1895 }
1896 _ => (String::new(), false, String::new(), 0),
1897 };
1898
1899 let rendered = crate::template_env::render(
1900 "ruby/assertion.jinja",
1901 minijinja::context! {
1902 assertion_type => "method_result",
1903 call_expr => call_expr,
1904 check => check,
1905 check_val => check_val_str,
1906 is_boolean_check => is_boolean_check,
1907 bool_check_val => bool_check_val,
1908 check_n => check_n_val,
1909 },
1910 );
1911 out.push_str(&rendered);
1912 } else {
1913 panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1914 }
1915 }
1916 "matches_regex" => {
1917 if let Some(expected) = &assertion.value {
1918 let rb_val = json_to_ruby(expected);
1919 let rendered = crate::template_env::render(
1920 "ruby/assertion.jinja",
1921 minijinja::context! {
1922 assertion_type => "matches_regex",
1923 field_expr => field_expr.clone(),
1924 expected_val => rb_val,
1925 },
1926 );
1927 out.push_str(&rendered);
1928 }
1929 }
1930 "not_error" => {
1931 }
1933 "error" => {
1934 }
1936 other => {
1937 panic!("Ruby e2e generator: unsupported assertion type: {other}");
1938 }
1939 }
1940}
1941
1942fn build_ruby_method_call(
1945 call_receiver: &str,
1946 result_var: &str,
1947 method_name: &str,
1948 args: Option<&serde_json::Value>,
1949) -> String {
1950 match method_name {
1951 "root_child_count" => format!("{result_var}.root_node.child_count"),
1952 "root_node_type" => format!("{result_var}.root_node.type"),
1953 "named_children_count" => format!("{result_var}.root_node.named_child_count"),
1954 "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
1955 "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
1956 "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
1957 "contains_node_type" => {
1958 let node_type = args
1959 .and_then(|a| a.get("node_type"))
1960 .and_then(|v| v.as_str())
1961 .unwrap_or("");
1962 format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
1963 }
1964 "find_nodes_by_type" => {
1965 let node_type = args
1966 .and_then(|a| a.get("node_type"))
1967 .and_then(|v| v.as_str())
1968 .unwrap_or("");
1969 format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
1970 }
1971 "run_query" => {
1972 let query_source = args
1973 .and_then(|a| a.get("query_source"))
1974 .and_then(|v| v.as_str())
1975 .unwrap_or("");
1976 let language = args
1977 .and_then(|a| a.get("language"))
1978 .and_then(|v| v.as_str())
1979 .unwrap_or("");
1980 format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1981 }
1982 _ => format!("{result_var}.{method_name}"),
1983 }
1984}
1985
1986fn ruby_module_name(module_path: &str) -> String {
1989 use heck::ToUpperCamelCase;
1990 module_path.to_upper_camel_case()
1991}
1992
1993fn json_to_ruby(value: &serde_json::Value) -> String {
1995 match value {
1996 serde_json::Value::String(s) => ruby_string_literal(s),
1997 serde_json::Value::Bool(true) => "true".to_string(),
1998 serde_json::Value::Bool(false) => "false".to_string(),
1999 serde_json::Value::Number(n) => n.to_string(),
2000 serde_json::Value::Null => "nil".to_string(),
2001 serde_json::Value::Array(arr) => {
2002 let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
2003 format!("[{}]", items.join(", "))
2004 }
2005 serde_json::Value::Object(map) => {
2006 let items: Vec<String> = map
2007 .iter()
2008 .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
2009 .collect();
2010 format!("{{ {} }}", items.join(", "))
2011 }
2012 }
2013}
2014
2015fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2021 setup_lines.push("visitor = Class.new do".to_string());
2022 for (method_name, action) in &visitor_spec.callbacks {
2023 emit_ruby_visitor_method(setup_lines, method_name, action);
2024 }
2025 setup_lines.push("end.new".to_string());
2026 "visitor".to_string()
2027}
2028
2029fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2031 let params = match method_name {
2032 "visit_link" => "ctx, href, text, title",
2033 "visit_image" => "ctx, src, alt, title",
2034 "visit_heading" => "ctx, level, text, id",
2035 "visit_code_block" => "ctx, lang, code",
2036 "visit_code_inline"
2037 | "visit_strong"
2038 | "visit_emphasis"
2039 | "visit_strikethrough"
2040 | "visit_underline"
2041 | "visit_subscript"
2042 | "visit_superscript"
2043 | "visit_mark"
2044 | "visit_button"
2045 | "visit_summary"
2046 | "visit_figcaption"
2047 | "visit_definition_term"
2048 | "visit_definition_description" => "ctx, text",
2049 "visit_text" => "ctx, text",
2050 "visit_list_item" => "ctx, ordered, marker, text",
2051 "visit_blockquote" => "ctx, content, depth",
2052 "visit_table_row" => "ctx, cells, is_header",
2053 "visit_custom_element" => "ctx, tag_name, html",
2054 "visit_form" => "ctx, action_url, method",
2055 "visit_input" => "ctx, input_type, name, value",
2056 "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2057 "visit_details" => "ctx, is_open",
2058 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2059 "visit_list_start" => "ctx, ordered",
2060 "visit_list_end" => "ctx, ordered, output",
2061 _ => "ctx",
2062 };
2063
2064 let (action_type, action_value, return_form) = match action {
2066 CallbackAction::Skip => ("skip", String::new(), "dict"),
2067 CallbackAction::Continue => ("continue", String::new(), "dict"),
2068 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2069 CallbackAction::Custom { output } => {
2070 let escaped = ruby_string_literal(output);
2071 ("custom", escaped, "dict")
2072 }
2073 CallbackAction::CustomTemplate { template, return_form } => {
2074 let interpolated = ruby_template_to_interpolation(template);
2075 let form = match return_form {
2076 TemplateReturnForm::Dict => "dict",
2077 TemplateReturnForm::BareString => "bare_string",
2078 };
2079 ("custom_template", format!("\"{interpolated}\""), form)
2080 }
2081 };
2082
2083 let rendered = crate::template_env::render(
2084 "ruby/visitor_method.jinja",
2085 minijinja::context! {
2086 method_name => method_name,
2087 params => params,
2088 action_type => action_type,
2089 action_value => action_value,
2090 return_form => return_form,
2091 },
2092 );
2093 for line in rendered.lines() {
2094 setup_lines.push(line.to_string());
2095 }
2096}
2097
2098fn is_file_path(s: &str) -> bool {
2103 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2104 return false;
2105 }
2106
2107 let first = s.chars().next().unwrap_or('\0');
2108 if first.is_ascii_alphanumeric() || first == '_' {
2109 if let Some(slash_pos) = s.find('/') {
2110 if slash_pos > 0 {
2111 let after_slash = &s[slash_pos + 1..];
2112 if after_slash.contains('.') && !after_slash.is_empty() {
2113 return true;
2114 }
2115 }
2116 }
2117 }
2118
2119 false
2120}
2121
2122fn is_base64(s: &str) -> bool {
2125 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2126 return false;
2127 }
2128
2129 if is_file_path(s) {
2130 return false;
2131 }
2132
2133 true
2134}