1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
34use std::path::{Component, Path, PathBuf};
35use std::sync::Arc;
36
37use crate::emit_model::*;
38use crate::emitter;
39use crate::emitter::RuntimeUse;
40use crate::emitter::bindings::WorkerBinding;
41use crate::emitter::harness_names::{
42 SysdriveKind, route_with, sysdrive_name, wrong_method_driver_name,
43};
44use bynk_check::checker;
45use bynk_check::checker::ExprId;
46use bynk_check::hints::HintSink;
47use bynk_check::index::RefSink;
48use bynk_check::locals::LocalsSink;
49use bynk_check::project_model::handler_cross_caps;
50use bynk_check::requirements::RequirementSink;
51use bynk_check::resolver::{self, ResolvedCommons};
52use bynk_check::symbols::*;
53use bynk_project::UnitKind;
54use bynk_project::discovery::*;
55use bynk_project::paths::*;
56use bynk_syntax::error::CompileError;
57use crate::ts_build::*;
59use bynk_check::checker::Types;
60use bynk_check::d1_migrations::D1Migrations;
61use bynk_check::test_suites::{self};
62use bynk_check::wire_format;
63use bynk_syntax::ast::{Case, Visibility};
64
65mod case_body;
68mod harness;
69mod integration_module;
70mod names;
71mod property_generators;
72mod property_tests;
73mod runtime_splice;
74mod stubs;
75mod system_jobs;
76mod system_request;
77mod system_support;
78mod test_cases;
79mod test_deps;
80mod test_main;
81mod test_module;
82mod test_runtime_modules;
83pub use self::harness::RunnableTest;
84pub use self::harness::discovery_manifest;
85use self::harness::*;
86use self::integration_module::*;
87use self::names::*;
88use self::property_generators::*;
89use self::property_tests::*;
90use self::runtime_splice::*;
91use self::stubs::*;
92use self::system_jobs::*;
93use self::system_request::*;
94use self::system_support::*;
95use self::test_cases::*;
96pub use self::test_deps::TestAssetFiles;
97use self::test_deps::*;
98pub use self::test_main::emit_test_main;
99use self::test_main::*;
100use self::test_module::*;
101
102pub const SMOKE_SUITE_SUFFIX: &str = ".smoke.bynk";
105
106pub const TEST_SESSION_KEY: &str = "Ynluay10ZXN0LXNlc3Npb24ta2V5LTAxMjM0NTY3ODk";
109
110pub const EVAL_CASE: &str = "bynk eval";
113
114fn drain_internal_faults(errors: &mut Vec<CompileError>, runtime_use: &RuntimeUse) -> bool {
125 let faults = runtime_use.take_faults();
126 let faulted = !faults.is_empty();
127 let failed = errors
128 .iter()
129 .any(|e| bynk_syntax::Severity::for_error(e) == bynk_syntax::Severity::Error);
130 if !failed {
131 errors.extend(
132 faults
133 .into_iter()
134 .map(crate::emitter::InternalFault::into_compile_error),
135 );
136 }
137 faulted
138}
139
140#[allow(clippy::too_many_arguments)]
147pub fn process_tests(
148 test_groups: &BTreeMap<String, Vec<usize>>,
149 parsed: &[ParsedFile],
150 kinds: &BTreeMap<String, UnitKind>,
151 unit_tables: &HashMap<String, UnitTable>,
152 exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
153 unit_consumes: &HashMap<String, Vec<String>>,
154 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
155 unit_uses: &HashMap<String, Vec<String>>,
156 broken: &bynk_check::project_model::BrokenDeclNames,
158 unit_flattened: &HashMap<String, HashMap<String, String>>,
165 groups: &BTreeMap<String, Vec<usize>>,
168 import_ext: ImportExt,
169 contracts: bool,
173 emitted_barrels: &mut HashSet<PathBuf>,
176 asset_files: &TestAssetFiles,
178 snapshot_files: Option<&BTreeMap<String, String>>,
180 d1_migrations: &D1Migrations,
182 d1_sql: Option<&bynk_check::d1_sql::D1Sql>,
185 binding_modules: &HashMap<String, String>,
188 schema_versions: &HashMap<String, i64>,
192 unit_callees: &HashMap<String, HashMap<ExprId, bynk_check::checker::Callee>>,
194 unit_event_subscriber_shapes: &HashMap<
197 String,
198 HashMap<String, bynk_model::EventSubscriberShape>,
199 >,
200 plain_json: bool,
203 errors: &mut Vec<CompileError>,
204 refs: &mut RefSink,
205 tys: &Arc<Types>,
206) -> (Vec<StagedFile>, Vec<RunnableTest>) {
207 let mut outputs: Vec<StagedFile> = Vec::new();
208 let mut runnable_tests: Vec<RunnableTest> = Vec::new();
209
210 let ready = test_suites::phase_test_bodies(
211 test_groups,
212 parsed,
213 kinds,
214 unit_tables,
215 exports_visibility,
216 unit_consumes,
217 unit_consumes_aliases,
218 unit_uses,
219 broken,
220 errors,
221 refs,
222 &mut bynk_check::locals::LocalsSink::new(),
223 tys,
224 d1_sql,
225 );
226
227 let mut sorted_targets: Vec<&String> = ready.keys().collect();
228 sorted_targets.sort();
229
230 for target_name in sorted_targets {
231 let target_stubs = &ready[target_name];
232 let target_kind = *kinds
235 .get(target_name)
236 .expect("phase_test_bodies only returns targets it resolved against `kinds`");
237 let indices = test_groups.get(target_name).unwrap();
238 let hidden =
241 test_suites::privileged_view(target_name, unit_tables, unit_uses, unit_consumes)
242 .map(|v| v.hidden)
243 .unwrap_or_default();
244
245 let runtime_use = RuntimeUse::default();
247 let emit_out = emit_test_module(
248 target_name,
249 target_kind,
250 indices,
251 parsed,
252 target_stubs,
253 unit_tables,
254 unit_consumes,
255 unit_consumes_aliases,
256 unit_uses,
257 unit_flattened,
258 exports_visibility,
259 import_ext,
260 contracts,
261 &hidden,
262 asset_harness(
263 target_name,
264 unit_uses,
265 unit_consumes,
266 unit_tables,
267 asset_files,
268 ),
269 fixture_consts(indices, parsed, asset_files),
270 binding_modules,
271 schema_versions,
272 unit_event_subscriber_shapes.get(target_name),
273 target_emits_events(
274 target_name,
275 target_kind,
276 unit_tables,
277 unit_flattened,
278 unit_callees,
279 ),
280 d1_migrations,
281 snapshot_files,
282 plain_json,
283 &runtime_use,
284 tys,
285 );
286 let emit_out = if drain_internal_faults(errors, &runtime_use) {
287 None
288 } else {
289 emit_out
290 };
291 if let Some((path, program, source_map, runnable)) = emit_out {
292 outputs.push(StagedFile {
293 output_path: path,
294 document: Document::Ts(program),
295 source_map,
296 debug_metadata: None,
297 });
298 runnable_tests.push(runnable);
299
300 let mut imported: Vec<&str> = vec![target_name.as_str()];
305 if let Some(consumed) = unit_consumes.get(target_name) {
306 imported.extend(consumed.iter().map(String::as_str));
307 }
308 if let Some(used) = unit_uses.get(target_name) {
309 imported.extend(used.iter().map(String::as_str));
310 }
311 imported.extend(hidden.values().map(String::as_str));
313 for name in imported {
314 if let Some(barrel) = crate::emitter::commons_barrel::emit_commons_barrel(
315 name,
316 groups,
317 parsed,
318 import_ext,
319 emitted_barrels,
320 &[],
321 ) {
322 outputs.push(barrel);
323 }
324 }
325 }
326 }
327
328 (outputs, runnable_tests)
331}
332
333#[derive(Clone, Copy)]
353pub struct IntegrationD1<'a> {
354 pub migrations: &'a D1Migrations,
355 pub sql: Option<&'a bynk_check::d1_sql::D1Sql>,
356}
357
358impl<'a> IntegrationD1<'a> {
359 pub fn new(migrations: &'a D1Migrations, sql: Option<&'a bynk_check::d1_sql::D1Sql>) -> Self {
360 Self { migrations, sql }
361 }
362}
363
364#[allow(clippy::too_many_arguments)]
365pub fn process_integration_tests(
366 integration_groups: &BTreeMap<String, Vec<usize>>,
367 parsed: &[ParsedFile],
368 kinds: &BTreeMap<String, UnitKind>,
369 unit_tables: &HashMap<String, UnitTable>,
370 unit_consumes: &HashMap<String, Vec<String>>,
371 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
372 unit_uses: &HashMap<String, Vec<String>>,
373 broken: &bynk_check::project_model::BrokenDeclNames,
375 groups: &BTreeMap<String, Vec<usize>>,
377 emitted_barrels: &mut HashSet<PathBuf>,
379 asset_files: &TestAssetFiles,
381 d1: IntegrationD1<'_>,
383 context_bindings: Option<&BTreeMap<String, Vec<WorkerBinding>>>,
386 event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
388 remote: Option<&crate::emit_model::RemoteTests>,
390 plain_json: bool,
393 errors: &mut Vec<CompileError>,
394 refs: &mut RefSink,
395 tys: &Arc<Types>,
396) -> (Vec<StagedFile>, Vec<RunnableTest>) {
397 let mut outputs: Vec<StagedFile> = Vec::new();
398 let mut runnables: Vec<RunnableTest> = Vec::new();
399
400 let ready = test_suites::phase_integration_bodies(
401 integration_groups,
402 parsed,
403 kinds,
404 unit_tables,
405 unit_consumes,
406 unit_consumes_aliases,
407 unit_uses,
408 broken,
409 errors,
410 refs,
411 tys,
412 d1.sql,
413 );
414 let d1_migrations = d1.migrations;
415
416 let mut sorted: Vec<&String> = ready.keys().collect();
417 sorted.sort();
418
419 for group_name in sorted {
420 let indices = integration_groups.get(group_name).unwrap();
421 let first = indices[0];
422 let Some(decl) = parsed[first].integration() else {
423 continue;
424 };
425 let suite_target = decl.target.joined();
429 let suite_name = suite_target.clone();
430 let participants = test_suites::infer_participants(&suite_target, unit_consumes, kinds);
432 let harness_participants = test_suites::infer_harness_participants(
435 &suite_target,
436 unit_consumes,
437 kinds,
438 event_subscribers,
439 );
440 let cross_context = ready
443 .get(group_name)
444 .expect("phase_integration_bodies only returns groups it resolved");
445
446 let mut uses_targets: Vec<String> = Vec::new();
447 for &i in indices {
448 if let Some(d) = parsed[i].integration() {
449 for u in &d.uses {
450 let q = u.target.joined();
451 if !uses_targets.contains(&q) {
452 uses_targets.push(q);
453 }
454 }
455 }
456 }
457
458 let mut case_inputs: Vec<SystemCaseInput> = Vec::new();
462 for &i in indices {
463 let Some(d) = parsed[i].integration() else {
464 continue;
465 };
466 let rel_path = parsed[i].identity_path().to_string_lossy().into_owned();
467 let map_source = parsed[i].map_source_name();
468 for case in &d.cases {
469 case_inputs.push(SystemCaseInput {
470 case,
471 suite_fns: test_suites::SuiteItems::of(d),
472 tier: case_effective_tier(case, d),
473 env: bynk_check::test_env::case_env(d, case, asset_files.fixtures),
474 env_values: bynk_check::test_env::case_env_values(d, case),
475 source: parsed[i].source(),
476 rel_path: rel_path.clone(),
477 map_source: map_source.clone(),
478 });
479 }
480 }
481 if let Some(all) = context_bindings {
487 let mut names: BTreeMap<String, String> = BTreeMap::new();
488 for p in &harness_participants {
489 for b in all.get(p).into_iter().flatten() {
490 names
491 .entry(b.name.clone())
492 .or_insert_with(|| format!("a binding of `{p}`'s Worker"));
493 }
494 for secret in foreign_caller_secrets(p, unit_tables) {
495 names.entry(secret).or_insert_with(|| {
496 format!("a foreign caller's secret the harness sets on `{p}`'s Worker")
497 });
498 }
499 }
500 names.entry("__bynkClock".to_string()).or_insert_with(|| {
502 "the harness clock the test harness sets on the participants' Workers".to_string()
503 });
504 let callers = std::iter::once(HARNESS_CALLER)
507 .chain(harness_participants.iter().map(String::as_str));
508 for key in callers.filter_map(wire_format::edge_key_from).chain(
509 harness_participants
510 .iter()
511 .filter_map(|p| wire_format::edge_key_to(p)),
512 ) {
513 names.entry(key).or_insert_with(|| {
514 "a call-edge key the harness sets on the participants' Workers".to_string()
515 });
516 }
517 for &i in indices {
518 if let Some(d) = parsed[i].integration() {
519 bynk_check::test_env::check_env_binding_clash(d, &names, errors);
520 }
521 }
522 }
523 let view =
525 test_suites::integration_view(&uses_targets, &participants, unit_tables, unit_uses);
526 let runtime_use = RuntimeUse::default();
527 let emitted = emit_integration_module(
528 &suite_name,
529 &participants,
530 &harness_participants,
531 context_bindings,
532 &uses_targets,
533 &view,
534 cross_context,
535 unit_tables,
536 &case_inputs,
537 participants.first().and_then(|target| {
538 asset_harness(target, unit_uses, unit_consumes, unit_tables, asset_files)
539 }),
540 fixture_consts(indices, parsed, asset_files),
541 remote,
542 d1_migrations,
543 errors,
544 tys,
545 plain_json,
546 &runtime_use,
547 );
548 let emitted = if drain_internal_faults(errors, &runtime_use) {
549 None
550 } else {
551 emitted
552 };
553 if let Some((path, program, source_map, runnable)) = emitted {
554 outputs.push(StagedFile {
555 output_path: path,
556 document: Document::Ts(program),
557 source_map,
558 debug_metadata: None,
559 });
560 runnables.push(runnable);
561
562 let owners: BTreeSet<&String> = view.hidden.values().collect();
568 for name in uses_targets.iter().chain(owners) {
569 if let Some(barrel) = crate::emitter::commons_barrel::emit_commons_barrel(
570 name,
571 groups,
572 parsed,
573 ImportExt::Js,
574 emitted_barrels,
575 &[],
576 ) {
577 outputs.push(barrel);
578 }
579 }
580 }
581 }
582
583 (outputs, runnables)
584}
585
586fn foreign_caller_secrets(p: &str, unit_tables: &HashMap<String, UnitTable>) -> Vec<String> {
590 let Some(t) = unit_tables.get(p) else {
591 return Vec::new();
592 };
593 let mut secrets: Vec<String> = t
594 .services
595 .values()
596 .flat_map(|s| s.handlers.iter())
597 .filter_map(|h| bynk_check::actors::call_admission_for(h, &t.actors))
598 .flat_map(|a| a.foreign.into_iter().map(|f| f.secret))
599 .collect();
600 secrets.sort();
601 secrets.dedup();
602 secrets
603}
604
605struct SystemCaseInput<'a> {
608 case: &'a Case,
609 suite_fns: test_suites::SuiteItems<'a>,
611 tier: bynk_syntax::ast::TestTier,
613 env: BTreeMap<String, String>,
616 env_values: BTreeMap<String, bynk_check::test_env::EnvValue>,
619 source: &'a str,
620 rel_path: String,
621 map_source: String,
622}
623
624#[cfg(test)]
626mod test_support {
627 use bynk_syntax::ast::{BaseType, Ident, TypeRef};
628 use bynk_syntax::span::Span;
629
630 pub(super) fn named(n: &str) -> TypeRef {
631 TypeRef::Named(Ident {
632 name: n.to_string(),
633 span: Span::default(),
634 })
635 }
636 pub(super) fn base(b: BaseType) -> TypeRef {
637 TypeRef::Base(b, Span::default())
638 }
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644 use bynk_syntax::ast::{BaseType, TypeRef};
645 use bynk_syntax::span::Span;
646
647 use super::test_support::{base, named};
649
650 fn ts_type_ref(r: &TypeRef) -> String {
652 bynk_ts::print_type(&emitter::ts_types::ts_type_of(r))
653 }
654
655 fn faulted_use() -> RuntimeUse {
656 let ru = RuntimeUse::default();
657 ru.note_internal_fault(Span::new(1, 2), "receiver namespace".to_string());
658 ru
659 }
660
661 #[test]
662 fn a_fault_is_reported_when_the_project_has_no_other_error() {
663 let mut errors = Vec::new();
664 assert!(drain_internal_faults(&mut errors, &faulted_use()));
665 assert_eq!(errors.len(), 1);
666 assert_eq!(errors[0].category, crate::emitter::MISSING_CHECKER_FACT);
667 }
668
669 #[test]
670 fn a_fault_in_a_project_that_already_has_errors_is_drained_not_reported() {
671 let mut errors = vec![CompileError::new("test.other", Span::new(0, 1), "x")];
672 let ru = faulted_use();
673 assert!(
674 drain_internal_faults(&mut errors, &ru),
675 "the output is still dropped"
676 );
677 assert_eq!(errors.len(), 1, "no internal error on top of the real one");
678 assert!(ru.take_faults().is_empty(), "drained");
679 }
680
681 #[test]
682 fn a_fault_beside_only_warnings_is_still_reported() {
683 let warning = bynk_syntax::diagnostics::REGISTRY
684 .iter()
685 .find(|d| d.severity == bynk_syntax::Severity::Warning)
686 .expect("the registry has a warning")
687 .code;
688 let mut errors = vec![CompileError::new(warning, Span::new(0, 1), "x")];
689 let ru = faulted_use();
690 assert!(drain_internal_faults(&mut errors, &ru));
691 assert_eq!(errors.len(), 2, "the warning, then the reported fault");
692 assert_eq!(errors[1].category, crate::emitter::MISSING_CHECKER_FACT);
693 }
694
695 #[test]
696 fn ts_type_ref_bases_and_generics() {
697 assert_eq!(ts_type_ref(&base(BaseType::Int)), "number");
698 assert_eq!(ts_type_ref(&base(BaseType::Float)), "number");
699 assert_eq!(ts_type_ref(&base(BaseType::String)), "string");
700 assert_eq!(ts_type_ref(&base(BaseType::Bool)), "boolean");
701 assert_eq!(ts_type_ref(&named("Order")), "Order");
702 assert_eq!(
703 ts_type_ref(&TypeRef::List(Box::new(named("Order")), Span::default())),
704 "readonly Order[]"
705 );
706 assert_eq!(
707 ts_type_ref(&TypeRef::Option(
708 Box::new(base(BaseType::Int)),
709 Span::default()
710 )),
711 "Option<number>"
712 );
713 assert_eq!(
714 ts_type_ref(&TypeRef::Effect(
715 Box::new(TypeRef::Unit(Span::default())),
716 Span::default()
717 )),
718 "globalThis.Promise<void>"
719 );
720 assert_eq!(
721 ts_type_ref(&TypeRef::Map(
722 Box::new(base(BaseType::String)),
723 Box::new(named("V")),
724 Span::default()
725 )),
726 "ReadonlyMap<string, V>"
727 );
728 assert_eq!(
729 ts_type_ref(&TypeRef::Result(
730 Box::new(named("T")),
731 Box::new(named("E")),
732 Span::default()
733 )),
734 "Result<T, E>"
735 );
736 assert_eq!(
737 ts_type_ref(&TypeRef::HttpResult(Box::new(named("T")), Span::default())),
738 "HttpResult<T>"
739 );
740 assert_eq!(
741 ts_type_ref(&TypeRef::ValidationError(Span::default())),
742 "ValidationError"
743 );
744 assert_eq!(
745 ts_type_ref(&TypeRef::DecodeError(Span::default())),
746 "DecodeError"
747 );
748 }
749
750 #[test]
751 fn ts_type_ref_fn_uses_positional_param_names() {
752 let f = TypeRef::Fn(
753 vec![base(BaseType::Int), named("Order")],
754 Box::new(TypeRef::Unit(Span::default())),
755 Span::default(),
756 );
757 assert_eq!(ts_type_ref(&f), "(a0: number, a1: Order) => void");
758 }
759
760 #[test]
761 fn ts_type_ref_qualified_prefixes_only_scoped_names() {
762 let mut scope: HashSet<String> = HashSet::new();
763 scope.insert("Order".to_string());
764 assert_eq!(
766 bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
767 &named("Order"),
768 &scope,
769 "Ns"
770 )),
771 "Ns.Order"
772 );
773 assert_eq!(
775 bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
776 &named("Other"),
777 &scope,
778 "Ns"
779 )),
780 "Other"
781 );
782 assert_eq!(
784 bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
785 &TypeRef::List(Box::new(named("Order")), Span::default()),
786 &scope,
787 "Ns"
788 )),
789 "readonly Ns.Order[]"
790 );
791 assert_eq!(
793 bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
794 &base(BaseType::Int),
795 &scope,
796 "Ns"
797 )),
798 "number"
799 );
800 }
801
802 #[test]
805 fn run_id_reads_the_environment_only_in_a_remote_build() {
806 let remote = bynk_ts::print_stmt(&run_id_stmt(true), 0);
807 assert!(remote.contains("BYNK_TEST_RUN_ID"));
808 let local = bynk_ts::print_stmt(&run_id_stmt(false), 0);
809 assert!(!local.contains("BYNK_TEST_RUN_ID"));
810 assert!(local.contains("\"local\""));
811 }
812}