Skip to main content

bynk_check/
test_env.rs

1//! #2134: a suite's configuration, `env { NAME = "value" … }`.
2//!
3//! A suite or case declares the variables and secrets its participants see.
4//! At `system` each participant's Worker `env` holds them, as Wrangler would
5//! put them there; at `unit`/`integration` they are what the `Secrets` test
6//! double answers. One map applies to every participant, and a case's `env`
7//! layers over its suite's, name by name.
8//!
9//! The checks here are tier-independent: a name given twice at one scope
10//! (`bynk.suite.duplicate_env`) and a value that is neither a `String`
11//! literal nor a `fixture` of the same suite (`bynk.suite.env_not_literal`). The `system`-only binding clash
12//! (`bynk.suite.env_binding_clash`) needs each Worker's binding names, which
13//! the emitter computes, so it is [`check_env_binding_clash`], called from
14//! there with them.
15
16use std::collections::{BTreeMap, HashMap};
17
18use bynk_syntax::ast::{Case, EnvClause, Expr, ExprKind, FixtureDecl, SuiteDecl};
19use bynk_syntax::error::CompileError;
20use bynk_syntax::span::Span;
21
22/// `bynk.suite.duplicate_env` and `bynk.suite.env_not_literal` for one suite
23/// declaration: its own `env` clauses as one scope, and each case's as
24/// another.
25pub fn check_env_clauses(decl: &SuiteDecl, errors: &mut Vec<CompileError>) {
26    check_scope(decl, &decl.envs, "suite", errors);
27    for case in &decl.cases {
28        check_scope(decl, &case.envs, "case", errors);
29    }
30}
31
32/// #2956: what an `env` entry's value is. A `fixture` of the same suite is a
33/// compile-time `String` constant, so it is as static as a literal; its text
34/// stays in the test module once, and the entry refers to it by path.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum EnvValue {
37    /// A `String` literal, verbatim.
38    Literal(String),
39    /// The suite's `fixture` of that normalised path.
40    Fixture(String),
41}
42
43/// The fixture of `decl` that `value` names, when it is a bare name of one.
44fn fixture_named<'a>(decl: &'a SuiteDecl, value: &Expr) -> Option<&'a FixtureDecl> {
45    let ExprKind::Ident(id) = &value.kind else {
46        return None;
47    };
48    decl.fixtures.iter().find(|f| f.name.name == id.name)
49}
50
51/// The [`EnvValue`] of one entry's value, or `None` when it is neither (already
52/// `bynk.suite.env_not_literal`).
53fn env_value(decl: &SuiteDecl, value: &Expr) -> Option<EnvValue> {
54    if let ExprKind::StrLit(v) = &value.kind {
55        return Some(EnvValue::Literal(v.clone()));
56    }
57    fixture_named(decl, value)
58        .map(|f| EnvValue::Fixture(bynk_project::assets::normalise_asset_path(&f.path)))
59}
60
61fn check_scope(decl: &SuiteDecl, envs: &[EnvClause], scope: &str, errors: &mut Vec<CompileError>) {
62    let mut seen: HashMap<&str, Span> = HashMap::new();
63    for entry in envs.iter().flat_map(|e| e.entries.iter()) {
64        let name = entry.name.name.as_str();
65        if let Some(prev) = seen.get(name) {
66            errors.push(
67                CompileError::new(
68                    "bynk.suite.duplicate_env",
69                    entry.name.span,
70                    format!("`{name}` is given more than once in this {scope}'s `env`"),
71                )
72                .with_label(*prev, "first given here")
73                .with_note(
74                    "each name has one value per scope; a case's `env` may override a name its suite gives",
75                ),
76            );
77        } else {
78            seen.insert(name, entry.name.span);
79        }
80        if env_value(decl, &entry.value).is_none() {
81            errors.push(
82                CompileError::new(
83                    "bynk.suite.env_not_literal",
84                    entry.value.span,
85                    format!(
86                        "the value of `{name}` in an `env` clause is not a `String` literal or a fixture of this suite"
87                    ),
88                )
89                .with_note(
90                    "a Worker's variables and secrets are strings, so an `env` entry's value is written as one, `NAME = \"value\"`, or names a `fixture` this suite declares",
91                ),
92            );
93        }
94    }
95}
96
97/// The variables and secrets `case` runs with, as written: its suite's `env`
98/// entries, overlaid by the case's own, name by name. Only a literal or a
99/// fixture of the suite is kept; anything else is already
100/// `bynk.suite.env_not_literal`.
101pub fn case_env_values(decl: &SuiteDecl, case: &Case) -> BTreeMap<String, EnvValue> {
102    let mut env = BTreeMap::new();
103    for envs in [&decl.envs, &case.envs] {
104        for entry in envs.iter().flat_map(|e| e.entries.iter()) {
105            if let Some(v) = env_value(decl, &entry.value) {
106                env.insert(entry.name.name.clone(), v);
107            }
108        }
109    }
110    env
111}
112
113/// [`case_env_values`] with each fixture replaced by its text, from
114/// `fixtures` (each declared file's text by normalised path). A fixture whose
115/// text is not there was refused when it was read, so it is left out.
116pub fn case_env(
117    decl: &SuiteDecl,
118    case: &Case,
119    fixtures: &BTreeMap<String, String>,
120) -> BTreeMap<String, String> {
121    case_env_values(decl, case)
122        .into_iter()
123        .filter_map(|(k, v)| match v {
124            EnvValue::Literal(s) => Some((k, s)),
125            EnvValue::Fixture(path) => fixtures.get(&path).map(|t| (k, t.clone())),
126        })
127        .collect()
128}
129
130/// Whether `decl` gives any `env` entry, at the suite or on a case.
131pub fn has_env(decl: &SuiteDecl) -> bool {
132    !decl.envs.is_empty() || decl.cases.iter().any(|c| !c.envs.is_empty())
133}
134
135/// `bynk.suite.env_binding_clash`: at `system`, an `env` entry lands on each
136/// participant's Worker `env`, so a name one of them already binds (a Service
137/// Binding, KV namespace or Durable Object namespace), or a key the harness
138/// sets there itself (a call edge's key, a foreign caller's secret), is
139/// refused. `bindings` maps each such name to what holds it, as a phrase
140/// ("a binding of `shop.ledger`'s Worker").
141pub fn check_env_binding_clash(
142    decl: &SuiteDecl,
143    bindings: &BTreeMap<String, String>,
144    errors: &mut Vec<CompileError>,
145) {
146    let entries = decl
147        .envs
148        .iter()
149        .chain(decl.cases.iter().flat_map(|c| c.envs.iter()))
150        .flat_map(|e| e.entries.iter());
151    for entry in entries {
152        let name = &entry.name.name;
153        let Some(owner) = bindings.get(name) else {
154            continue;
155        };
156        errors.push(
157            CompileError::new(
158                "bynk.suite.env_binding_clash",
159                entry.name.span,
160                format!("`{name}` is {owner}, so it cannot be given in `env`"),
161            )
162            .with_note(
163                "at `system`, an `env` entry is put on every participant's Worker `env`, where it would clash with what is already there",
164            )
165            .with_note("rename the variable"),
166        );
167    }
168}
169
170/// #2138 (end-to-end testing track §3.7): a case run against a named target.
171/// A deployed target already runs with its own variables, so the runner can't
172/// apply the case's `env`; the case runs only if its `env` and the target's
173/// declared `vars` agree on every name either mentions. Refused
174/// (`bynk.test.remote_unsupported_env`), first match reported:
175/// - an entry naming one of the target's `secrets` — a secret comes from the
176///   environment, never from a suite;
177/// - an entry the target doesn't declare, or declares with another value;
178/// - a declared variable the case doesn't set, which would read as `None` in
179///   process, so the case wouldn't promote unchanged.
180pub fn remote_env_disagreement(
181    case_name: &str,
182    span: Span,
183    env: &BTreeMap<String, String>,
184    vars: &BTreeMap<String, String>,
185    secrets: &[String],
186) -> Option<CompileError> {
187    let refusal = |what: String, note: &str| {
188        Some(
189            CompileError::new(
190                "bynk.test.remote_unsupported_env",
191                span,
192                format!(
193                    "case `\"{case_name}\"` {what}, so it can't run against this target unchanged"
194                ),
195            )
196            .with_note(note.to_string()),
197        )
198    };
199    for (name, value) in env {
200        if secrets.contains(name) {
201            return refusal(
202                format!("sets the secret `{name}` in its `env`"),
203                "against a named target a secret comes from the environment, never from a suite; drop it from the case's `env` for this run",
204            );
205        }
206        match vars.get(name) {
207            None => {
208                return refusal(
209                    format!("sets `{name}` in its `env`, which the target doesn't declare"),
210                    "declare the value the target was deployed with under its `vars`, or run the case in process",
211                );
212            }
213            Some(deployed) if deployed != value => {
214                return refusal(
215                    format!(
216                        "sets `{name} = \"{value}\"`, but the target was deployed with `\"{deployed}\"`"
217                    ),
218                    "a suite written for one configuration must not run against another; run it in process, or against a target deployed as it expects",
219                );
220            }
221            Some(_) => {}
222        }
223    }
224    if let Some(name) = vars.keys().find(|n| !env.contains_key(*n)) {
225        return refusal(
226            format!("doesn't set `{name}`, which the target declares"),
227            "in process an unset name reads as `None`, so the target is a different environment; pin the value in the case's `env`",
228        );
229    }
230    None
231}
232
233#[cfg(test)]
234mod remote_env_tests {
235    use super::*;
236
237    fn map(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
238        pairs
239            .iter()
240            .map(|(k, v)| (k.to_string(), v.to_string()))
241            .collect()
242    }
243
244    fn check(env: &[(&str, &str)], vars: &[(&str, &str)], secrets: &[&str]) -> Option<String> {
245        let secrets: Vec<String> = secrets.iter().map(|s| s.to_string()).collect();
246        remote_env_disagreement("c", Span::default(), &map(env), &map(vars), &secrets)
247            .map(|e| e.message)
248    }
249
250    #[test]
251    fn agreeing_env_and_vars_run() {
252        assert_eq!(check(&[], &[], &[]), None);
253        assert_eq!(check(&[("P", "fake")], &[("P", "fake")], &["S"]), None);
254    }
255
256    #[test]
257    fn every_disagreement_is_refused() {
258        let listed = check(&[("S", "x")], &[], &["S"]).expect("a listed name is refused");
259        assert!(listed.contains("sets the secret `S`"), "{listed}");
260        let undeclared = check(&[("P", "fake")], &[], &[]).expect("undeclared is refused");
261        assert!(undeclared.contains("doesn't declare"), "{undeclared}");
262        let differs = check(&[("P", "fake")], &[("P", "real")], &[]).expect("differs");
263        assert!(differs.contains("deployed with `\"real\"`"), "{differs}");
264        let unset = check(&[], &[("P", "real")], &[]).expect("unset is refused");
265        assert!(unset.contains("doesn't set `P`"), "{unset}");
266    }
267}