1use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
12#[serde(deny_unknown_fields)]
13pub struct Script {
14 pub name: String,
15 #[serde(default, skip_serializing_if = "Option::is_none")]
17 pub note: Option<String>,
18 #[serde(default = "default_backend")]
19 pub backend: String,
20 #[serde(default = "default_size")]
21 pub size: [f32; 2],
22 #[serde(default = "default_ppp")]
23 pub ppp: f32,
24 #[serde(default)]
26 pub seed: bool,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub document: Option<String>,
30 #[serde(default, skip_serializing_if = "Vec::is_empty")]
37 pub fixtures: Vec<String>,
38 #[serde(default = "default_timeout")]
39 pub timeout_ms: u64,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub video: Option<Video>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub plm: Option<PlmSpec>,
50 pub steps: Vec<Step>,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
57#[serde(deny_unknown_fields)]
58pub struct PlmSpec {
59 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 pub users: Vec<PlmUser>,
62 #[serde(default, skip_serializing_if = "Vec::is_empty")]
65 pub setup: Vec<PlmCall>,
66 #[serde(default = "default_plm_app_user")]
72 pub app_user: String,
73 #[serde(default = "default_true")]
77 pub app_token: bool,
78 #[serde(default, skip_serializing_if = "Vec::is_empty")]
80 pub args: Vec<String>,
81 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
83 pub env: std::collections::BTreeMap<String, String>,
84}
85
86fn default_plm_app_user() -> String {
87 "admin".into()
88}
89
90fn default_true() -> bool {
91 true
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
96#[serde(deny_unknown_fields)]
97pub struct PlmUser {
98 pub username: String,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub password: Option<String>,
102 #[serde(default, skip_serializing_if = "Vec::is_empty")]
103 pub groups: Vec<String>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub scope: Option<String>,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
113#[serde(deny_unknown_fields)]
114pub struct PlmCall {
115 #[serde(default = "default_plm_method")]
116 pub method: String,
117 pub path: String,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub body: Option<Value>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub raw: Option<String>,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub content_type: Option<String>,
129 #[serde(default, rename = "as", skip_serializing_if = "Option::is_none")]
132 pub as_user: Option<String>,
133 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
138 pub browser: bool,
139 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
142 pub bind: std::collections::BTreeMap<String, String>,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub status: Option<u16>,
147}
148
149fn default_plm_method() -> String {
150 "GET".into()
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
162#[serde(deny_unknown_fields)]
163pub struct Video {
164 pub out: String,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub title: Option<String>,
172 #[serde(default = "default_video_width")]
175 pub width: u32,
176 #[serde(default = "default_video_speed")]
178 pub speed: i32,
179}
180
181fn default_video_width() -> u32 {
182 1000
183}
184fn default_video_speed() -> i32 {
185 15
186}
187fn default_hold_ms() -> u32 {
188 1600
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
203#[serde(deny_unknown_fields)]
204pub struct Frame {
205 pub caption: String,
207 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub highlight: Option<Value>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub entity: Option<Value>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub point: Option<Value>,
221 #[serde(default = "default_hold_ms")]
223 pub hold_ms: u32,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub motion: Option<Motion>,
230}
231
232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
247#[serde(deny_unknown_fields)]
248pub struct Motion {
249 #[serde(default = "default_motion_frames")]
253 pub frames: u32,
254 #[serde(default = "default_motion_hold_ms")]
258 pub hold_ms: u32,
259 #[serde(default = "default_cursor_scale")]
264 pub cursor_scale: u32,
265}
266
267fn default_motion_frames() -> u32 {
268 8
269}
270fn default_motion_hold_ms() -> u32 {
271 120
272}
273fn default_cursor_scale() -> u32 {
274 3
275}
276
277pub const PLM_REQUEST: &str = "plm_request";
280
281pub const PLM_SERVER: &str = "plm_server";
284
285pub const DRAG_TOOLS: [&str; 3] = ["drag", "drag_widget", "drag_entity"];
288
289fn default_backend() -> String {
290 "headless".into()
291}
292fn default_size() -> [f32; 2] {
293 [1400.0, 960.0]
294}
295fn default_ppp() -> f32 {
296 1.0
297}
298fn default_timeout() -> u64 {
299 120_000
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
303#[serde(deny_unknown_fields)]
304pub struct Step {
305 pub tool: String,
306 #[serde(default)]
307 pub args: Value,
308 #[serde(default, skip_serializing_if = "Vec::is_empty")]
309 pub expect: Vec<Expect>,
310 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub save: Option<String>,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub compare: Option<Compare>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub note: Option<String>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
321 pub expect_error: Option<String>,
322 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
326 pub bind: std::collections::BTreeMap<String, String>,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub frame: Option<Frame>,
331}
332
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
334#[serde(deny_unknown_fields)]
335pub struct Compare {
336 pub baseline: String,
338 #[serde(default = "default_max_diff")]
339 pub max_diff_ratio: f64,
340}
341
342fn default_max_diff() -> f64 {
343 0.002
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
349#[serde(deny_unknown_fields)]
350pub struct Expect {
351 pub path: String,
352 #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
353 pub eq: Option<Value>,
354 #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
355 pub ne: Option<Value>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub gt: Option<f64>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub gte: Option<f64>,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub lt: Option<f64>,
362 #[serde(default, skip_serializing_if = "Option::is_none")]
363 pub lte: Option<f64>,
364 #[serde(default, skip_serializing_if = "Option::is_none")]
365 pub near: Option<f64>,
366 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub tol: Option<f64>,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub contains: Option<Value>,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub matches: Option<String>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub exists: Option<bool>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub len: Option<usize>,
376}
377
378fn present<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
386where
387 D: serde::Deserializer<'de>,
388{
389 Value::deserialize(deserializer).map(Some)
390}
391
392pub mod exit {
394 pub const PASS: i32 = 0;
395 pub const EXPECTATION_FAILED: i32 = 1;
396 pub const TOOL_ERROR: i32 = 2;
397 pub const HOST_ERROR: i32 = 3;
398 pub const TIMEOUT: i32 = 4;
399}
400
401impl Script {
402 pub fn parse(text: &str) -> Result<Self, String> {
403 let s: Script = serde_json::from_str(text).map_err(|e| format!("script parse: {e}"))?;
404 if s.steps.is_empty() {
405 return Err("script has no steps".into());
406 }
407 for (i, step) in s.steps.iter().enumerate() {
408 if let Some(frame) = &step.frame {
409 if let Some(motion) = &frame.motion {
410 if !DRAG_TOOLS.contains(&step.tool.as_str()) {
415 return Err(format!(
416 "step {i}: `frame.motion` films a DRAG, but this step is `{}` (one of {})",
417 step.tool,
418 DRAG_TOOLS.join(", ")
419 ));
420 }
421 if s.video.is_none() {
422 return Err(format!(
423 "step {i}: `frame.motion` only means something in a script that declares a `video`"
424 ));
425 }
426 if motion.frames == 0 {
427 return Err(format!("step {i}: `frame.motion.frames` must be at least 1"));
428 }
429 if motion.cursor_scale == 0 {
430 return Err(format!("step {i}: `frame.motion.cursor_scale` must be at least 1"));
431 }
432 }
433 }
434 if (step.tool == PLM_REQUEST || step.tool == PLM_SERVER) && (step.save.is_some() || step.compare.is_some()) {
438 return Err(format!(
439 "step {i}: `{}` is answered by the runner and makes no image, so `save` / `compare` cannot be honoured",
440 step.tool
441 ));
442 }
443 if !step.bind.is_empty() && step.expect_error.is_some() {
444 return Err(format!(
445 "step {i}: `bind` reads the step's result, but `expect_error` expects it to fail, so nothing would be bound"
446 ));
447 }
448 if !step.bind.is_empty() && s.plm.is_none() {
449 return Err(format!("step {i}: `bind` needs the script to declare `plm`, which holds the variables"));
450 }
451 for (j, e) in step.expect.iter().enumerate() {
452 if e.operator_count() != 1 {
453 return Err(format!(
454 "step {i} (`{}`) expect {j}: exactly one operator is required",
455 step.tool
456 ));
457 }
458 if !e.path.starts_with('/') && !e.path.is_empty() {
459 return Err(format!(
460 "step {i} expect {j}: `path` must be a JSON pointer starting with `/` (got `{}`)",
461 e.path
462 ));
463 }
464 }
465 }
466 Ok(s)
467 }
468
469 pub fn json_schema() -> Value {
472 serde_json::to_value(schemars::schema_for!(Script)).unwrap_or(Value::Null)
473 }
474}
475
476impl Expect {
477 fn operator_count(&self) -> usize {
478 [
479 self.eq.is_some(),
480 self.ne.is_some(),
481 self.gt.is_some(),
482 self.gte.is_some(),
483 self.lt.is_some(),
484 self.lte.is_some(),
485 self.near.is_some(),
486 self.contains.is_some(),
487 self.matches.is_some(),
488 self.exists.is_some(),
489 self.len.is_some(),
490 ]
491 .iter()
492 .filter(|b| **b)
493 .count()
494 }
495
496 pub fn check(&self, result: &Value) -> Result<(), String> {
499 let actual = result.pointer(&self.path);
500 if let Some(exists) = self.exists {
501 return if actual.is_some() == exists {
502 Ok(())
503 } else {
504 Err(format!("{}: exists == {} expected {exists}", self.path, actual.is_some()))
505 };
506 }
507 let Some(actual) = actual else {
508 return Err(format!("{}: no value at that path", self.path));
509 };
510 let num = |v: &Value| v.as_f64();
511 let shown = {
512 let t = actual.to_string();
513 if t.chars().count() > 160 {
514 format!("{}…", t.chars().take(160).collect::<String>())
515 } else {
516 t
517 }
518 };
519 let fail = |what: &str| Err(format!("{}: {what}; actual {shown}", self.path));
520 if let Some(e) = &self.eq {
521 return if actual == e { Ok(()) } else { fail(&format!("expected {e}")) };
522 }
523 if let Some(e) = &self.ne {
524 return if actual != e { Ok(()) } else { fail(&format!("expected not {e}")) };
525 }
526 if let Some(b) = self.gt {
527 return match num(actual) { Some(a) if a > b => Ok(()), _ => fail(&format!("expected > {b}")) };
528 }
529 if let Some(b) = self.gte {
530 return match num(actual) { Some(a) if a >= b => Ok(()), _ => fail(&format!("expected >= {b}")) };
531 }
532 if let Some(b) = self.lt {
533 return match num(actual) { Some(a) if a < b => Ok(()), _ => fail(&format!("expected < {b}")) };
534 }
535 if let Some(b) = self.lte {
536 return match num(actual) { Some(a) if a <= b => Ok(()), _ => fail(&format!("expected <= {b}")) };
537 }
538 if let Some(b) = self.near {
539 let tol = self.tol.unwrap_or(1e-6);
540 return match num(actual) {
541 Some(a) if (a - b).abs() <= tol * b.abs().max(1.0) => Ok(()),
542 _ => fail(&format!("expected within {tol} (relative) of {b}")),
543 };
544 }
545 if let Some(needle) = &self.contains {
546 let ok = match (actual, needle) {
547 (Value::String(s), Value::String(n)) => s.contains(n.as_str()),
548 (Value::Array(a), n) => a.contains(n),
549 (Value::Object(o), Value::String(n)) => o.contains_key(n),
550 _ => false,
551 };
552 return if ok { Ok(()) } else { fail(&format!("expected to contain {needle}")) };
553 }
554 if let Some(pattern) = &self.matches {
555 let Some(s) = actual.as_str() else { return fail("expected a string to match") };
556 return if glob_match(pattern, s) { Ok(()) } else { fail(&format!("expected to match `{pattern}`")) };
557 }
558 if let Some(n) = self.len {
559 let l = match actual {
560 Value::Array(a) => Some(a.len()),
561 Value::String(s) => Some(s.chars().count()),
562 Value::Object(o) => Some(o.len()),
563 _ => None,
564 };
565 return match l { Some(l) if l == n => Ok(()), _ => fail(&format!("expected length {n}")) };
566 }
567 Err(format!("{}: no operator", self.path))
568 }
569}
570
571pub fn glob_match(pattern: &str, text: &str) -> bool {
574 fn rec(p: &[char], t: &[char]) -> bool {
575 match (p.first(), t.first()) {
576 (None, None) => true,
577 (Some('*'), _) => rec(&p[1..], t) || (!t.is_empty() && rec(p, &t[1..])),
578 (Some('?'), Some(_)) => rec(&p[1..], &t[1..]),
579 (Some(a), Some(b)) if a == b => rec(&p[1..], &t[1..]),
580 _ => false,
581 }
582 }
583 let p: Vec<char> = pattern.chars().collect();
584 let t: Vec<char> = text.chars().collect();
585 rec(&p, &t)
586}
587