use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Script {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(default = "default_backend")]
pub backend: String,
#[serde(default = "default_size")]
pub size: [f32; 2],
#[serde(default = "default_ppp")]
pub ppp: f32,
#[serde(default)]
pub seed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub document: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fixtures: Vec<String>,
#[serde(default = "default_timeout")]
pub timeout_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub video: Option<Video>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plm: Option<PlmSpec>,
pub steps: Vec<Step>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlmSpec {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub users: Vec<PlmUser>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub setup: Vec<PlmCall>,
#[serde(default = "default_plm_app_user")]
pub app_user: String,
#[serde(default = "default_true")]
pub app_token: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub env: std::collections::BTreeMap<String, String>,
}
fn default_plm_app_user() -> String {
"admin".into()
}
fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlmUser {
pub username: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlmCall {
#[serde(default = "default_plm_method")]
pub method: String,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, rename = "as", skip_serializing_if = "Option::is_none")]
pub as_user: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub browser: bool,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub bind: std::collections::BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<u16>,
}
fn default_plm_method() -> String {
"GET".into()
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Video {
pub out: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default = "default_video_width")]
pub width: u32,
#[serde(default = "default_video_speed")]
pub speed: i32,
}
fn default_video_width() -> u32 {
1000
}
fn default_video_speed() -> i32 {
15
}
fn default_hold_ms() -> u32 {
1600
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Frame {
pub caption: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub highlight: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub entity: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub point: Option<Value>,
#[serde(default = "default_hold_ms")]
pub hold_ms: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub motion: Option<Motion>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Motion {
#[serde(default = "default_motion_frames")]
pub frames: u32,
#[serde(default = "default_motion_hold_ms")]
pub hold_ms: u32,
#[serde(default = "default_cursor_scale")]
pub cursor_scale: u32,
}
fn default_motion_frames() -> u32 {
8
}
fn default_motion_hold_ms() -> u32 {
120
}
fn default_cursor_scale() -> u32 {
3
}
pub const PLM_REQUEST: &str = "plm_request";
pub const PLM_SERVER: &str = "plm_server";
pub const DRAG_TOOLS: [&str; 3] = ["drag", "drag_widget", "drag_entity"];
fn default_backend() -> String {
"headless".into()
}
fn default_size() -> [f32; 2] {
[1400.0, 960.0]
}
fn default_ppp() -> f32 {
1.0
}
fn default_timeout() -> u64 {
120_000
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Step {
pub tool: String,
#[serde(default)]
pub args: Value,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub expect: Vec<Expect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub save: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compare: Option<Compare>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expect_error: Option<String>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub bind: std::collections::BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frame: Option<Frame>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Compare {
pub baseline: String,
#[serde(default = "default_max_diff")]
pub max_diff_ratio: f64,
}
fn default_max_diff() -> f64 {
0.002
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Expect {
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
pub eq: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
pub ne: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gt: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gte: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lt: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lte: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub near: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tol: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contains: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matches: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exists: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub len: Option<usize>,
}
fn present<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
Value::deserialize(deserializer).map(Some)
}
pub mod exit {
pub const PASS: i32 = 0;
pub const EXPECTATION_FAILED: i32 = 1;
pub const TOOL_ERROR: i32 = 2;
pub const HOST_ERROR: i32 = 3;
pub const TIMEOUT: i32 = 4;
}
impl Script {
pub fn parse(text: &str) -> Result<Self, String> {
let s: Script = serde_json::from_str(text).map_err(|e| format!("script parse: {e}"))?;
if s.steps.is_empty() {
return Err("script has no steps".into());
}
for (i, step) in s.steps.iter().enumerate() {
if let Some(frame) = &step.frame {
if let Some(motion) = &frame.motion {
if !DRAG_TOOLS.contains(&step.tool.as_str()) {
return Err(format!(
"step {i}: `frame.motion` films a DRAG, but this step is `{}` (one of {})",
step.tool,
DRAG_TOOLS.join(", ")
));
}
if s.video.is_none() {
return Err(format!(
"step {i}: `frame.motion` only means something in a script that declares a `video`"
));
}
if motion.frames == 0 {
return Err(format!("step {i}: `frame.motion.frames` must be at least 1"));
}
if motion.cursor_scale == 0 {
return Err(format!("step {i}: `frame.motion.cursor_scale` must be at least 1"));
}
}
}
if (step.tool == PLM_REQUEST || step.tool == PLM_SERVER) && (step.save.is_some() || step.compare.is_some()) {
return Err(format!(
"step {i}: `{}` is answered by the runner and makes no image, so `save` / `compare` cannot be honoured",
step.tool
));
}
if !step.bind.is_empty() && step.expect_error.is_some() {
return Err(format!(
"step {i}: `bind` reads the step's result, but `expect_error` expects it to fail, so nothing would be bound"
));
}
if !step.bind.is_empty() && s.plm.is_none() {
return Err(format!("step {i}: `bind` needs the script to declare `plm`, which holds the variables"));
}
for (j, e) in step.expect.iter().enumerate() {
if e.operator_count() != 1 {
return Err(format!(
"step {i} (`{}`) expect {j}: exactly one operator is required",
step.tool
));
}
if !e.path.starts_with('/') && !e.path.is_empty() {
return Err(format!(
"step {i} expect {j}: `path` must be a JSON pointer starting with `/` (got `{}`)",
e.path
));
}
}
}
Ok(s)
}
pub fn json_schema() -> Value {
serde_json::to_value(schemars::schema_for!(Script)).unwrap_or(Value::Null)
}
}
impl Expect {
fn operator_count(&self) -> usize {
[
self.eq.is_some(),
self.ne.is_some(),
self.gt.is_some(),
self.gte.is_some(),
self.lt.is_some(),
self.lte.is_some(),
self.near.is_some(),
self.contains.is_some(),
self.matches.is_some(),
self.exists.is_some(),
self.len.is_some(),
]
.iter()
.filter(|b| **b)
.count()
}
pub fn check(&self, result: &Value) -> Result<(), String> {
let actual = result.pointer(&self.path);
if let Some(exists) = self.exists {
return if actual.is_some() == exists {
Ok(())
} else {
Err(format!("{}: exists == {} expected {exists}", self.path, actual.is_some()))
};
}
let Some(actual) = actual else {
return Err(format!("{}: no value at that path", self.path));
};
let num = |v: &Value| v.as_f64();
let shown = {
let t = actual.to_string();
if t.chars().count() > 160 {
format!("{}…", t.chars().take(160).collect::<String>())
} else {
t
}
};
let fail = |what: &str| Err(format!("{}: {what}; actual {shown}", self.path));
if let Some(e) = &self.eq {
return if actual == e { Ok(()) } else { fail(&format!("expected {e}")) };
}
if let Some(e) = &self.ne {
return if actual != e { Ok(()) } else { fail(&format!("expected not {e}")) };
}
if let Some(b) = self.gt {
return match num(actual) { Some(a) if a > b => Ok(()), _ => fail(&format!("expected > {b}")) };
}
if let Some(b) = self.gte {
return match num(actual) { Some(a) if a >= b => Ok(()), _ => fail(&format!("expected >= {b}")) };
}
if let Some(b) = self.lt {
return match num(actual) { Some(a) if a < b => Ok(()), _ => fail(&format!("expected < {b}")) };
}
if let Some(b) = self.lte {
return match num(actual) { Some(a) if a <= b => Ok(()), _ => fail(&format!("expected <= {b}")) };
}
if let Some(b) = self.near {
let tol = self.tol.unwrap_or(1e-6);
return match num(actual) {
Some(a) if (a - b).abs() <= tol * b.abs().max(1.0) => Ok(()),
_ => fail(&format!("expected within {tol} (relative) of {b}")),
};
}
if let Some(needle) = &self.contains {
let ok = match (actual, needle) {
(Value::String(s), Value::String(n)) => s.contains(n.as_str()),
(Value::Array(a), n) => a.contains(n),
(Value::Object(o), Value::String(n)) => o.contains_key(n),
_ => false,
};
return if ok { Ok(()) } else { fail(&format!("expected to contain {needle}")) };
}
if let Some(pattern) = &self.matches {
let Some(s) = actual.as_str() else { return fail("expected a string to match") };
return if glob_match(pattern, s) { Ok(()) } else { fail(&format!("expected to match `{pattern}`")) };
}
if let Some(n) = self.len {
let l = match actual {
Value::Array(a) => Some(a.len()),
Value::String(s) => Some(s.chars().count()),
Value::Object(o) => Some(o.len()),
_ => None,
};
return match l { Some(l) if l == n => Ok(()), _ => fail(&format!("expected length {n}")) };
}
Err(format!("{}: no operator", self.path))
}
}
pub fn glob_match(pattern: &str, text: &str) -> bool {
fn rec(p: &[char], t: &[char]) -> bool {
match (p.first(), t.first()) {
(None, None) => true,
(Some('*'), _) => rec(&p[1..], t) || (!t.is_empty() && rec(p, &t[1..])),
(Some('?'), Some(_)) => rec(&p[1..], &t[1..]),
(Some(a), Some(b)) if a == b => rec(&p[1..], &t[1..]),
_ => false,
}
}
let p: Vec<char> = pattern.chars().collect();
let t: Vec<char> = text.chars().collect();
rec(&p, &t)
}