1use crate::emsg;
24use serde::Serialize;
25
26#[derive(Debug, PartialEq, Serialize)]
28pub struct TestRun {
29 pub passed: u32,
30 pub failed: u32,
31 #[serde(skip_serializing_if = "is_zero")]
34 pub skipped: u32,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub suites: Option<Vec<Suite>>,
37 #[serde(skip_serializing_if = "Option::is_none")]
38 pub error: Option<TestError>,
39 #[serde(skip_serializing_if = "Option::is_none")]
43 pub coverage: Option<Coverage>,
44 #[serde(skip_serializing_if = "Option::is_none")]
48 pub transport: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
53 pub snapshots: Option<crate::snapshots::Counts>,
54 #[serde(skip_serializing_if = "Option::is_none")]
58 pub eval: Option<EvalValue>,
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize)]
64pub struct EvalValue {
65 #[serde(skip_serializing_if = "Option::is_none")]
67 pub value: Option<serde_json::Value>,
68 #[serde(rename = "type")]
69 pub ty: String,
70}
71
72fn is_zero(n: &u32) -> bool {
73 *n == 0
74}
75
76#[derive(Debug, PartialEq, Serialize)]
81pub struct Coverage {
82 pub covered: u32,
84 pub lines: u32,
86 pub percent: u32,
88 pub files: Vec<FileCoverage>,
89}
90
91#[derive(Debug, PartialEq, Serialize)]
93pub struct FileCoverage {
94 pub path: String,
95 pub covered: u32,
96 pub lines: u32,
97 pub percent: u32,
98 pub uncovered: Vec<u32>,
100 pub covered_lines: Vec<u32>,
105}
106
107impl From<&crate::coverage::CoverageReport> for Coverage {
108 fn from(r: &crate::coverage::CoverageReport) -> Self {
109 Coverage {
110 covered: r.total_covered(),
111 lines: r.total_lines(),
112 percent: r.total_percent(),
113 files: r
114 .files
115 .iter()
116 .map(|f| FileCoverage {
117 path: f.path.clone(),
118 covered: f.covered,
119 lines: f.total,
120 percent: crate::coverage::percent(f.covered, f.total),
121 uncovered: f.uncovered.clone(),
122 covered_lines: f.covered_lines.clone(),
123 })
124 .collect(),
125 }
126 }
127}
128
129#[derive(Debug, PartialEq, Serialize)]
130pub struct Suite {
131 pub name: String,
132 pub kind: String,
133 pub cases: Vec<Case>,
134}
135
136#[derive(Debug, PartialEq, Serialize)]
137pub struct Case {
138 pub name: String,
139 pub outcome: String,
143 #[serde(skip_serializing_if = "Option::is_none")]
144 pub message: Option<String>,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 pub location: Option<Location>,
147 #[serde(skip_serializing_if = "Option::is_none")]
150 pub retries: Option<u32>,
151 #[serde(skip_serializing_if = "Option::is_none")]
156 pub detached_failures: Option<u32>,
157 #[serde(skip_serializing_if = "Option::is_none")]
162 pub tier: Option<String>,
163 #[serde(skip_serializing_if = "Option::is_none")]
168 pub kind: Option<String>,
169 #[serde(skip_serializing_if = "Option::is_none")]
172 pub seed: Option<String>,
173 #[serde(skip_serializing_if = "Option::is_none")]
176 pub counterexample: Option<String>,
177 #[serde(skip_serializing_if = "Option::is_none")]
180 pub violation: Option<Violation>,
181 #[serde(skip_serializing_if = "Option::is_none")]
186 pub refusals: Option<Vec<Refusal>>,
187 #[serde(skip_serializing_if = "Option::is_none")]
192 pub origin: Option<String>,
193 #[serde(skip_serializing_if = "Option::is_none")]
197 pub warnings: Option<Vec<Warning>>,
198 #[serde(skip)]
202 pub duration_ms: Option<f64>,
203}
204
205#[derive(Debug, Clone, PartialEq, Serialize)]
209pub struct Warning {
210 pub code: String,
211 pub route: String,
213 pub status: u16,
215 pub declared: Vec<u16>,
217 pub message: String,
219}
220
221impl Warning {
222 pub(crate) fn from_event(value: &serde_json::Value) -> Option<Warning> {
225 Some(Warning {
226 code: value.get("code")?.as_str()?.to_string(),
227 route: value.get("route")?.as_str()?.to_string(),
228 status: u16::try_from(value.get("status")?.as_u64()?).ok()?,
229 declared: value
230 .get("declared")?
231 .as_array()?
232 .iter()
233 .filter_map(|n| u16::try_from(n.as_u64()?).ok())
234 .collect(),
235 message: value.get("message")?.as_str()?.to_string(),
236 })
237 }
238
239 pub fn line(&self, program: &str) -> String {
241 format!("{program} test: warning[{}]: {}", self.code, self.message)
242 }
243}
244
245#[derive(Debug, PartialEq, Serialize)]
246pub struct Location {
247 pub path: String,
248 pub line: u32,
249 pub col: u32,
250}
251
252#[derive(Debug, PartialEq, Serialize)]
256pub struct Violation {
257 pub kind: String,
258 pub agent: String,
259 pub name: String,
260 pub location: Option<Location>,
261}
262
263#[derive(Debug, PartialEq, Serialize)]
267pub struct Refusal {
268 pub index: u32,
269 pub call: String,
270 pub kind: String,
271 pub agent: String,
272 pub name: String,
273 pub location: Option<Location>,
274}
275
276#[derive(Debug, PartialEq, Serialize)]
277pub struct TestError {
278 pub kind: String,
279 #[serde(skip_serializing_if = "Option::is_none")]
280 pub message: Option<String>,
281 #[serde(skip_serializing_if = "Vec::is_empty")]
284 pub diagnostics: Vec<String>,
285 #[serde(skip_serializing_if = "Option::is_none")]
287 pub stderr: Option<String>,
288}
289
290impl TestRun {
291 pub fn empty() -> Self {
293 TestRun {
294 passed: 0,
295 failed: 0,
296 skipped: 0,
297 suites: Some(Vec::new()),
298 error: None,
299 coverage: None,
300 transport: None,
301 snapshots: None,
302 eval: None,
303 }
304 }
305
306 pub fn with_coverage(mut self, report: &crate::coverage::CoverageReport) -> Self {
311 if !report.is_empty() {
312 self.coverage = Some(Coverage::from(report));
313 }
314 self
315 }
316
317 pub fn discovered(suites: Vec<Suite>) -> Self {
324 TestRun {
325 passed: 0,
326 failed: 0,
327 skipped: 0,
328 suites: Some(suites),
329 error: None,
330 coverage: None,
331 transport: None,
332 snapshots: None,
333 eval: None,
334 }
335 }
336
337 pub fn runtime_error(message: impl Into<String>, stderr: Option<String>) -> Self {
342 TestRun {
343 passed: 0,
344 failed: 0,
345 skipped: 0,
346 suites: None,
347 error: Some(TestError {
348 kind: "runtime".to_string(),
349 message: Some(message.into()),
350 diagnostics: Vec::new(),
351 stderr: stderr.filter(|s| !s.trim().is_empty()),
352 }),
353 coverage: None,
354 transport: None,
355 snapshots: None,
356 eval: None,
357 }
358 }
359
360 pub fn codegen_error(diagnostics: Vec<String>, tsc_output: String) -> Self {
363 let mut run = Self::compile_error(diagnostics);
364 if let Some(e) = run.error.as_mut() {
365 e.stderr = Some(tsc_output).filter(|s| !s.trim().is_empty());
366 }
367 run
368 }
369
370 pub fn timeout_error(message: impl Into<String>) -> Self {
373 let mut run = Self::runtime_error(message, None);
374 if let Some(error) = run.error.as_mut() {
375 error.kind = "timeout".to_string();
376 }
377 run
378 }
379
380 pub fn no_tests_error(message: impl Into<String>) -> Self {
382 let mut run = Self::runtime_error(message, None);
383 if let Some(error) = run.error.as_mut() {
384 error.kind = "no_tests".to_string();
385 }
386 run
387 }
388
389 pub fn compile_error(diagnostics: Vec<String>) -> Self {
391 TestRun {
392 passed: 0,
393 failed: 0,
394 skipped: 0,
395 suites: None,
396 error: Some(TestError {
397 kind: "compile".to_string(),
398 message: None,
399 diagnostics,
400 stderr: None,
401 }),
402 coverage: None,
403 transport: None,
404 snapshots: None,
405 eval: None,
406 }
407 }
408
409 pub fn with_snapshots(mut self, counts: Option<crate::snapshots::Counts>) -> Self {
414 self.snapshots = counts;
415 self
416 }
417
418 pub fn with_tiers(mut self, discovered: &[crate::project::DiscoveredSuite]) -> Self {
419 for suite in self.suites.iter_mut().flatten() {
420 let Some(known) = discovered.iter().find(|d| d.name == suite.name) else {
421 continue;
422 };
423 for case in &mut suite.cases {
424 let known_case = known.cases.iter().find(|c| c.name == case.name);
425 if let Some(tier) = known_case.and_then(|c| c.tier) {
426 case.tier = Some(tier.to_string());
427 }
428 if known_case.is_some_and(|c| c.doc) {
429 case.origin = Some("doc".to_string());
430 }
431 }
432 }
433 self
434 }
435
436 pub fn with_remote(mut self, transport: String, skipped: &[(String, String, String)]) -> Self {
440 self.transport = Some(transport);
441 self.with_skips(skipped)
442 }
443
444 pub fn warnings(&self) -> impl Iterator<Item = &Warning> {
446 self.suites
447 .iter()
448 .flatten()
449 .flat_map(|s| &s.cases)
450 .flat_map(|c| c.warnings.iter().flatten())
451 }
452
453 pub fn with_skips(mut self, skipped: &[(String, String, String)]) -> Self {
456 if skipped.is_empty() {
457 return self;
458 }
459 self.skipped = u32::try_from(skipped.len()).unwrap_or(u32::MAX);
460 let suites = self.suites.get_or_insert_with(Vec::new);
461 for (suite, case, reason) in skipped {
462 let case = Case {
463 name: case.clone(),
464 outcome: "skipped".to_string(),
465 message: Some(reason.clone()),
466 location: None,
467 retries: None,
468 detached_failures: None,
469 tier: Some("system".to_string()),
471 kind: None,
472 seed: None,
473 counterexample: None,
474 violation: None,
475 refusals: None,
476 origin: None,
477 warnings: None,
478 duration_ms: None,
479 };
480 match suites.iter_mut().find(|s| &s.name == suite) {
481 Some(s) => s.cases.push(case),
482 None => suites.push(Suite {
483 name: suite.clone(),
484 kind: "integration".to_string(),
485 cases: vec![case],
486 }),
487 }
488 }
489 self
490 }
491
492 pub fn render(&self) -> String {
495 let mut s = serde_json::to_string_pretty(self).expect("TestRun serialises");
496 s.push('\n');
497 s
498 }
499}
500
501#[derive(Debug, Default, Clone, PartialEq, Eq)]
505pub struct Unmatched {
506 pub suites: Vec<String>,
507 pub cases: Vec<String>,
508}
509
510impl Unmatched {
511 pub fn is_empty(&self) -> bool {
512 self.suites.is_empty() && self.cases.is_empty()
513 }
514
515 pub fn messages(&self) -> Vec<String> {
517 let suites = self
518 .suites
519 .iter()
520 .map(|s| format!("no suite named --suite {s:?}"));
521 let cases = self
522 .cases
523 .iter()
524 .map(|c| format!("no case matched --case {c:?}"));
525 suites.chain(cases).collect()
526 }
527
528 pub fn report(&self, program: &str) {
531 for message in self.messages() {
532 emsg!("{program} test: error: {message}");
533 }
534 }
535}
536
537#[derive(Debug, Default, PartialEq)]
541pub struct ParsedRun {
542 pub passed: u32,
543 pub failed: u32,
544 pub suites: Vec<Suite>,
545 pub complete: bool,
546 pub unmatched: Unmatched,
548 pub snapshots: Option<crate::snapshots::Report>,
550 pub eval: Option<EvalValue>,
552}
553
554impl ParsedRun {
555 pub fn into_document(self, stderr: &str) -> TestRun {
560 if self.complete {
561 TestRun {
562 passed: self.passed,
563 failed: self.failed,
564 skipped: 0,
565 suites: Some(self.suites),
566 error: None,
567 coverage: None,
568 transport: None,
569 snapshots: None,
570 eval: self.eval,
571 }
572 } else {
573 let trimmed = stderr.trim();
574 TestRun {
575 passed: self.passed,
576 failed: self.failed,
577 skipped: 0,
578 suites: Some(self.suites),
579 error: Some(TestError {
580 kind: "runtime".to_string(),
581 message: Some("the test runner exited before completing".to_string()),
582 diagnostics: Vec::new(),
583 stderr: (!trimmed.is_empty()).then(|| trimmed.to_string()),
584 }),
585 coverage: None,
586 transport: None,
587 snapshots: None,
588 eval: None,
589 }
590 }
591 }
592}
593
594pub fn parse_ndjson(stdout: &str) -> ParsedRun {
598 let mut run = ParsedRun::default();
599 let mut pending: Vec<Warning> = Vec::new();
603 for line in stdout.lines() {
604 let line = line.trim();
605 if line.is_empty() {
606 continue;
607 }
608 let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
609 continue;
610 };
611 match value.get("type").and_then(|t| t.as_str()) {
612 Some("suite-begin") => {
613 run.suites.push(Suite {
614 name: str_field(&value, "name"),
615 kind: str_field(&value, "kind"),
616 cases: Vec::new(),
617 });
618 }
619 Some("warning") => pending.extend(Warning::from_event(&value)),
620 Some("case") => {
621 let mut case = case_from_event(&value);
622 case.warnings = (!pending.is_empty()).then(|| std::mem::take(&mut pending));
623 if case.outcome == "pass" {
624 run.passed += 1;
625 } else {
626 run.failed += 1;
627 }
628 if let Some(suite) = run.suites.last_mut() {
629 suite.cases.push(case);
630 }
631 }
632 Some("eval-value") => {
633 run.eval = Some(EvalValue {
634 value: value.get("value").cloned(),
635 ty: str_field(&value, "valueType"),
636 });
637 }
638 Some("snapshots") => {
639 run.snapshots = value
640 .get("files")
641 .map(crate::snapshots::Report::from_files_value);
642 }
643 Some("run-end") => {
644 run.complete = true;
645 run.unmatched = unmatched_from_event(&value);
646 }
647 _ => {}
648 }
649 }
650 run
651}
652
653pub(crate) fn case_from_event(value: &serde_json::Value) -> Case {
656 let message = value
657 .get("message")
658 .and_then(|m| m.as_str())
659 .map(str::to_string);
660 let location = value
661 .get("location")
662 .and_then(|l| l.as_str())
663 .and_then(parse_location);
664 let retries = value
665 .get("retries")
666 .and_then(serde_json::Value::as_u64)
667 .filter(|n| *n > 0)
668 .map(|n| u32::try_from(n).unwrap_or(u32::MAX));
669 let detached_failures = value
670 .get("detached_failures")
671 .and_then(serde_json::Value::as_u64)
672 .filter(|n| *n > 0)
673 .map(|n| u32::try_from(n).unwrap_or(u32::MAX));
674 let violation = value.get("violation").map(violation_from_json);
675 let refusals = refusals_from_json(value.get("refusals"));
676 Case {
677 name: str_field(value, "name"),
678 outcome: str_field(value, "outcome"),
679 message,
680 location,
681 retries,
682 detached_failures,
683 tier: None,
684 kind: str_opt(value, "kind"),
685 seed: str_opt(value, "seed"),
686 counterexample: str_opt(value, "counterexample"),
687 violation,
688 refusals,
689 origin: None,
690 warnings: None,
691 duration_ms: value.get("durationMs").and_then(serde_json::Value::as_f64),
692 }
693}
694
695fn location_from_json(value: &serde_json::Value) -> Option<Location> {
698 value.get("location").and_then(|l| match l {
699 serde_json::Value::String(s) => parse_location(s),
700 serde_json::Value::Object(_) => Some(Location {
701 path: str_field(l, "path"),
702 line: l
703 .get("line")
704 .and_then(serde_json::Value::as_u64)
705 .unwrap_or(0) as u32,
706 col: l
707 .get("col")
708 .and_then(serde_json::Value::as_u64)
709 .unwrap_or(0) as u32,
710 }),
711 _ => None,
712 })
713}
714
715pub(crate) fn violation_from_json(value: &serde_json::Value) -> Violation {
717 Violation {
718 kind: str_field(value, "kind"),
719 agent: str_field(value, "agent"),
720 name: str_field(value, "name"),
721 location: location_from_json(value),
722 }
723}
724
725pub(crate) fn warnings_from_json(value: Option<&serde_json::Value>) -> Option<Vec<Warning>> {
728 let warnings: Vec<Warning> = value?
729 .as_array()?
730 .iter()
731 .filter_map(Warning::from_event)
732 .collect();
733 (!warnings.is_empty()).then_some(warnings)
734}
735
736pub(crate) fn refusals_from_json(value: Option<&serde_json::Value>) -> Option<Vec<Refusal>> {
739 let refusals: Vec<Refusal> = value?
740 .as_array()?
741 .iter()
742 .filter_map(|r| {
743 Some(Refusal {
744 index: u32::try_from(r.get("index")?.as_u64()?).ok()?,
745 call: r.get("call")?.as_str()?.to_string(),
746 kind: r.get("kind")?.as_str()?.to_string(),
747 agent: r.get("agent")?.as_str()?.to_string(),
748 name: r.get("name")?.as_str()?.to_string(),
749 location: location_from_json(r),
750 })
751 })
752 .collect();
753 (!refusals.is_empty()).then_some(refusals)
754}
755
756pub(crate) fn unmatched_from_event(value: &serde_json::Value) -> Unmatched {
758 let Some(unmatched) = value.get("unmatched") else {
759 return Unmatched::default();
760 };
761 let strings = |key: &str| -> Vec<String> {
762 unmatched
763 .get(key)
764 .and_then(|v| v.as_array())
765 .map(|a| {
766 a.iter()
767 .filter_map(|v| v.as_str())
768 .map(str::to_string)
769 .collect()
770 })
771 .unwrap_or_default()
772 };
773 Unmatched {
774 suites: strings("suites"),
775 cases: strings("cases"),
776 }
777}
778
779fn str_opt(value: &serde_json::Value, key: &str) -> Option<String> {
780 value.get(key).and_then(|v| v.as_str()).map(str::to_string)
781}
782
783fn str_field(value: &serde_json::Value, key: &str) -> String {
784 value
785 .get(key)
786 .and_then(|v| v.as_str())
787 .unwrap_or_default()
788 .to_string()
789}
790
791fn parse_location(s: &str) -> Option<Location> {
796 let (rest, col) = s.rsplit_once(':')?;
797 let (path, line) = rest.rsplit_once(':')?;
798 let line: u32 = line.parse().ok()?;
799 let col: u32 = col.parse().ok()?;
800 if path.is_empty() {
801 return None;
802 }
803 Some(Location {
804 path: path.to_string(),
805 line,
806 col,
807 })
808}
809
810#[cfg(test)]
811mod tests {
812 use super::*;
813
814 #[test]
815 fn a_warning_event_belongs_to_the_case_that_follows_it() {
816 let stream = concat!(
817 r#"{"type":"suite-begin","name":"s","kind":"integration","tests":2}"#,
818 "\n",
819 r#"{"type":"warning","code":"bynk.test.smoke_undeclared_status","route":"GET /a","status":409,"declared":[200,404],"message":"m"}"#,
820 "\n",
821 r#"{"type":"case","suite":"s","name":"one","outcome":"pass"}"#,
822 "\n",
823 r#"{"type":"case","suite":"s","name":"two","outcome":"pass"}"#,
824 "\n",
825 r#"{"type":"run-end","passed":2,"failed":0}"#,
826 "\n",
827 );
828 let run = parse_ndjson(stream);
829 assert_eq!((run.passed, run.failed), (2, 0));
831 let cases = &run.suites[0].cases;
832 let warning = &cases[0].warnings.as_ref().expect("the first case warns")[0];
833 assert_eq!(warning.code, "bynk.test.smoke_undeclared_status");
834 assert_eq!(warning.route, "GET /a");
835 assert_eq!(warning.status, 409);
836 assert_eq!(warning.declared, vec![200, 404]);
837 assert_eq!(cases[1].warnings, None);
838 let doc = run.into_document("").render();
839 assert!(
840 doc.contains(r#""warnings": ["#) && doc.matches("warnings").count() == 1,
841 "{doc}"
842 );
843 }
844
845 fn known(
846 suite: &str,
847 cases: &[(&str, Option<&'static str>)],
848 ) -> crate::project::DiscoveredSuite {
849 crate::project::DiscoveredSuite {
850 name: suite.to_string(),
851 kind: "unit",
852 cases: cases
853 .iter()
854 .map(|(name, tier)| crate::project::DiscoveredCase {
855 name: (*name).to_string(),
856 location: None,
857 tier: *tier,
858 generative: None,
859 doc: false,
860 })
861 .collect(),
862 skipped: Vec::new(),
863 envs: Vec::new(),
864 }
865 }
866
867 #[test]
870 fn a_cases_duration_is_read_but_never_written_to_the_document() {
871 let ndjson = concat!(
872 r#"{"type":"suite-begin","name":"s","kind":"unit","tests":1}"#,
873 "\n",
874 r#"{"type":"case","suite":"s","name":"c","outcome":"pass","durationMs":1.5}"#,
875 "\n",
876 r#"{"type":"suite-end","name":"s"}"#,
877 "\n",
878 r#"{"type":"run-end","passed":1,"failed":0}"#,
879 "\n",
880 );
881 let parsed = parse_ndjson(ndjson);
882 assert_eq!(parsed.suites[0].cases[0].duration_ms, Some(1.5));
883 let rendered = parsed.into_document("").render();
884 assert!(!rendered.contains("durationMs"), "{rendered}");
885 }
886
887 #[test]
890 fn a_cases_detached_failures_are_kept_and_zero_is_dropped() {
891 let ndjson = concat!(
892 r#"{"type":"suite-begin","name":"s","kind":"unit","tests":2}"#,
893 "\n",
894 r#"{"type":"case","suite":"s","name":"a","outcome":"pass","detached_failures":2}"#,
895 "\n",
896 r#"{"type":"case","suite":"s","name":"b","outcome":"pass","detached_failures":0}"#,
897 "\n",
898 r#"{"type":"suite-end","name":"s"}"#,
899 "\n",
900 r#"{"type":"run-end","passed":2,"failed":0}"#,
901 "\n",
902 );
903 let parsed = parse_ndjson(ndjson);
904 assert_eq!(parsed.suites[0].cases[0].detached_failures, Some(2));
905 assert_eq!(parsed.suites[0].cases[1].detached_failures, None);
906 let rendered = parsed.into_document("").render();
907 assert!(rendered.contains("\"detached_failures\": 2"), "{rendered}");
908 assert_eq!(
909 rendered.matches("detached_failures").count(),
910 1,
911 "{rendered}"
912 );
913 }
914
915 #[test]
918 fn run_end_reports_the_values_a_filter_selected_nothing_for() {
919 let ended = parse_ndjson(concat!(
920 r#"{"type":"run-begin","suites":0}"#,
921 "\n",
922 r#"{"type":"run-end","passed":0,"failed":0,"unmatched":{"suites":["nope"],"cases":["typo","other"]}}"#,
923 "\n",
924 ));
925 assert!(ended.complete);
926 assert_eq!(ended.unmatched.suites, vec!["nope".to_string()]);
927 assert_eq!(
928 ended.unmatched.cases,
929 vec!["typo".to_string(), "other".to_string()]
930 );
931 assert_eq!(
932 ended.unmatched.messages(),
933 vec![
934 "no suite named --suite \"nope\"".to_string(),
935 "no case matched --case \"typo\"".to_string(),
936 "no case matched --case \"other\"".to_string(),
937 ]
938 );
939
940 let plain = parse_ndjson(r#"{"type":"run-end","passed":1,"failed":0}"#);
941 assert!(plain.unmatched.is_empty());
942 }
943
944 #[test]
949 fn a_run_takes_each_cases_tier_from_the_case_table() {
950 let ndjson = concat!(
951 r#"{"type":"suite-begin","name":"shop","kind":"unit"}"#,
952 "\n",
953 r#"{"type":"case","name":"wired","outcome":"pass"}"#,
954 "\n",
955 r#"{"type":"case","name":"plain","outcome":"fail","message":"no"}"#,
956 "\n",
957 r#"{"type":"case","name":"a property","outcome":"pass"}"#,
958 "\n",
959 r#"{"type":"case","name":"unlisted","outcome":"pass"}"#,
960 "\n",
961 r#"{"type":"suite-begin","name":"other","kind":"unit"}"#,
962 "\n",
963 r#"{"type":"case","name":"wired","outcome":"pass"}"#,
964 "\n",
965 r#"{"type":"run-end"}"#,
966 "\n",
967 );
968 let table = [
969 known(
970 "shop",
971 &[
972 ("wired", Some("system")),
973 ("plain", Some("unit")),
974 ("a property", None),
975 ],
976 ),
977 known("other", &[("wired", Some("integration"))]),
978 ];
979 let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
980 let suites = doc.suites.unwrap();
981 let tiers = |i: usize| -> Vec<Option<String>> {
982 suites[i].cases.iter().map(|c| c.tier.clone()).collect()
983 };
984 assert_eq!(
985 tiers(0),
986 [Some("system".into()), Some("unit".into()), None, None]
987 );
988 assert_eq!(
989 tiers(1),
990 [Some("integration".into())],
991 "the same name in another suite"
992 );
993 }
994
995 #[test]
998 fn file_coverage_carries_covered_and_uncovered_lines() {
999 let report = crate::coverage::CoverageReport {
1000 files: vec![crate::coverage::FileCoverage {
1001 path: "src/demo/m.bynk".into(),
1002 covered: 2,
1003 total: 5,
1004 uncovered: vec![7, 8, 9],
1005 covered_lines: vec![3, 4],
1006 }],
1007 };
1008 assert_eq!(
1009 serde_json::to_string(&Coverage::from(&report)).unwrap(),
1010 r#"{"covered":2,"lines":5,"percent":40,"files":[{"path":"src/demo/m.bynk","covered":2,"lines":5,"percent":40,"uncovered":[7,8,9],"covered_lines":[3,4]}]}"#
1011 );
1012 }
1013
1014 #[test]
1015 fn refusals_read_in_either_shape_and_drop_what_is_malformed() {
1016 let refusal = |location: &str| {
1017 format!(
1018 r#"{{"index":1,"call":"Spend","kind":"transition","agent":"Wallet","name":"never_decreases","location":{location}}}"#
1019 )
1020 };
1021 let as_event = refusals_from_json(
1022 serde_json::from_str(&format!(
1023 r#"[{}]"#,
1024 refusal(r#""src/demo/wallet.bynk:18:14""#)
1025 ))
1026 .ok()
1027 .as_ref(),
1028 )
1029 .unwrap();
1030 let as_document = refusals_from_json(
1031 serde_json::from_str(&format!(
1032 r#"[{}]"#,
1033 refusal(r#"{"path":"src/demo/wallet.bynk","line":18,"col":14}"#)
1034 ))
1035 .ok()
1036 .as_ref(),
1037 )
1038 .unwrap();
1039 assert_eq!(as_event, as_document);
1040 assert_eq!(as_event[0].index, 1);
1041 assert_eq!(as_event[0].kind, "transition");
1042 assert_eq!(as_event[0].location.as_ref().unwrap().line, 18);
1043
1044 let malformed: serde_json::Value =
1046 serde_json::from_str(r#"[{"index":0,"call":"Spend","kind":"invariant"}]"#).unwrap();
1047 assert_eq!(refusals_from_json(Some(&malformed)), None);
1048 assert_eq!(refusals_from_json(Some(&serde_json::json!([]))), None);
1049 assert_eq!(refusals_from_json(Some(&serde_json::json!("x"))), None);
1050 assert_eq!(refusals_from_json(None), None);
1051 }
1052
1053 #[test]
1054 fn a_violation_reads_its_location_in_either_shape() {
1055 let as_event = serde_json::json!({
1058 "kind": "transition", "agent": "Meter", "name": "same",
1059 "location": "src/demo/m.bynk:28:14"
1060 });
1061 let as_document = serde_json::json!({
1062 "kind": "transition", "agent": "Meter", "name": "same",
1063 "location": { "path": "src/demo/m.bynk", "line": 28, "col": 14 }
1064 });
1065 let expected = Some(Location {
1066 path: "src/demo/m.bynk".to_string(),
1067 line: 28,
1068 col: 14,
1069 });
1070 assert_eq!(violation_from_json(&as_event).location, expected);
1071 assert_eq!(violation_from_json(&as_document).location, expected);
1072 }
1073
1074 #[test]
1075 fn a_doc_example_case_is_marked_and_no_other_is() {
1076 let table = vec![crate::project::DiscoveredSuite {
1077 name: "demo.m".to_string(),
1078 kind: "unit",
1079 cases: vec![
1080 crate::project::DiscoveredCase {
1081 name: "doc example m.bynk:4".to_string(),
1082 location: None,
1083 tier: Some("unit"),
1084 generative: None,
1085 doc: true,
1086 },
1087 crate::project::DiscoveredCase {
1088 name: "real".to_string(),
1089 location: None,
1090 tier: Some("unit"),
1091 generative: None,
1092 doc: false,
1093 },
1094 ],
1095 skipped: Vec::new(),
1096 envs: Vec::new(),
1097 }];
1098 let ndjson = concat!(
1099 r#"{"type":"suite-begin","name":"demo.m","kind":"unit","tests":2}"#,
1100 "\n",
1101 r#"{"type":"case","suite":"demo.m","name":"doc example m.bynk:4","outcome":"pass"}"#,
1102 "\n",
1103 r#"{"type":"case","suite":"demo.m","name":"real","outcome":"pass"}"#,
1104 "\n",
1105 r#"{"type":"suite-end","name":"demo.m"}"#,
1106 "\n",
1107 r#"{"type":"run-end","passed":2,"failed":0}"#,
1108 "\n",
1109 );
1110 let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
1111 let rendered = doc.render();
1112 assert_eq!(rendered.matches("\"origin\"").count(), 1, "{rendered}");
1114 assert!(rendered.contains("\"origin\": \"doc\""), "{rendered}");
1115 let suites = doc.suites.as_ref().unwrap();
1116 assert_eq!(suites[0].cases[0].origin.as_deref(), Some("doc"));
1117 assert_eq!(suites[0].cases[1].origin, None);
1118 }
1119}