Skip to main content

bynk_driver/
smoke.rs

1//! `bynk test --smoke` (#2658): a `system` suite per context, derived from its
2//! `from http` services, so every declared route is exercised on a real
3//! runtime without a test written for it.
4//!
5//! Each route gets up to three cases, all in existing test surface:
6//!
7//! 1. **answers** — a typed call with every argument fabricated by `Val`, under
8//!    a fabricated principal; it passes unless the answer is a 5xx. A smoke
9//!    input is valid by construction, so a server error is the defect a smoke
10//!    exists to find, even one the handler constructs itself.
11//! 2. **rejects a malformed body** (a route with a JSON `body`) — the same call
12//!    with `Wire("{not json")` as the body, which the boundary must refuse. A
13//!    service with `on rejected` renders that refusal itself, as a `400` the
14//!    harness reads as `Handled(BadRequest(_))`.
15//! 3. **refuses no credential** (a route whose principal is not public) — the
16//!    same call `by Nobody`, which the auth seam must refuse.
17//!
18//! The synthesised suites are added to the build's source overlay, beside the
19//! context file they test, as the doc-example suites are (#2461), and the
20//! project's own suites are left out: a smoke run runs only the smoke. Whether a
21//! case can be built is decided by checking it: a case whose check reports one
22//! of the codes in `SKIPPABLE` (a `Matches` type `Val` cannot fabricate, a
23//! principal it cannot construct) is dropped and reported as skipped, with the
24//! checker's reason. Any other diagnostic in a synthesised suite is a bug in
25//! this module, never a skip, so a run cannot pass green by skipping everything.
26
27use crate::emsg;
28use std::collections::HashMap;
29use std::path::{Path, PathBuf};
30
31use crate::project::AttributedError;
32use bynk_model::{IrHandlerKind, IrHttpMethod, lower_handler_kind_ir};
33use bynk_syntax::ast::{
34    ActorDecl, CommonsItem, Context, Handler, ServiceDecl, ServiceProtocol, SourceUnit,
35};
36use bynk_syntax::lexer::tokenize;
37use bynk_syntax::parser::parse_unit_with_recovery;
38
39/// The tail of a synthesised suite's file name: `<stem>.smoke.bynk` beside the
40/// context's `<stem>.bynk`.
41pub const SYNTHETIC_SUFFIX: &str = crate::project::SMOKE_SUITE_SUFFIX;
42
43/// Every case a smoke suite holds is named with this prefix, so it cannot
44/// collide with a case the author wrote.
45pub const CASE_PREFIX: &str = "smoke: ";
46
47/// The diagnostics that make a case un-buildable rather than wrong: the case is
48/// skipped with the checker's message as its reason. A code ending in `*`
49/// matches by prefix.
50const SKIPPABLE: &[&str] = &[
51    // A `String where Matches(…)` has no generator.
52    "bynk.val.needs_pin",
53    "bynk.val.agent_not_generable",
54    // `Val` fabricates only a named type, so a bare base type with no literal
55    // in `bare_literal` (#2706) is skipped, not a failure of the whole run.
56    "bynk.val.unsupported_kind",
57    // A principal the synthesiser could not construct.
58    "bynk.test.actor_identity_required",
59    "bynk.test.actor_no_identity",
60    "bynk.test.principal_identity_mismatch",
61    "bynk.test.principal_required",
62    // A case a run against a real runtime cannot make.
63    "bynk.test.remote_unsupported_*",
64];
65
66/// Which routes a smoke run may call.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum Methods {
69    /// In process, or against a local `bynk dev`: state is disposable.
70    All,
71    /// Against a named target without `--smoke-unsafe`: `GET` only, since a
72    /// fabricated `POST` would write real records to a shared deployment.
73    SafeOnly,
74}
75
76/// A route the smoke run does not call, and why.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Skip {
79    /// The suite it would have been in: the context's dotted name.
80    pub suite: String,
81    pub case: String,
82    /// A diagnostic code, or `smoke` for a route left out by policy.
83    pub code: String,
84    pub reason: String,
85}
86
87/// One synthesised case: its name and its byte range in the suite text.
88#[derive(Debug, Clone)]
89struct Case {
90    name: String,
91    range: std::ops::Range<usize>,
92}
93
94/// One context's synthesised suite.
95#[derive(Debug, Clone)]
96struct Suite {
97    key: PathBuf,
98    context: String,
99    header: String,
100    /// The text of each case, in order.
101    cases: Vec<(Case, String)>,
102}
103
104impl Suite {
105    /// The suite's source, recording each case's byte range.
106    fn render(&mut self) -> String {
107        let mut text = self.header.clone();
108        for (case, body) in &mut self.cases {
109            let start = text.len();
110            text.push_str(body);
111            case.range = start..text.len();
112        }
113        text.push_str("}\n");
114        text
115    }
116}
117
118/// The smoke suites for a project, and what they leave out.
119#[derive(Debug, Clone, Default)]
120pub struct Smoke {
121    suites: Vec<Suite>,
122    skipped: Vec<Skip>,
123    routes: usize,
124}
125
126/// Why a smoke run cannot go ahead.
127pub enum SmokeError {
128    /// A synthesised suite has a diagnostic that is not a skip: a bug here.
129    Synthesis(Vec<AttributedError>),
130    /// The project itself does not check.
131    Project(Vec<AttributedError>),
132}
133
134impl Smoke {
135    /// Synthesise the smoke suites for every `from http` service in `sources`.
136    pub fn collect(sources: &HashMap<PathBuf, String>, methods: Methods) -> Self {
137        let mut keys: Vec<&PathBuf> = sources.keys().collect();
138        keys.sort();
139        let mut contexts: Vec<(&PathBuf, Context)> = Vec::new();
140        let mut actors: HashMap<String, (ActorDecl, String)> = HashMap::new();
141        for key in keys {
142            let source = &sources[key];
143            let Ok(tokens) = tokenize(source) else {
144                continue;
145            };
146            let (unit, errors) = parse_unit_with_recovery(&tokens, source);
147            if !errors.is_empty() {
148                continue;
149            }
150            let items = match &unit {
151                Some(SourceUnit::Context(c)) => &c.items,
152                Some(SourceUnit::Commons(c)) => &c.items,
153                _ => continue,
154            };
155            for item in items {
156                if let CommonsItem::Actor(a) = item {
157                    actors
158                        .entry(a.name.name.clone())
159                        .or_insert_with(|| (a.clone(), source.clone()));
160                }
161            }
162            if let Some(SourceUnit::Context(c)) = unit {
163                contexts.push((key, c));
164            }
165        }
166        let mut smoke = Smoke::default();
167        for (key, context) in contexts {
168            smoke.add_context(sources, key, &context, &actors, methods);
169        }
170        smoke
171    }
172
173    fn add_context(
174        &mut self,
175        sources: &HashMap<PathBuf, String>,
176        key: &Path,
177        context: &Context,
178        actors: &HashMap<String, (ActorDecl, String)>,
179        methods: Methods,
180    ) {
181        let source = &sources[key];
182        let name = context.name.joined();
183        let services: Vec<&ServiceDecl> = context
184            .items
185            .iter()
186            .filter_map(|item| match item {
187                // M-1's domain clause (ADR 0735, #2999 DECISION B): `collect` reads a
188                // recovering parse before `settle` checks the project, so it holds no
189                // `TypedCommons` for `bynk_model::lower_protocol_ir_from_commons`.
190                CommonsItem::Service(s) if matches!(s.protocol, ServiceProtocol::Http) => Some(s),
191                _ => None,
192            })
193            .collect();
194        if services.is_empty() {
195            return;
196        }
197        let stem = key.file_stem().unwrap_or_default().to_string_lossy();
198        let synth = key.with_file_name(format!("{stem}{SYNTHETIC_SUFFIX}"));
199        // A file the project really has is never overwritten.
200        if sources.contains_key(&synth) {
201            return;
202        }
203        let mut suite = Suite {
204            key: synth,
205            context: name.clone(),
206            header: format!(
207                "// Generated by `bynk test --smoke` from the routes of `{name}`.\n\
208                 suite {name} as system {{\n"
209            ),
210            cases: Vec::new(),
211        };
212        let qualify = services.len() > 1;
213        for service in services {
214            let renders_rejections = service
215                .handlers
216                .iter()
217                .any(|h| matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Rejected));
218            for handler in &service.handlers {
219                let IrHandlerKind::Http { method, path } = lower_handler_kind_ir(&handler.kind)
220                else {
221                    continue;
222                };
223                self.routes += 1;
224                let route = if qualify {
225                    format!("{} {} {path}", service.name.name, method.as_str())
226                } else {
227                    format!("{} {path}", method.as_str())
228                };
229                let route = Route {
230                    label: route,
231                    service: &service.name.name,
232                    method,
233                    path: path.clone(),
234                    handler,
235                    source,
236                    renders_rejections,
237                };
238                let principal = principal(handler, service, actors);
239                let cases = route.cases(&principal);
240                if methods == Methods::SafeOnly && method != IrHttpMethod::Get {
241                    // One skip per case the route would have run, so the
242                    // skip list agrees with the run's own count (#3008).
243                    for (case, _) in cases {
244                        self.skipped.push(Skip {
245                            suite: name.clone(),
246                            case: case.name,
247                            code: "smoke".to_string(),
248                            reason: format!(
249                                "a `{}` route writes, so a run against a named target calls only `GET` routes; pass `--smoke-unsafe` to call it",
250                                method.as_str()
251                            ),
252                        });
253                    }
254                    continue;
255                }
256                suite.cases.extend(cases);
257            }
258        }
259        if !suite.cases.is_empty() {
260            self.suites.push(suite);
261        }
262    }
263
264    /// The overlay a smoke run builds: `sources` without the project's own
265    /// suites, plus the synthesised ones.
266    pub fn overlay(&mut self, sources: &HashMap<PathBuf, String>) -> HashMap<PathBuf, String> {
267        let mut out: HashMap<PathBuf, String> = sources
268            .iter()
269            .filter(|(_, text)| !is_suite(text))
270            .map(|(k, v)| (k.clone(), v.clone()))
271            .collect();
272        for suite in &mut self.suites {
273            out.insert(suite.key.clone(), suite.render());
274        }
275        out
276    }
277
278    /// Check the synthesised suites with `check`, dropping every case that
279    /// reports a code in `SKIPPABLE`, until they check clean. Returns the
280    /// overlay to build.
281    pub fn settle(
282        &mut self,
283        sources: &HashMap<PathBuf, String>,
284        check: impl Fn(HashMap<PathBuf, String>) -> Vec<AttributedError>,
285    ) -> Result<HashMap<PathBuf, String>, SmokeError> {
286        loop {
287            let overlay = self.overlay(sources);
288            let errors = check(overlay.clone());
289            if errors.is_empty() {
290                return Ok(overlay);
291            }
292            let (ours, theirs): (Vec<_>, Vec<_>) =
293                errors.into_iter().partition(|e| self.suite_of(e).is_some());
294            if !theirs.is_empty() {
295                return Err(SmokeError::Project(theirs));
296            }
297            let mut unexplained = Vec::new();
298            let mut dropped = false;
299            for error in ours {
300                let suite = self.suite_of(&error).expect("partitioned on it");
301                let start = error.error.span.start;
302                let Some(i) = self.suites[suite]
303                    .cases
304                    .iter()
305                    .position(|(c, _)| c.range.contains(&start))
306                else {
307                    unexplained.push(error);
308                    continue;
309                };
310                if !skippable(error.error.category) {
311                    unexplained.push(error);
312                    continue;
313                }
314                let (case, _) = self.suites[suite].cases.remove(i);
315                self.skipped.push(Skip {
316                    suite: self.suites[suite].context.clone(),
317                    case: case.name,
318                    code: error.error.category.to_string(),
319                    reason: error.error.message.clone(),
320                });
321                dropped = true;
322                // The other errors' ranges are stale until the next render.
323                break;
324            }
325            if !unexplained.is_empty() {
326                return Err(SmokeError::Synthesis(unexplained));
327            }
328            if !dropped {
329                return Ok(overlay);
330            }
331            self.suites.retain(|s| !s.cases.is_empty());
332        }
333    }
334
335    fn suite_of(&self, error: &AttributedError) -> Option<usize> {
336        let path = error.source_path.as_ref()?;
337        self.suites
338            .iter()
339            .position(|s| path == &s.key || s.key.ends_with(path))
340    }
341
342    /// The routes considered, the cases that will run, and the ones skipped.
343    pub fn summary(&self) -> (usize, usize, &[Skip]) {
344        let cases = self.suites.iter().map(|s| s.cases.len()).sum();
345        (self.routes, cases, &self.skipped)
346    }
347
348    /// The synthesised suites as source, for `--print`: each headed by the
349    /// path it would live at, with the skipped cases listed as comments.
350    pub fn print(&mut self, root: &Path) -> String {
351        let mut out = String::new();
352        for suite in &mut self.suites {
353            let path = suite.key.strip_prefix(root).unwrap_or(&suite.key);
354            // `/` on every platform, as every path the CLI shows is (#2999 PR 1:
355            // Windows printed `src\shop\api.smoke.bynk`).
356            let path = path.to_string_lossy().replace('\\', "/");
357            out.push_str(&format!("// {path}\n"));
358            out.push_str(&suite.render());
359            out.push('\n');
360        }
361        for skip in &self.skipped {
362            out.push_str(&format!(
363                "// skipped `{}` case \"{}\" [{}]: {}\n",
364                skip.suite, skip.case, skip.code, skip.reason
365            ));
366        }
367        out
368    }
369}
370
371/// The environment variable that turns on the test runtime's strict decoding
372/// of an answer (`responseToHttpResult`): a smoke case fails on a status the
373/// runtime does not know, or a JSON body that does not decode as the route's
374/// declared type, where an author's own case gets the raw value to judge.
375pub use bynk_project::env_protocol::TEST_STRICT_WIRE as STRICT_WIRE_ENV;
376
377/// #2685: the environment variable `bynk test --smoke` sets for `bynk`, the path of a
378/// file holding a JSON object from each route's key (`<context> <service> <METHOD> <path>`) to the
379/// statuses its handler can answer. `bynk` computes it, since the response set
380/// is walked by `bynk-ide`, which the `bynk` binary does not carry; the test
381/// runtime warns (`bynk.test.smoke_undeclared_status`) when a smoke case gets a
382/// non-5xx answer outside its route's set. Without it, as in a direct `bynk
383/// test --smoke`, a smoke run compares nothing.
384pub use bynk_project::env_protocol::SMOKE_DECLARED_FILE as DECLARED_ENV;
385
386/// #2685: the code of the warning a smoke case carries for an answer its route
387/// does not declare.
388pub const UNDECLARED_STATUS_CODE: &str = "bynk.test.smoke_undeclared_status";
389
390/// A smoke run ready to build: the options with the synthesised suites in place
391/// of the project's own, and the skips to report.
392pub struct Prepared {
393    pub options: crate::project::CompileOptions,
394    pub smoke: Smoke,
395}
396
397/// Synthesise and settle the smoke suites over `options`' sources. `report`
398/// prints what was skipped and the counts; a nested run (one `--against dev`
399/// group) leaves that to the run that started it. On a failure the reason has
400/// been printed and the exit code is returned.
401pub fn prepare(
402    program: &str,
403    options: crate::project::CompileOptions,
404    methods: Methods,
405    json: bool,
406    stream: bool,
407    report: bool,
408) -> Result<Prepared, std::process::ExitCode> {
409    use crate::test_json::TestRun;
410    let fail = |message: String| {
411        if json {
412            crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
413        } else {
414            emsg!("{program} test: error: {message}");
415        }
416        std::process::ExitCode::FAILURE
417    };
418    let Some(sources) = options.sources.clone() else {
419        return Err(fail(
420            "`--smoke` needs a project directory, not a single file".to_string(),
421        ));
422    };
423    let mut smoke = Smoke::collect(&sources, methods);
424    let check = |overlay: HashMap<PathBuf, String>| {
425        crate::project::check_project(&options.clone().sources(overlay)).errors
426    };
427    let overlay = match smoke.settle(&sources, check) {
428        Ok(overlay) => overlay,
429        Err(e) => {
430            let (errors, note) = match e {
431                SmokeError::Project(errors) => (errors, None),
432                SmokeError::Synthesis(errors) => (
433                    errors,
434                    Some(
435                        "a synthesised smoke suite does not check: this is a bug in `--smoke`, please report it at https://github.com/bynk-lang/bynk/issues",
436                    ),
437                ),
438            };
439            let check =
440                crate::project::check_project(&options.clone().sources(smoke.overlay(&sources)));
441            let failure = crate::project::ProjectFailure {
442                errors,
443                snapshots: check.snapshots,
444                display_root: check.display_root,
445            };
446            if json {
447                crate::test_stream::print_run(
448                    stream,
449                    &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
450                );
451            } else {
452                crate::print_project_failure(&failure);
453            }
454            if let Some(note) = note {
455                emsg!("{program} test: error: {note}");
456            }
457            return Err(std::process::ExitCode::FAILURE);
458        }
459    };
460    let (routes, cases, skipped) = smoke.summary();
461    if report {
462        for skip in skipped {
463            eprintln!(
464                "{program} test: skipped `{}` case \"{}\" [{}]: {}",
465                skip.suite, skip.case, skip.code, skip.reason
466            );
467        }
468        eprintln!(
469            "{program} test: smoke: {cases} case{} from {routes} route{}, {} skipped",
470            if cases == 1 { "" } else { "s" },
471            if routes == 1 { "" } else { "s" },
472            skipped.len()
473        );
474    }
475    if cases == 0 {
476        return Err(fail(if routes == 0 {
477            "`--smoke` found no `from http` route to call".to_string()
478        } else {
479            format!("`--smoke` could build no case: all {routes} routes were skipped")
480        }));
481    }
482    Ok(Prepared {
483        options: options.sources(overlay),
484        smoke,
485    })
486}
487
488impl Smoke {
489    /// The skips as `(suite, skip)` pairs, the shape a remote run's take.
490    pub fn remote_skips(&self) -> Vec<(String, crate::project::RemoteSkip)> {
491        self.skipped
492            .iter()
493            .map(|s| {
494                (
495                    s.suite.clone(),
496                    crate::project::RemoteSkip {
497                        case: s.case.clone(),
498                        code: s.code.clone(),
499                        reason: s.reason.clone(),
500                    },
501                )
502            })
503            .collect()
504    }
505}
506
507/// #2706: `Val` refuses a bare base type (`Val[String]` is `bynk.val.unsupported_kind`), so a
508/// plain `String`, `Int` or `Bool` parameter, such as a route's path parameter, is given a
509/// literal instead. A refined or declared type still goes through `Val`.
510fn bare_literal(ty: &str) -> Option<String> {
511    match ty.trim() {
512        "String" => Some(r#""a""#.to_string()),
513        "Int" => Some("1".to_string()),
514        "Bool" => Some("true".to_string()),
515        _ => None,
516    }
517}
518
519fn skippable(code: &str) -> bool {
520    SKIPPABLE.iter().any(|s| match s.strip_suffix('*') {
521        Some(prefix) => code.starts_with(prefix),
522        None => code == *s,
523    })
524}
525
526/// Whether `text` is a test file: a `suite` unit.
527fn is_suite(text: &str) -> bool {
528    let Ok(tokens) = tokenize(text) else {
529        return false;
530    };
531    matches!(
532        parse_unit_with_recovery(&tokens, text).0,
533        Some(SourceUnit::Suite(_))
534    )
535}
536
537/// How a case acts.
538#[derive(Debug, Clone, PartialEq, Eq)]
539struct Principal {
540    /// The `by` clause's text, such as `Visitor` or `User(Val[UserId])`.
541    by: String,
542    /// The route admits an unauthenticated caller, so there is nothing to
543    /// refuse.
544    public: bool,
545}
546
547/// The principal to call `handler` as: a public member of its actor sum if it
548/// has one, else its first actor, with an identity fabricated by `Val`.
549fn principal(
550    handler: &Handler,
551    service: &ServiceDecl,
552    actors: &HashMap<String, (ActorDecl, String)>,
553) -> Principal {
554    let by = handler.by_clause.as_ref().or(service.default_by.as_ref());
555    let names: Vec<&str> = by
556        .map(|b| b.actors.iter().map(|a| a.name.as_str()).collect())
557        .unwrap_or_default();
558    let is_public = |name: &str| {
559        name == "Visitor"
560            || actors
561                .get(name)
562                .is_some_and(|(a, _)| a.auth.as_ref().is_some_and(|s| s.name == "None"))
563    };
564    if let Some(public) = names.iter().find(|n| is_public(n)) {
565        return Principal {
566            by: (*public).to_string(),
567            public: true,
568        };
569    }
570    let Some(first) = names.first() else {
571        return Principal {
572            by: "Visitor".to_string(),
573            public: true,
574        };
575    };
576    // A refinement actor carries its base actor's identity.
577    let base = actors
578        .get(*first)
579        .and_then(|(a, _)| a.refinement.as_ref())
580        .map_or(*first, |r| r.base.name.as_str());
581    let identity = actors.get(base).and_then(|(a, source)| {
582        let ty = a.identity.as_ref()?;
583        let span = ty.span();
584        source.get(span.start..span.end).map(str::to_string)
585    });
586    Principal {
587        by: match identity {
588            Some(ty) => format!("{first}(Val[{ty}])"),
589            None => (*first).to_string(),
590        },
591        public: false,
592    }
593}
594
595/// One route, and the source of the context declaring it.
596struct Route<'a> {
597    label: String,
598    service: &'a str,
599    method: IrHttpMethod,
600    path: String,
601    handler: &'a Handler,
602    source: &'a str,
603    renders_rejections: bool,
604}
605
606impl Route<'_> {
607    fn case_name(&self, what: &str) -> String {
608        format!("{CASE_PREFIX}{} {what}", self.label)
609    }
610
611    fn is_raw(&self) -> bool {
612        self.handler
613            .annotations
614            .iter()
615            .any(|a| a.name.name == "raw")
616    }
617
618    /// Each argument's text, in the handler's parameter order; `body` is
619    /// replaced by `body` when given.
620    fn args(&self, body: Option<&str>) -> Vec<String> {
621        self.handler
622            .params
623            .iter()
624            .map(|p| {
625                if p.name.name == "headers" {
626                    return "RequestHeaders.of([])".to_string();
627                }
628                // #3513 C: `cf` is a record of optionals, so the empty literal is the case.
629                if p.name.name == "cf"
630                    && matches!(&p.type_ref, bynk_syntax::ast::TypeRef::Named(id) if id.name == "RequestCf")
631                {
632                    return "RequestCf {}".to_string();
633                }
634                if matches!(p.type_ref, bynk_syntax::ast::TypeRef::RequestQuery(_)) {
635                    return "RequestQuery.empty()".to_string();
636                }
637                if matches!(p.type_ref, bynk_syntax::ast::TypeRef::RequestCookies(_)) {
638                    return "RequestCookies.empty()".to_string();
639                }
640                if p.name.name == "body"
641                    && let Some(body) = body
642                {
643                    return body.to_string();
644                }
645                let span = p.type_ref.span();
646                let ty = self.source.get(span.start..span.end).unwrap_or("()");
647                bare_literal(ty).unwrap_or_else(|| format!("Val[{ty}]"))
648            })
649            .collect()
650    }
651
652    fn call(&self, args: &[String], by: &str) -> String {
653        let mut all = vec![format!("{:?}", self.path)];
654        all.extend(args.iter().cloned());
655        format!(
656            "{}.{}({}) by {by}",
657            self.service,
658            self.method.as_str(),
659            all.join(", ")
660        )
661    }
662
663    fn cases(&self, principal: &Principal) -> Vec<(Case, String)> {
664        let case = |name: String, call: String, expect: &str| {
665            (
666                Case {
667                    name: name.clone(),
668                    range: 0..0,
669                },
670                format!("  case {name:?} {{\n    let r <- {call}\n    expect {expect}\n  }}\n"),
671            )
672        };
673        let args = self.args(None);
674        let mut out = vec![case(
675            self.case_name("answers"),
676            self.call(&args, &principal.by),
677            "!(r is ServerError(_) || r is NotImplemented(_) || r is BadGateway(_) || r is ServiceUnavailable(_) || r is GatewayTimeout(_))",
678        )];
679        let has_body = self.handler.params.iter().any(|p| p.name.name == "body");
680        if has_body && !self.is_raw() {
681            let expect = if self.renders_rejections {
682                "r is Rejected(_) || r is Handled(BadRequest(_))"
683            } else {
684                "r is Rejected(_)"
685            };
686            out.push(case(
687                self.case_name("rejects a malformed body"),
688                self.call(&self.args(Some("Wire(\"{not json\")")), &principal.by),
689                expect,
690            ));
691        }
692        if !principal.public {
693            out.push(case(
694                self.case_name("refuses no credential"),
695                self.call(&args, "Nobody"),
696                "r is Rejected(Unauthorized)",
697            ));
698        }
699        out
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    #[test]
708    fn bare_literal_covers_string_int_and_bool_only() {
709        assert_eq!(bare_literal("String").as_deref(), Some(r#""a""#));
710        assert_eq!(bare_literal("Int").as_deref(), Some("1"));
711        assert_eq!(bare_literal("Bool").as_deref(), Some("true"));
712        assert_eq!(bare_literal("List[String]"), None);
713        assert_eq!(bare_literal("Sku"), None);
714    }
715
716    fn sources(files: &[(&str, &str)]) -> HashMap<PathBuf, String> {
717        files
718            .iter()
719            .map(|(k, v)| (PathBuf::from(k), v.to_string()))
720            .collect()
721    }
722
723    const SHOP: &str = r#"context shop.api
724
725type UserId = String where NonEmpty
726actor User { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
727type Item = { sku: String where NonEmpty }
728
729service api from http {
730  on GET("/ping") () -> Effect[HttpResult[String]] by v: Visitor {
731    Ok("pong")
732  }
733  on PUT("/cart/:sku") (sku: String, body: Item) -> Effect[HttpResult[Item]] by u: User {
734    Created(body)
735  }
736}
737"#;
738
739    #[test]
740    fn a_route_gets_answers_rejects_and_refuses_cases() {
741        let src = sources(&[("/p/src/shop/api.bynk", SHOP)]);
742        let mut smoke = Smoke::collect(&src, Methods::All);
743        let overlay = smoke.overlay(&src);
744        let text = &overlay[&PathBuf::from("/p/src/shop/api.smoke.bynk")];
745        assert!(text.contains("suite shop.api as system {"), "{text}");
746        assert!(
747            text.contains(r#"let r <- api.GET("/ping") by Visitor"#),
748            "{text}"
749        );
750        assert!(
751            text.contains(r#"api.PUT("/cart/:sku", "a", Val[Item]) by User(Val[UserId])"#),
752            "{text}"
753        );
754        assert!(
755            text.contains(r#"api.PUT("/cart/:sku", "a", Wire("{not json")) by User(Val[UserId])"#),
756            "{text}"
757        );
758        assert!(
759            text.contains(r#"api.PUT("/cart/:sku", "a", Val[Item]) by Nobody"#),
760            "{text}"
761        );
762        // A public route has no credential to refuse, and a GET no body.
763        assert!(!text.contains("smoke: GET /ping refuses"), "{text}");
764        assert!(!text.contains("smoke: GET /ping rejects"), "{text}");
765        assert_eq!(smoke.summary().0, 2);
766        assert_eq!(smoke.summary().1, 4);
767    }
768
769    #[test]
770    fn a_named_target_calls_only_get_routes() {
771        let src = sources(&[("/p/src/shop/api.bynk", SHOP)]);
772        let mut smoke = Smoke::collect(&src, Methods::SafeOnly);
773        let overlay = smoke.overlay(&src);
774        let text = &overlay[&PathBuf::from("/p/src/shop/api.smoke.bynk")];
775        assert!(!text.contains("PUT"), "{text}");
776        let (_, cases, skipped) = smoke.summary();
777        assert_eq!(cases, 1);
778        // Every case the write route would have run is named, not only its
779        // first (#3008).
780        let names: Vec<&str> = skipped.iter().map(|s| s.case.as_str()).collect();
781        let mut all = Smoke::collect(&src, Methods::All);
782        let _ = all.overlay(&src);
783        let (_, run, _) = all.summary();
784        // The skipped cases plus the ones that run are every case there is.
785        assert_eq!(names.len() + cases, run, "{names:?}");
786        assert!(
787            names.contains(&"smoke: PUT /cart/:sku answers"),
788            "{names:?}"
789        );
790        assert!(skipped.iter().all(|s| s.reason.contains("--smoke-unsafe")));
791    }
792
793    #[test]
794    fn the_projects_own_suites_are_left_out() {
795        let src = sources(&[
796            ("/p/src/shop/api.bynk", SHOP),
797            (
798                "/p/tests/api.test.bynk",
799                "suite shop.api {\n  case \"x\" {\n    expect true\n  }\n}\n",
800            ),
801        ]);
802        let mut smoke = Smoke::collect(&src, Methods::All);
803        let overlay = smoke.overlay(&src);
804        assert!(!overlay.contains_key(&PathBuf::from("/p/tests/api.test.bynk")));
805        assert!(overlay.contains_key(&PathBuf::from("/p/src/shop/api.bynk")));
806    }
807
808    #[test]
809    fn a_service_that_renders_rejections_accepts_its_own_400() {
810        let src = sources(&[(
811            "/p/src/a.bynk",
812            r#"context a
813
814type Note = { text: String }
815
816service web from http {
817  on POST("/n") (body: Note) -> Effect[HttpResult[Note]] by v: Visitor {
818    Created(body)
819  }
820  on rejected (r: BoundaryRejection) -> Effect[HttpResult[()]] {
821    BadRequest("no")
822  }
823}
824"#,
825        )]);
826        let mut smoke = Smoke::collect(&src, Methods::All);
827        let text = smoke.overlay(&src)[&PathBuf::from("/p/src/a.smoke.bynk")].clone();
828        assert!(
829            text.contains("expect r is Rejected(_) || r is Handled(BadRequest(_))"),
830            "{text}"
831        );
832    }
833
834    #[test]
835    fn a_refinement_actor_acts_with_its_base_actors_identity() {
836        let src = sources(&[(
837            "/p/src/a.bynk",
838            r#"context a
839
840type UserId = String where NonEmpty
841actor User { auth = Bearer(secret = "S"), identity = UserId }
842actor Admin = User where hasClaim("admin")
843
844service web from http {
845  on GET("/admin") () -> Effect[HttpResult[String]] by a: Admin {
846    Ok("a")
847  }
848}
849"#,
850        )]);
851        let mut smoke = Smoke::collect(&src, Methods::All);
852        let text = smoke.overlay(&src)[&PathBuf::from("/p/src/a.smoke.bynk")].clone();
853        assert!(
854            text.contains(r#"web.GET("/admin") by Admin(Val[UserId])"#),
855            "{text}"
856        );
857        assert!(
858            text.contains("smoke: GET /admin refuses no credential"),
859            "{text}"
860        );
861    }
862
863    #[test]
864    fn two_http_services_in_one_context_name_their_service() {
865        let src = sources(&[(
866            "/p/src/a.bynk",
867            r#"context a
868
869service web from http {
870  on GET("/x") () -> Effect[HttpResult[String]] by v: Visitor {
871    Ok("x")
872  }
873}
874
875service admin from http {
876  on GET("/y") () -> Effect[HttpResult[String]] by v: Visitor {
877    Ok("y")
878  }
879}
880"#,
881        )]);
882        let mut smoke = Smoke::collect(&src, Methods::All);
883        let text = smoke.overlay(&src)[&PathBuf::from("/p/src/a.smoke.bynk")].clone();
884        assert!(
885            text.contains(r#"case "smoke: web GET /x answers""#),
886            "{text}"
887        );
888        assert!(
889            text.contains(r#"case "smoke: admin GET /y answers""#),
890            "{text}"
891        );
892    }
893
894    #[test]
895    fn skippable_codes_match_by_prefix() {
896        assert!(skippable("bynk.val.needs_pin"));
897        assert!(skippable("bynk.test.remote_unsupported_call"));
898        assert!(!skippable("bynk.types.type_mismatch"));
899    }
900}