1use std::collections::BTreeMap;
2
3use either::Either;
4use rand::{Rng, SeedableRng};
5use scratch_test_interpreter::{
6 Limits, RunError,
7 default_state::{DefaultState, DefaultStateError},
8 error::UserError,
9};
10use scratch_test_model::{Id, ProjectDoc, attrs::DataId};
11use serde::{Deserialize, Serialize};
12
13use crate::{
14 Features, LogPfx,
15 catchable::cerr,
16 evaluation::{
17 Context, Rundata, SelectableSource, SingleEvaluation, SingleEvaluationError,
18 single_evaluation::EvalSignal,
19 },
20 spec::{
21 Array, GeneralTest, MapKey, NoticeAction, PrimitiveValue, RandomGeneration, RuntimeAction,
22 RuntimeCriterion, RuntimeValue, Text,
23 },
24};
25
26#[derive(Debug, thiserror::Error, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
27#[serde(rename_all = "kebab-case")]
28pub enum FatalRunError {
29 #[error("runerror-file: {_0}")]
30 File(#[from] scratch_test_interpreter::error::InvalidFileError),
31 #[error("runerror-internal: {_0}")]
32 Internal(#[from] scratch_test_interpreter::error::InternalError),
33 #[error("runerror-unsupported: {_0}")]
34 Unsupported(#[from] scratch_test_interpreter::error::UnsupportedError),
35}
36
37#[derive(Debug, thiserror::Error, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
41#[serde(rename_all = "kebab-case")]
42pub enum JustFailTestRunError {
43 #[error("runerror-user: {_0}")]
44 User(#[from] UserError),
45 #[error("runerror-limit: {_0}")]
46 Limit(#[from] scratch_test_interpreter::error::LimitError),
47 #[error("runerror-other: {_0}")]
48 State(#[from] DefaultStateError),
49}
50
51pub type ActualTestResultEval = (
52 Vec<RuntimeAction>,
53 Result<Either<EvalSignal, RuntimeCriterion>, SingleEvaluationError>,
54);
55pub type ActualTestResultStatus =
56 Either<ActualTestResultEval, Result<JustFailTestRunError, FatalRunError>>;
57
58#[derive(Debug, PartialEq, PartialOrd, Clone)]
59pub struct ActualTestResult {
60 pub(crate) status: ActualTestResultStatus,
61 pub(crate) testdata: Rundata,
62 pub(crate) notice_actions: Vec<NoticeAction>,
63}
64
65impl ActualTestResult {
66 pub async fn from_run<Hooks, Source: SelectableSource>(
67 settings: &Context,
68 log_pfx: LogPfx,
69 test: &GeneralTest<Hooks>,
70 source: Source,
71 features: Features,
72 ) -> Self {
73 run_actual_test(settings, log_pfx, test, source, features).await
74 }
75}
76
77pub(crate) async fn run_actual_test<Hooks, Source: SelectableSource>(
78 settings: &Context,
79 log_pfx: LogPfx,
80 test: &GeneralTest<Hooks>,
81 fallback: Source,
82 features: Features,
83) -> ActualTestResult {
84 let (testdata, _state, error, _limits) = run_single_test_for_selectable(
85 settings,
86 log_pfx.clone(),
87 settings.doc(),
88 settings.initial_block(),
89 test,
90 );
91
92 if let Some(error) = error {
93 let maybe_error: Result<Option<JustFailTestRunError>, FatalRunError> = match error {
96 RunError::TerminatedByControlStop => Ok(None),
97 RunError::User(
98 err @ (UserError::InfiniteLoopWithoutBodyNeverStops
99 | UserError::ConditionLoopWithoutBodyNeverStops
100 | UserError::WaitUntilFalseNeverTerminatesInSingleThreadded),
101 ) => Ok(Some(err.into())),
102 RunError::File(err) => Err(err.into()),
103 RunError::Internal(err) => Err(err.into()),
104 RunError::Unsupported(err) => Err(err.into()),
105 RunError::Limit(err) => Ok(Some(err.into())),
106 RunError::State(err) => Ok(Some(err.into())),
107 };
108 if let Some(error) = maybe_error.transpose() {
109 return ActualTestResult {
110 status: Either::Right(error),
111 testdata,
112 notice_actions: Default::default(),
113 };
114 }
115 }
116
117 let criterion = test.criterion();
118 match SingleEvaluation::new(
119 log_pfx.join("pass-crit"),
120 settings.entities(),
121 criterion.cast_id(),
122 &(&testdata, &fallback),
123 features,
124 settings.allowed_network().clone(),
125 ) {
126 Ok(eval) => {
127 let (notice_actions, eval) = eval.run_to_end_with_early_return().await;
128 let value: Result<Either<EvalSignal, RuntimeCriterion>, SingleEvaluationError> =
129 eval.one_specialized();
130 ActualTestResult {
131 status: Either::Left((eval.into_actions(), value)),
132 testdata,
133 notice_actions,
134 }
135 }
136 Err(err) => ActualTestResult {
137 status: Either::Left((Default::default(), Err(err.into()))),
138 testdata,
139 notice_actions: Default::default(),
140 },
141 }
142}
143
144fn run_single_test_for_selectable<Hooks>(
145 ctx: &Context,
146 _log_pfx: LogPfx,
147 doc: &ProjectDoc,
148 initial_block: &Id,
149 general: &GeneralTest<Hooks>,
150) -> (
151 Rundata,
152 DefaultState,
153 Option<RunError<DefaultStateError>>,
154 Limits,
155) {
156 let input: Option<&Vec<PrimitiveValue>> = general.input().as_ref();
157 let predefined_randoms = general.predefined_randoms().as_ref();
158 let random_generation = general.random_generation();
159
160 let interp =
161 scratch_test_interpreter::Interpreter::new_restrictive().with_limits(ctx.limits().clone());
162
163 let mut state = DefaultState::from_doc(doc, ctx.max_list_length().into());
164 state.set_randoms(match random_generation {
166 RandomGeneration::Disabled => None,
167 RandomGeneration::EnabledWithSeed(seed) => {
168 Some(rand::prelude::StdRng::seed_from_u64(*seed))
169 }
170 RandomGeneration::Enabled => {
171 Some(rand::prelude::StdRng::seed_from_u64(rand::rng().next_u64()))
172 }
173 });
174
175 if let Some(input) = input {
176 let answers: Vec<std::sync::Arc<str>> = input
177 .iter()
178 .map(|x| x.to_owned().into_text().into())
179 .collect();
180 state.set_answers(answers);
181 }
182
183 setup_initial_lists_and_vars(doc, &mut state, general);
184
185 if let Some(predefined_randoms) = predefined_randoms {
186 state.set_predefined_randoms(predefined_randoms.iter().cloned().collect());
187 }
188 let report = interp.run(doc, state, initial_block);
189 let (state, error, limits) = report.take_parts();
190
191 let rundata = Rundata::new(
192 state
193 .answer_inputs()
194 .iter()
195 .map(|x| RuntimeValue::from(Text::from(x.to_string())))
196 .map(Ok)
197 .collect::<Vec<_>>(),
198 state
199 .output_lines()
200 .map(|x| RuntimeValue::from(Text::from(x.to_string())))
201 .map(Ok)
202 .collect::<Vec<_>>(),
203 state
204 .used_randoms()
205 .map(|x| RuntimeValue::from(*x))
206 .map(Ok)
207 .collect::<Vec<_>>(),
208 state
209 .lists()
210 .iter()
211 .map(|x| {
212 (
213 MapKey::Str(x.0.name().to_string().into()),
214 Ok(RuntimeValue::from(Array::from(x.1.clone()))),
215 )
216 })
217 .collect::<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>(),
218 state
219 .variables()
220 .iter()
221 .map(|x| {
222 (
223 MapKey::Str(x.0.name().to_string().into()),
224 Ok(RuntimeValue::from(x.1.clone())),
225 )
226 })
227 .collect::<BTreeMap<MapKey, Result<RuntimeValue, cerr>>>(),
228 );
229 (rundata, state, error, limits)
230}
231
232fn setup_initial_lists_and_vars<Hooks>(
233 doc: &ProjectDoc,
234 state: &mut DefaultState,
235 general: &GeneralTest<Hooks>,
236) {
237 let mut new_id = 0;
238 let mut new_id_str;
239
240 if let Some(initial_vars) = general.initial_variables().as_ref() {
241 let doc_vars: BTreeMap<&str, &scratch_test_model::Id> = doc
242 .targets()
243 .iter()
244 .flat_map(|target| target.variables().values())
245 .map(|x| (x.0.name().as_str(), x.0.id()))
246 .collect();
247
248 for (name, value) in initial_vars.iter() {
249 let id: scratch_test_model::Id = if let Some(id) = doc_vars.get(name.as_str()).cloned()
250 {
251 id.clone()
252 } else {
253 loop {
254 new_id += 1;
255 new_id_str = format!("id{new_id}");
256 if doc_vars
257 .values()
258 .find(|x| ****x == *new_id_str.as_str())
259 .is_none()
260 {
261 break;
262 }
263 }
264 new_id_str.into()
265 };
266 state
267 .variables_mut()
268 .insert(DataId::new(name.clone(), id), value.clone().into_svalue());
269 }
270 }
271
272 if let Some(initial_lists) = general.initial_lists().as_ref() {
273 let doc_lists: BTreeMap<&str, &scratch_test_model::Id> = doc
274 .targets()
275 .iter()
276 .flat_map(|target| target.lists().values())
277 .map(|x| (x.0.name().as_str(), x.0.id()))
278 .collect();
279 for (name, value) in initial_lists.iter() {
280 let id: scratch_test_model::Id = if let Some(id) = doc_lists.get(name.as_str()).cloned()
281 {
282 id.clone()
283 } else {
284 loop {
285 new_id += 1;
286 new_id_str = format!("id{new_id}");
287 if doc_lists
288 .values()
289 .find(|x| ****x == *new_id_str.as_str())
290 .is_none()
291 {
292 break;
293 }
294 }
295 new_id_str.into()
296 };
297 state.lists_mut().insert(
298 DataId::new(name.clone(), id),
299 value.iter().map(|x| x.clone().into_svalue()).collect(),
300 );
301 }
302 }
303}