day_script_protocol/
ids.rs1use serde::{Deserialize, Serialize};
5use std::collections::BTreeSet;
6
7#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
8pub struct IdDeclaration {
9 pub family: String,
10 pub keyed: bool,
11 pub package: String,
12 pub version: String,
13 pub locations: Vec<String>,
14}
15#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
16pub struct IdCatalog {
17 pub schema_version: u32,
18 pub declarations: Vec<IdDeclaration>,
19}
20impl IdCatalog {
21 pub fn validate(&self) -> Result<(), String> {
27 if self.schema_version != 1 {
28 return Err("unsupported element registry version".into());
29 }
30 let mut names = BTreeSet::new();
31 for d in &self.declarations {
32 if !names.insert(&d.family) {
33 return Err(format!("duplicate registry family {}", d.family));
34 }
35 }
36 Ok(())
37 }
38 pub fn resolve(&self, id: &str) -> Result<&IdDeclaration, String> {
45 let mut split = None;
46 let mut chars = id.char_indices().peekable();
47 while let Some((i, c)) = chars.next() {
48 if c == ':' {
49 if chars.peek().is_some_and(|(_, c)| *c == ':') {
50 chars.next();
51 } else {
52 split = Some(i);
53 break;
54 }
55 }
56 }
57 let family = split.map_or(id, |i| &id[..i]);
58 let d = self
59 .declarations
60 .iter()
61 .find(|d| d.family == family)
62 .ok_or_else(|| format!("undeclared element ID {family:?}"))?;
63 if d.keyed != split.is_some() {
64 return Err(format!("element ID {id:?} has wrong static/keyed shape"));
65 }
66 if let Some(i) = split {
67 validate_key(&id[i + 1..])?;
68 }
69 Ok(d)
70 }
71}
72fn unreserved(b: u8) -> bool {
73 b.is_ascii_alphanumeric() || b"-._~".contains(&b)
74}
75fn validate_key(key: &str) -> Result<(), String> {
76 let b = key.as_bytes();
77 let mut out = Vec::new();
78 let mut i = 0;
79 while i < b.len() {
80 if unreserved(b[i]) {
81 out.push(b[i]);
82 i += 1;
83 continue;
84 }
85 if b[i] != b'%' || i + 2 >= b.len() {
86 return Err("noncanonical element key; use percent-encoded UTF-8".into());
87 }
88 let digit = |x: u8| match x {
89 b'0'..=b'9' => Some(x - b'0'),
90 b'A'..=b'F' => Some(x - b'A' + 10),
91 _ => None,
92 };
93 let (Some(hi), Some(lo)) = (digit(b[i + 1]), digit(b[i + 2])) else {
94 return Err("element key escapes require uppercase hexadecimal".into());
95 };
96 let byte = (hi << 4) | lo;
97 if unreserved(byte) {
98 return Err("unnecessary element key escape".into());
99 }
100 out.push(byte);
101 i += 3;
102 }
103 String::from_utf8(out).map_err(|_| "element key is not UTF-8".to_owned())?;
104 Ok(())
105}
106#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
107#[serde(rename_all = "snake_case")]
108pub enum EvidenceClass {
109 Interaction,
110 Assertion,
111 Observed,
112 Negative,
113}
114#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
115pub struct IdEvidence {
116 pub family: String,
117 pub class: EvidenceClass,
118}
119
120impl crate::Step {
121 #[must_use]
128 pub fn element_references(&self) -> Vec<String> {
129 let value = serde_json::to_value(self).expect("serializable step");
130 let mut ids = Vec::new();
131 for field in ["id", "relative_to", "item_id"] {
132 if let Some(id) = value.get(field).and_then(|v| v.as_str()) {
133 ids.push(id.to_owned());
134 }
135 }
136 if let Self::Toolbar { item, .. } = self {
137 ids.push(item.clone());
138 }
139 ids
140 }
141 #[must_use]
142 pub fn evidence_class(&self) -> Option<EvidenceClass> {
143 use EvidenceClass::{Assertion, Interaction, Negative, Observed};
144 match self {
145 Self::WaitFor { .. } => Some(Observed),
146 Self::AssertMissing { .. } | Self::AssertHidden { .. } => Some(Negative),
147 Self::AssertVisible { .. }
148 | Self::AssertText { .. }
149 | Self::AssertValue { .. }
150 | Self::AssertFrame { .. }
151 | Self::AssertDisplayed { .. }
152 | Self::AssertNative { .. }
153 | Self::AssertFocused { .. } => Some(Assertion),
154 Self::WebEval { text, contains, .. } => {
155 if text.is_some() || contains.is_some() {
156 Some(Assertion)
157 } else {
158 Some(Observed)
159 }
160 }
161 Self::Tap { .. }
162 | Self::Key { .. }
163 | Self::ScrollTo { .. }
164 | Self::Drag { .. }
165 | Self::Hover { .. }
166 | Self::Pan { .. }
167 | Self::Pinch { .. }
168 | Self::Rotate { .. }
169 | Self::Submit { .. }
170 | Self::Input { .. }
171 | Self::SetValue { .. }
172 | Self::Toggle { .. }
173 | Self::Select { .. }
174 | Self::Focus { .. }
175 | Self::Reorder { .. }
176 | Self::Expand { .. }
177 | Self::TreeMove { .. }
178 | Self::DeleteRow { .. }
179 | Self::SwipeRow { .. }
180 | Self::Menu { .. }
181 | Self::Toolbar { .. }
182 | Self::ContextMenu { .. } => Some(Interaction),
183 _ => None,
184 }
185 }
186}
187#[cfg(test)]
188mod tests {
189 use super::*;
190 #[test]
191 fn namespace_and_canonical_keys() {
192 let c = IdCatalog {
193 schema_version: 1,
194 declarations: vec![IdDeclaration {
195 family: "account::row".into(),
196 keyed: true,
197 package: "fixture".into(),
198 version: "0".into(),
199 locations: vec![],
200 }],
201 };
202 for s in ["account::row:42", "account::row:", "account::row:%3Ab"] {
203 assert!(c.resolve(s).is_ok(), "{s}");
204 }
205 for s in [
206 "account::row",
207 "account::row:%3ab",
208 "account::row:%41",
209 "account::row:%FF",
210 "unknown:1",
211 ] {
212 assert!(c.resolve(s).is_err(), "{s}");
213 }
214 }
215}