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