BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / tests / card_inputs.rs

card_inputs.rs

card_inputs.rs 12.5 KiB Download Raw
1use serde_json::{Value, json};
2use teams_core::{
3 AdaptiveCard, CardAction, CardActionKind, CardElement, CardInput, CardInputKind, ChoiceStyle,
4 TextStyle, collect_input_values, merge_input_data,
5};
6
7fn card(body: Value, actions: Value) -> AdaptiveCard {
8 AdaptiveCard::parse(&json!({"body": body, "actions": actions}).to_string()).unwrap()
9}
10
11fn inputs(body: Value) -> Vec<CardInput> {
12 card(body, json!([])).own_inputs()
13}
14
15fn one(body: Value) -> CardInput {
16 let mut parsed = inputs(json!([body]));
17 assert_eq!(parsed.len(), 1);
18 parsed.remove(0)
19}
20
21fn submit(data: Value, associated: Option<&str>) -> CardAction {
22 let mut action = json!({"type": "Action.Submit", "title": "Go", "data": data});
23 if let Some(associated) = associated {
24 action["associatedInputs"] = json!(associated);
25 }
26 card(json!([{"type": "TextBlock", "text": "x"}]), json!([action]))
27 .actions
28 .remove(0)
29}
30
31fn values(pairs: Value) -> serde_json::Map<String, Value> {
32 pairs.as_object().unwrap().clone()
33}
34
35#[test]
36fn text_input_keeps_every_field() {
37 let input = one(json!({
38 "type": "Input.Text", "id": "name", "label": "Name", "placeholder": "Your name",
39 "value": "Ada", "isMultiline": true, "maxLength": 20, "style": "Password",
40 "regex": "^[A-Z]", "isRequired": true, "errorMessage": "Start with a capital"
41 }));
42 assert_eq!(input.id, "name");
43 assert_eq!(input.label.as_deref(), Some("Name"));
44 assert!(input.required);
45 assert_eq!(input.error_message.as_deref(), Some("Start with a capital"));
46 let CardInputKind::Text(text) = &input.kind else {
47 panic!("text input expected");
48 };
49 assert_eq!(text.placeholder.as_deref(), Some("Your name"));
50 assert_eq!(text.value, "Ada");
51 assert!(text.multiline);
52 assert_eq!(text.max_length, Some(20));
53 assert_eq!(text.style, TextStyle::Password);
54 assert_eq!(text.regex.as_deref(), Some("^[A-Z]"));
55}
56
57#[test]
58fn number_input_reads_numeric_value_and_range() {
59 let input = one(json!({"type": "Input.Number", "id": "n", "value": 5, "min": 1, "max": 10.5}));
60 let CardInputKind::Number(number) = &input.kind else {
61 panic!("number input expected");
62 };
63 assert_eq!(number.value, "5");
64 assert_eq!((number.min, number.max), (Some(1.), Some(10.5)));
65}
66
67#[test]
68fn date_and_time_inputs_keep_their_bounds() {
69 let date = one(
70 json!({"type": "Input.Date", "id": "d", "value": "2026-01-02", "min": "2026-01-01", "max": "2026-12-31"}),
71 );
72 let CardInputKind::Date(moment) = &date.kind else {
73 panic!("date input expected");
74 };
75 assert_eq!(moment.value, "2026-01-02");
76 assert_eq!(moment.min.as_deref(), Some("2026-01-01"));
77 let time = one(json!({"type": "Input.Time", "id": "t", "value": "09:30"}));
78 assert!(matches!(time.kind, CardInputKind::Time(_)));
79 assert_eq!(time.initial_value(), "09:30");
80}
81
82#[test]
83fn toggle_defaults_to_true_false_and_off() {
84 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "Agree"}));
85 let CardInputKind::Toggle(toggle) = &input.kind else {
86 panic!("toggle expected");
87 };
88 assert_eq!(toggle.title, "Agree");
89 assert_eq!(
90 (toggle.value_on.as_str(), toggle.value_off.as_str()),
91 ("true", "false")
92 );
93 assert_eq!(input.initial_value(), "false");
94 assert_eq!(toggle.flipped("false"), "true");
95 assert_eq!(toggle.flipped("true"), "false");
96}
97
98#[test]
99fn toggle_with_custom_values_starts_on_its_value() {
100 let input = one(
101 json!({"type": "Input.Toggle", "id": "t", "title": "x", "valueOn": "yes", "valueOff": "no", "value": "yes"}),
102 );
103 assert_eq!(input.initial_value(), "yes");
104}
105
106#[test]
107fn choice_set_parses_style_and_multi_select() {
108 let input = one(json!({
109 "type": "Input.ChoiceSet", "id": "c", "style": "expanded", "isMultiSelect": true,
110 "value": "a,b", "placeholder": "Pick",
111 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}, {"title": "C", "value": "c"}]
112 }));
113 let CardInputKind::Choice(choice) = &input.kind else {
114 panic!("choice set expected");
115 };
116 assert_eq!(choice.style, ChoiceStyle::Expanded);
117 assert!(choice.multi);
118 assert_eq!(choice.choices.len(), 3);
119 assert_eq!(choice.selected("a,b"), vec!["a", "b"]);
120 assert_eq!(choice.toggled("a,b", "c"), "a,b,c");
121 assert_eq!(choice.toggled("a,b", "a"), "b");
122 assert_eq!(choice.toggled("", "b"), "b");
123}
124
125#[test]
126fn single_choice_replaces_the_selection() {
127 let input = one(json!({
128 "type": "Input.ChoiceSet", "id": "c", "style": "filtered",
129 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}]
130 }));
131 let CardInputKind::Choice(choice) = &input.kind else {
132 panic!("choice set expected");
133 };
134 assert_eq!(choice.style, ChoiceStyle::Filtered);
135 assert_eq!(choice.toggled("a", "b"), "b");
136 assert!(choice.selected("").is_empty());
137}
138
139#[test]
140fn inputs_without_id_or_choices_and_unknown_types_fall_back() {
141 let parsed = card(
142 json!([
143 {"type": "Input.Text"},
144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
145 {"type": "Input.Slider", "id": "r", "fallbackText": "Slider is not supported"}
146 ]),
147 json!([]),
148 );
149 assert!(parsed.own_inputs().is_empty());
150 assert_eq!(parsed.items.len(), 1);
151 assert!(matches!(parsed.items[0].element, CardElement::Text(_)));
152}
153
154#[test]
155fn nested_inputs_are_found_in_containers_and_columns_but_not_show_cards() {
156 let parsed = card(
157 json!([
158 {"type": "Input.Text", "id": "a"},
159 {"type": "Container", "items": [{"type": "Input.Text", "id": "b"}]},
160 {"type": "ColumnSet", "columns": [{"type": "Column", "items": [{"type": "Input.Text", "id": "c"}]}]},
161 {"type": "ActionSet", "actions": [
162 {"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "Input.Text", "id": "d"}]}}
163 ]}
164 ]),
165 json!([]),
166 );
167 let own: Vec<String> = parsed
168 .own_inputs()
169 .into_iter()
170 .map(|input| input.id)
171 .collect();
172 assert_eq!(own, ["a", "b", "c"]);
173 let all: Vec<String> = parsed
174 .all_inputs()
175 .into_iter()
176 .map(|input| input.id)
177 .collect();
178 assert_eq!(all, ["a", "b", "c", "d"]);
179}
180
181#[test]
182fn required_input_rejects_empty_with_default_or_custom_message() {
183 let plain = one(json!({"type": "Input.Text", "id": "a", "isRequired": true}));
184 assert_eq!(plain.validate("").as_deref(), Some("Required"));
185 assert_eq!(plain.validate("x"), None);
186 let custom = one(
187 json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Tell us"}),
188 );
189 assert_eq!(custom.validate("").as_deref(), Some("Tell us"));
190 let optional = one(json!({"type": "Input.Text", "id": "a"}));
191 assert_eq!(optional.validate(""), None);
192}
193
194#[test]
195fn text_regex_and_max_length_are_validated() {
196 let input = one(json!({"type": "Input.Text", "id": "a", "regex": "^\\d+$", "maxLength": 3}));
197 assert_eq!(input.validate("12"), None);
198 assert_eq!(input.validate("ab").as_deref(), Some("Invalid value"));
199 assert_eq!(input.validate("1234").as_deref(), Some("Invalid value"));
200}
201
202#[test]
203fn number_range_and_format_are_validated() {
204 let input = one(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 10}));
205 assert_eq!(input.validate("5.5"), None);
206 assert_eq!(input.validate("0").as_deref(), Some("Invalid value"));
207 assert_eq!(input.validate("11").as_deref(), Some("Invalid value"));
208 assert_eq!(input.validate("abc").as_deref(), Some("Invalid value"));
209}
210
211#[test]
212fn date_and_time_format_and_bounds_are_validated() {
213 let date =
214 one(json!({"type": "Input.Date", "id": "d", "min": "2026-01-10", "max": "2026-01-20"}));
215 assert_eq!(date.validate("2026-01-15"), None);
216 assert!(date.validate("2026-01-09").is_some());
217 assert!(date.validate("2026-01-21").is_some());
218 assert!(date.validate("15.01.2026").is_some());
219 assert!(date.validate("2026-02-30").is_some());
220 let time = one(json!({"type": "Input.Time", "id": "t", "min": "09:00", "max": "17:00"}));
221 assert_eq!(time.validate("09:30"), None);
222 assert!(time.validate("08:59").is_some());
223 assert!(time.validate("25:00").is_some());
224}
225
226#[test]
227fn required_toggle_must_be_on() {
228 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "x", "isRequired": true}));
229 assert_eq!(input.validate("false").as_deref(), Some("Invalid value"));
230 assert_eq!(input.validate("true"), None);
231}
232
233#[test]
234fn collecting_returns_every_error_or_all_values() {
235 let parsed = inputs(json!([
236 {"type": "Input.Text", "id": "a", "isRequired": true},
237 {"type": "Input.Text", "id": "b", "isRequired": true, "errorMessage": "Needed"},
238 {"type": "Input.Text", "id": "c"}
239 ]));
240 let errors = collect_input_values(&parsed, |input| {
241 if input.id == "c" {
242 "x".into()
243 } else {
244 String::new()
245 }
246 })
247 .unwrap_err();
248 assert_eq!(errors.len(), 2);
249 assert_eq!(errors[0].id, "a");
250 assert_eq!(errors[1].message, "Needed");
251 let collected = collect_input_values(&parsed, |input| format!("v-{}", input.id)).unwrap();
252 assert_eq!(
253 Value::Object(collected),
254 json!({"a": "v-a", "b": "v-b", "c": "v-c"})
255 );
256}
257
258#[test]
259fn merge_keeps_string_data_and_builds_objects_otherwise() {
260 let inputs = values(json!({"a": "1"}));
261 assert_eq!(
262 merge_input_data(&json!({"k": 1, "a": "old"}), &inputs),
263 json!({"k": 1, "a": "1"})
264 );
265 assert_eq!(merge_input_data(&Value::Null, &inputs), json!({"a": "1"}));
266 assert_eq!(merge_input_data(&json!("plain"), &inputs), json!("plain"));
267}
268
269#[test]
270fn submit_payload_carries_the_merged_inputs() {
271 let action = submit(json!({"action": "save"}), None);
272 assert!(action.collects_inputs);
273 let payload = action
274 .with_inputs(&values(json!({"name": "Ada"})))
275 .invoke_payload()
276 .unwrap();
277 assert_eq!(payload.name, "messageback");
278 assert_eq!(payload.value, json!({"action": "save", "name": "Ada"}));
279}
280
281#[test]
282fn submit_without_data_becomes_the_input_object() {
283 let action = card(
284 json!([{"type": "TextBlock", "text": "x"}]),
285 json!([{"type": "Action.Submit", "title": "Go"}]),
286 )
287 .actions
288 .remove(0);
289 let payload = action
290 .with_inputs(&values(json!({"name": "Ada"})))
291 .invoke_payload()
292 .unwrap();
293 assert_eq!(payload.value, json!({"name": "Ada"}));
294}
295
296#[test]
297fn submit_with_string_data_ignores_the_inputs() {
298 let action = submit(json!("go"), None);
299 let payload = action
300 .with_inputs(&values(json!({"name": "Ada"})))
301 .invoke_payload()
302 .unwrap();
303 assert_eq!(payload.value, json!("go"));
304}
305
306#[test]
307fn associated_inputs_none_is_parsed() {
308 assert!(!submit(json!({}), Some("none")).collects_inputs);
309 assert!(submit(json!({}), Some("auto")).collects_inputs);
310}
311
312#[test]
313fn message_back_sends_the_merged_object_as_value() {
314 let action = submit(
315 json!({"id": 7, "msteams": {"type": "messageBack", "text": "hi", "value": "old"}}),
316 None,
317 );
318 let payload = action
319 .with_inputs(&values(json!({"name": "Ada"})))
320 .invoke_payload()
321 .unwrap();
322 assert_eq!(payload.value, json!({"id": 7, "name": "Ada"}));
323 let without = action
324 .with_inputs(&values(json!({})))
325 .invoke_payload()
326 .unwrap();
327 assert_eq!(without.value, json!("old"));
328}
329
330#[test]
331fn task_fetch_merges_inputs_and_drops_the_settings() {
332 let action = submit(json!({"msteams": {"type": "task/fetch"}, "k": 1}), None);
333 let payload = action
334 .with_inputs(&values(json!({"name": "Ada"})))
335 .invoke_payload()
336 .unwrap();
337 assert_eq!(payload.name, "task/fetch");
338 assert_eq!(
339 payload.value,
340 json!({"data": {"k": 1, "name": "Ada", "type": "task/fetch"}, "context": {"theme": "dark"}})
341 );
342}
343
344#[test]
345fn execute_merges_inputs_into_the_action_data() {
346 let action = card(
347 json!([{"type": "TextBlock", "text": "x"}]),
348 json!([{"type": "Action.Execute", "title": "Go", "verb": "save", "data": {"k": 1}}]),
349 )
350 .actions
351 .remove(0);
352 let sent = action.with_inputs(&values(json!({"name": "Ada"})));
353 let CardActionKind::Execute(execute) = &sent.kind else {
354 panic!("execute expected");
355 };
356 assert_eq!(execute.data, json!({"k": 1, "name": "Ada"}));
357 let payload = sent.invoke_payload().unwrap();
358 assert_eq!(
359 payload.value["action"]["data"],
360 json!({"k": 1, "name": "Ada"})
361 );
362}