BlueGit

ict rusty-teams

Files

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

adaptive_card.rs

adaptive_card.rs 21.1 KiB Download Raw
1use serde_json::json;
2use teams_core::{
3 AdaptiveCard, CardAction, CardActionIcon, CardActionKind, CardElement, ColumnWidth,
4 ExecuteTrigger, IconSize, ImageSize, Span, TextColor, TextSize, ToggleTarget,
5 VerticalAlignment, card_content_text,
6};
7
8fn digest_card() -> String {
9 json!({
10 "type": "AdaptiveCard",
11 "msTeams": {"width": "Full"},
12 "body": [
13 {"type": "ColumnSet", "columns": [
14 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
15 {"type": "Image", "url": "https://img.example.com/person.png", "size": "small", "style": "person", "height": "32px"}
16 ]},
17 {"type": "Column", "width": "stretch", "items": [
18 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Ada Example edited your page"}
19 ]}
20 ]},
21 {"type": "ColumnSet", "separator": true, "columns": [
22 {"type": "Column", "width": "40px", "items": [
23 {"type": "Image", "url": "https://img.example.com/page.png", "width": "24px", "height": "24px"}
24 ]},
25 {"type": "Column", "width": 2, "items": [
26 {"type": "TextBlock", "weight": "bolder", "wrap": true, "color": "accent", "text": "[**Quarterly Plan**](https://example.com/wiki/plan) in [**Product Space**](https://example.com/wiki/space)"},
27 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "text": "Owned by: Ada Example"}
28 ]}
29 ]},
30 {"type": "ActionSet", "actions": [
31 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/plan"},
32 {"type": "Action.OpenUrl", "title": "Unsafe", "url": "javascript:alert(1)"},
33 {"type": "Action.Submit", "title": "Watch", "data": {"action": "watch"}},
34 {"type": "Action.Submit", "title": "Hidden", "isVisible": false}
35 ]}
36 ]
37 })
38 .to_string()
39}
40
41#[test]
42fn digest_card_keeps_layout_text_and_actions() {
43 let card = AdaptiveCard::parse(&digest_card()).unwrap();
44 assert!(card.full_width);
45 assert_eq!(card.items.len(), 3);
46
47 let CardElement::Columns { columns, .. } = &card.items[0].element else {
48 panic!("first item is a column set");
49 };
50 assert_eq!(columns[0].width, ColumnWidth::Auto);
51 assert_eq!(columns[0].layout.vertical_alignment, VerticalAlignment::Center);
52 let CardElement::Image(image) = &columns[0].items[0].element else {
53 panic!("avatar column holds an image");
54 };
55 assert!(image.person);
56 assert_eq!(image.size, ImageSize::Small);
57 assert_eq!(image.height, Some(32.));
58 let CardElement::Text(title) = &columns[1].items[0].element else {
59 panic!("title column holds text");
60 };
61 assert!(title.bold && title.wrap);
62 assert_eq!(title.size, TextSize::Medium);
63
64 assert!(card.items[1].separator);
65 let CardElement::Columns { columns, .. } = &card.items[1].element else {
66 panic!("second item is a column set");
67 };
68 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
69 assert_eq!(columns[1].width, ColumnWidth::Weighted(2.));
70 let CardElement::Text(line) = &columns[1].items[0].element else {
71 panic!("text expected");
72 };
73 assert_eq!(line.color, TextColor::Accent);
74 assert_eq!(
75 line.spans[0],
76 Span::Link {
77 url: "https://example.com/wiki/plan".to_owned(),
78 children: vec![Span::Bold(vec![Span::Text("Quarterly Plan".to_owned())])],
79 }
80 );
81 let CardElement::Text(owner) = &columns[1].items[1].element else {
82 panic!("text expected");
83 };
84 assert!(owner.subtle);
85
86 let CardElement::Actions(actions) = &card.items[2].element else {
87 panic!("third item is an action set");
88 };
89 assert_eq!(actions.len(), 3);
90 assert_eq!(
91 actions[0].kind,
92 CardActionKind::OpenUrl("https://example.com/wiki/plan".to_owned())
93 );
94 assert_eq!(actions[1].kind, CardActionKind::Unsupported);
95 assert_eq!(actions[2].title, "Watch");
96 let CardActionKind::Submit(submit) = &actions[2].kind else {
97 panic!("watch is a submit action");
98 };
99 assert_eq!(submit.data, json!({"action": "watch"}));
100 assert!(actions[2].is_clickable());
101}
102
103fn card_actions(actions: serde_json::Value) -> Vec<CardAction> {
104 let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": actions});
105 AdaptiveCard::parse(&card.to_string()).unwrap().actions
106}
107
108#[test]
109fn plain_submit_sends_its_data_as_a_message_back() {
110 let actions = card_actions(json!([
111 {"type": "Action.Submit", "title": "Unwatch", "data": {"type": "unwatch", "page": "p1"}}
112 ]));
113 let payload = actions[0].invoke_payload().unwrap();
114 assert_eq!(payload.name, "messageback");
115 assert_eq!(payload.value, json!({"type": "unwatch", "page": "p1"}));
116}
117
118#[test]
119fn task_fetch_submit_wraps_data_without_the_teams_settings() {
120 let actions = card_actions(json!([
121 {"type": "Action.Submit", "title": "Bell", "data": {"cardType": "n", "msteams": {"type": "task/fetch"}}}
122 ]));
123 let payload = actions[0].invoke_payload().unwrap();
124 assert_eq!(payload.name, "task/fetch");
125 assert_eq!(
126 payload.value,
127 json!({"data": {"cardType": "n", "type": "task/fetch"}, "context": {"theme": "dark"}})
128 );
129}
130
131#[test]
132fn message_back_and_im_back_send_the_teams_value() {
133 let actions = card_actions(json!([
134 {"type": "Action.Submit", "title": "A", "data": {"msteams": {"type": "messageBack", "value": {"k": 1}}}},
135 {"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}
136 ]));
137 let first = actions[0].invoke_payload().unwrap();
138 assert_eq!(
139 (first.name.as_str(), first.value),
140 ("messageback", json!({"k": 1}))
141 );
142 let second = actions[1].invoke_payload().unwrap();
143 assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));
144}
145
146#[test]
147fn execute_action_carries_verb_id_and_data() {
148 let actions = card_actions(json!([
149 {"type": "Action.Execute", "id": "a1", "title": "Approve", "verb": "approve", "data": {"n": 3}},
150 {"type": "Action.Execute", "title": "No verb"}
151 ]));
152 let payload = actions[0].invoke_payload().unwrap();
153 assert_eq!(payload.name, "adaptiveCard/action");
154 assert_eq!(
155 payload.value,
156 json!({
157 "action": {"type": "Action.Execute", "id": "a1", "verb": "approve", "data": {"n": 3}},
158 "trigger": "manual"
159 })
160 );
161 assert_eq!(actions[1].kind, CardActionKind::Unsupported);
162}
163
164#[test]
165fn show_card_and_toggle_actions_are_parsed_locally() {
166 let actions = card_actions(json!([
167 {"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "TextBlock", "text": "nested"}]}},
168 {"type": "Action.ToggleVisibility", "title": "Toggle", "targetElements": ["a", {"elementId": "b", "isVisible": true}]},
169 {"type": "Action.ToggleVisibility", "title": "Empty", "targetElements": []}
170 ]));
171 let CardActionKind::ShowCard(nested) = &actions[0].kind else {
172 panic!("show card expected");
173 };
174 assert_eq!(nested.plain_text().as_deref(), Some("nested"));
175 assert!(actions[0].invoke_payload().is_none());
176 assert_eq!(
177 actions[1].kind,
178 CardActionKind::ToggleVisibility(vec![
179 ToggleTarget {
180 element_id: "a".to_owned(),
181 visible: None
182 },
183 ToggleTarget {
184 element_id: "b".to_owned(),
185 visible: Some(true)
186 },
187 ])
188 );
189 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
190}
191
192#[test]
193fn disabled_actions_stay_disabled_and_hidden_ones_need_an_id() {
194 let actions = card_actions(json!([
195 {"type": "Action.Submit", "title": "Off", "isEnabled": false, "data": {}},
196 {"type": "Action.Submit", "title": "Gone", "isVisible": false},
197 {"type": "Action.Submit", "title": "Later", "id": "later", "isVisible": false}
198 ]));
199 assert_eq!(actions.len(), 2);
200 assert!(!actions[0].is_clickable());
201 assert!(!actions[1].visible);
202 assert_eq!(actions[1].id.as_deref(), Some("later"));
203}
204
205#[test]
206fn toggled_items_keep_their_id_and_stay_out_of_the_text() {
207 let card = json!({"body": [
208 {"type": "TextBlock", "text": "shown"},
209 {"type": "TextBlock", "id": "details", "isVisible": false, "text": "secret"}
210 ]})
211 .to_string();
212 let parsed = AdaptiveCard::parse(&card).unwrap();
213 assert_eq!(parsed.items.len(), 2);
214 assert_eq!(parsed.items[1].id.as_deref(), Some("details"));
215 assert!(!parsed.items[1].visible);
216 assert_eq!(parsed.plain_text().as_deref(), Some("shown"));
217}
218
219#[test]
220fn plain_text_drops_urls_images_and_buttons() {
221 assert_eq!(
222 card_content_text(&digest_card()).unwrap(),
223 "Ada Example edited your page\nQuarterly Plan in Product Space\nOwned by: Ada Example"
224 );
225}
226
227#[test]
228fn hidden_and_unknown_elements_are_skipped_but_fallback_text_stays() {
229 let card = json!({
230 "body": [
231 {"type": "TextBlock", "text": "hidden", "isVisible": false},
232 {"type": "Carousel", "fallbackText": "Open the carousel elsewhere"},
233 {"type": "Carousel"},
234 {"type": "Image", "url": "http://insecure.example.com/a.png"},
235 {"type": "TextBlock", "text": "shown"}
236 ]
237 })
238 .to_string();
239 assert_eq!(
240 card_content_text(&card).unwrap(),
241 "Open the carousel elsewhere\nshown"
242 );
243}
244
245#[test]
246fn containers_fact_sets_and_rich_text_are_parsed() {
247 let card = json!({
248 "body": [
249 {"type": "Container", "style": "emphasis", "items": [
250 {"type": "RichTextBlock", "inlines": [
251 "plain ",
252 {"type": "TextRun", "text": "bold", "weight": "bolder"},
253 {"type": "TextRun", "text": " link", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/x"}}
254 ]},
255 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
256 {"type": "ImageSet", "imageSize": "medium", "images": [
257 {"type": "Image", "url": "https://img.example.com/a.png"}
258 ]}
259 ]}
260 ]
261 })
262 .to_string();
263 assert_eq!(
264 card_content_text(&card).unwrap(),
265 "plain bold link\nEnv: prod"
266 );
267}
268
269#[test]
270fn cards_without_content_are_none() {
271 assert!(AdaptiveCard::parse("not json").is_none());
272 assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());
273 assert!(AdaptiveCard::parse("[1]").is_none());
274}
275
276#[test]
277fn element_visibility_covers_items_actions_and_nested_cards() {
278 let card = json!({
279 "body": [
280 {"type": "TextBlock", "id": "title", "text": "t"},
281 {"type": "Container", "items": [
282 {"type": "TextBlock", "id": "details", "isVisible": false, "text": "d"}
283 ]},
284 {"type": "ActionSet", "actions": [
285 {"type": "Action.Submit", "id": "later", "isVisible": false, "title": "Later"},
286 {"type": "Action.ShowCard", "title": "More", "card": {"body": [
287 {"type": "TextBlock", "id": "nested", "isVisible": false, "text": "n"}
288 ]}}
289 ]}
290 ]
291 })
292 .to_string();
293 let visibility = AdaptiveCard::parse(&card).unwrap().element_visibility();
294 assert_eq!(visibility.len(), 4);
295 assert!(visibility["title"]);
296 assert!(!visibility["details"]);
297 assert!(!visibility["later"]);
298 assert!(!visibility["nested"]);
299}
300
301fn parse(card: serde_json::Value) -> AdaptiveCard {
302 AdaptiveCard::parse(&card.to_string()).unwrap()
303}
304
305fn refresh_card(user_ids: Option<serde_json::Value>) -> AdaptiveCard {
306 let mut refresh =
307 json!({"action": {"type": "Action.Execute", "verb": "refreshView", "data": {"k": 1}}});
308 if let Some(user_ids) = user_ids {
309 refresh["userIds"] = user_ids;
310 }
311 parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": refresh}))
312}
313
314#[test]
315fn refresh_parses_the_execute_action_and_user_ids() {
316 let card = refresh_card(Some(json!(["8:orgid:ABC"])));
317 let refresh = card.refresh.unwrap();
318 assert_eq!(refresh.action.verb, "refreshView");
319 assert_eq!(refresh.user_ids, Some(vec!["8:orgid:ABC".to_owned()]));
320 assert!(parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": {"action": {"type": "Action.OpenUrl", "url": "https://a.example"}}})).refresh.is_none());
321}
322
323#[test]
324fn refresh_runs_for_small_chats_without_user_ids() {
325 let refresh = refresh_card(None).refresh.unwrap();
326 assert!(refresh.runs_automatically(Some(2), None));
327 assert!(refresh.runs_automatically(Some(60), Some("8:orgid:me")));
328 assert!(!refresh.runs_automatically(Some(61), Some("8:orgid:me")));
329 assert!(!refresh.runs_automatically(None, Some("8:orgid:me")));
330}
331
332#[test]
333fn refresh_with_user_ids_runs_only_for_listed_users() {
334 let refresh = refresh_card(Some(json!(["8:orgid:ABC-1", "8:orgid:other"])))
335 .refresh
336 .unwrap();
337 assert!(refresh.runs_automatically(Some(500), Some("abc-1")));
338 assert!(refresh.runs_automatically(Some(500), Some("8:orgid:abc-1")));
339 assert!(!refresh.runs_automatically(Some(2), Some("8:orgid:nobody")));
340 assert!(!refresh.runs_automatically(Some(2), None));
341}
342
343#[test]
344fn execute_payload_carries_the_trigger() {
345 let refresh = refresh_card(None).refresh.unwrap();
346 assert_eq!(refresh.action.payload().value["trigger"], "manual");
347 let automatic = refresh.action.payload_for(ExecuteTrigger::Automatic);
348 assert_eq!(automatic.name, "adaptiveCard/action");
349 assert_eq!(automatic.value["trigger"], "automatic");
350}
351
352#[test]
353fn tab_info_and_sign_in_submits_open_a_url() {
354 let actions = card_actions(json!([
355 {"type": "Action.Submit", "title": "Tab", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c", "websiteUrl": "https://site.example/w", "name": "n", "entityId": "e"}}}}},
356 {"type": "Action.Submit", "title": "Tab content", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c"}}}}},
357 {"type": "Action.Submit", "title": "Tab bad", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"websiteUrl": "javascript:x"}}}}},
358 {"type": "Action.Submit", "title": "Sign in", "data": {"msteams": {"type": "signin", "value": "https://login.example/start"}}}
359 ]));
360 assert_eq!(
361 actions[0].kind,
362 CardActionKind::OpenUrl("https://site.example/w".into())
363 );
364 assert_eq!(
365 actions[1].kind,
366 CardActionKind::OpenUrl("https://content.example/c".into())
367 );
368 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
369 assert_eq!(
370 actions[3].kind,
371 CardActionKind::OpenUrl("https://login.example/start".into())
372 );
373}
374
375#[test]
376fn other_invoke_submits_send_the_value_named_by_its_type() {
377 let actions = card_actions(json!([
378 {"type": "Action.Submit", "title": "Go", "data": {"msteams": {"type": "invoke", "value": {"type": "custom/thing", "payload": 1}}}}
379 ]));
380 let payload = actions[0].invoke_payload().unwrap();
381 assert_eq!(payload.name, "custom/thing");
382 assert_eq!(payload.value, json!({"type": "custom/thing", "payload": 1}));
383}
384
385#[test]
386fn add_app_submits_stay_as_unavailable_buttons() {
387 let actions = card_actions(json!([
388 {"type": "Action.Submit", "title": "Add", "data": {"msteams": {"type": "invoke", "value": {"type": "appInstallToConversation"}}}},
389 {"type": "Action.Submit", "title": "Add 2", "data": {"msteams": {"type": "addAppToConversation"}}}
390 ]));
391 for action in &actions {
392 assert_eq!(
393 action.kind,
394 CardActionKind::Unavailable("Adding apps is not supported")
395 );
396 assert!(!action.is_clickable());
397 }
398}
399
400#[test]
401fn select_actions_are_parsed_on_card_image_container_and_column() {
402 let select = json!({"type": "Action.OpenUrl", "url": "https://a.example"});
403 let card = parse(json!({
404 "selectAction": select,
405 "body": [
406 {"type": "Image", "url": "https://img.example/a.png", "selectAction": {"type": "Action.Submit", "data": {"a": 1}}},
407 {"type": "Container", "selectAction": {"type": "Action.ToggleVisibility", "targetElements": ["x"]}, "items": [{"type": "TextBlock", "text": "t"}]},
408 {"type": "ColumnSet", "columns": [{"type": "Column", "selectAction": {"type": "Action.Execute", "verb": "v"}, "items": [{"type": "TextBlock", "text": "t"}]}]},
409 {"type": "Image", "url": "https://img.example/b.png", "selectAction": {"type": "Action.ShowCard", "card": {"body": [{"type": "TextBlock", "text": "t"}]}}}
410 ]
411 }));
412 assert!(matches!(
413 card.select_action.unwrap().kind,
414 CardActionKind::OpenUrl(_)
415 ));
416 let CardElement::Image(image) = &card.items[0].element else {
417 panic!("image")
418 };
419 assert!(matches!(
420 image.select_action.as_ref().unwrap().kind,
421 CardActionKind::Submit(_)
422 ));
423 let CardElement::Container { select_action, .. } = &card.items[1].element else {
424 panic!("container")
425 };
426 assert!(matches!(
427 select_action.as_ref().unwrap().kind,
428 CardActionKind::ToggleVisibility(_)
429 ));
430 let CardElement::Columns { columns, .. } = &card.items[2].element else {
431 panic!("columns")
432 };
433 assert!(matches!(
434 columns[0].select_action.as_ref().unwrap().kind,
435 CardActionKind::Execute(_)
436 ));
437 let CardElement::Image(image) = &card.items[3].element else {
438 panic!("image")
439 };
440 assert!(image.select_action.is_none());
441}
442
443#[test]
444fn media_takes_the_first_web_source_and_poster() {
445 let card = parse(json!({"body": [
446 {"type": "Media", "poster": "https://img.example/p.png", "altText": "Intro", "sources": [
447 {"mimeType": "video/mp4", "url": "ftp://x"}, {"mimeType": "video/mp4", "url": "https://v.example/a.mp4"}, {"url": "https://v.example/b.mp4"}
448 ]},
449 {"type": "Media", "sources": []},
450 {"type": "TextBlock", "text": "after"}
451 ]}));
452 assert_eq!(card.items.len(), 2);
453 let CardElement::Media(media) = &card.items[0].element else {
454 panic!("media")
455 };
456 assert_eq!(media.source_url, "https://v.example/a.mp4");
457 assert_eq!(
458 media.poster_url.as_deref(),
459 Some("https://img.example/p.png")
460 );
461 assert_eq!(media.alt_text.as_deref(), Some("Intro"));
462}
463
464#[test]
465fn icon_elements_and_action_icons_are_parsed() {
466 let card = parse(json!({
467 "body": [
468 {"type": "Icon", "name": "Calendar", "size": "xxLarge", "color": "accent", "style": "Filled", "selectAction": {"type": "Action.OpenUrl", "url": "https://a.example"}},
469 {"type": "Icon", "name": "Mail"}
470 ],
471 "actions": [
472 {"type": "Action.OpenUrl", "title": "A", "url": "https://a.example", "iconUrl": "icon:Send,Filled"},
473 {"type": "Action.OpenUrl", "title": "B", "url": "https://a.example", "iconUrl": "https://img.example/i.png"},
474 {"type": "Action.OpenUrl", "title": "C", "url": "https://a.example", "iconUrl": "data:image/png;base64,AA"}
475 ]
476 }));
477 let CardElement::Icon(icon) = &card.items[0].element else {
478 panic!("icon")
479 };
480 assert_eq!(
481 (icon.name.as_str(), icon.size, icon.color, icon.filled),
482 (
483 "Calendar",
484 IconSize::ExtraExtraLarge,
485 TextColor::Accent,
486 true
487 )
488 );
489 assert!(icon.select_action.is_some());
490 let CardElement::Icon(plain) = &card.items[1].element else {
491 panic!("icon")
492 };
493 assert_eq!((plain.size, plain.filled), (IconSize::Standard, false));
494 assert_eq!(
495 card.actions[0].icon,
496 Some(CardActionIcon::Named("Send".into()))
497 );
498 assert_eq!(
499 card.actions[1].icon,
500 Some(CardActionIcon::Url("https://img.example/i.png".into()))
501 );
502 assert_eq!(card.actions[2].icon, None);
503}
504
505#[test]
506fn mentions_and_italic_survive_in_text_fact_and_rich_text() {
507 let card = parse(json!({"body": [
508 {"type": "TextBlock", "text": "Hi <at>Ada</at>, this is _soft_ and snake_case_x"},
509 {"type": "FactSet", "facts": [{"title": "Owner", "value": "<at>Bob</at>"}]},
510 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "cc <at>Cy</at>", "weight": "bolder"}]}
511 ]}));
512 let CardElement::Text(text) = &card.items[0].element else {
513 panic!("text")
514 };
515 assert!(text.spans.contains(&Span::Mention {
516 name: "Ada".into(),
517 id: None
518 }));
519 assert!(
520 text.spans
521 .contains(&Span::Italic(vec![Span::Text("soft".into())]))
522 );
523 let CardElement::Facts(facts) = &card.items[1].element else {
524 panic!("facts")
525 };
526 assert_eq!(
527 facts[0].value,
528 vec![Span::Mention {
529 name: "Bob".into(),
530 id: None
531 }]
532 );
533 let CardElement::Text(rich) = &card.items[2].element else {
534 panic!("rich")
535 };
536 assert_eq!(
537 rich.spans,
538 vec![Span::Bold(vec![
539 Span::Text("cc ".into()),
540 Span::Mention {
541 name: "Cy".into(),
542 id: None
543 }
544 ])]
545 );
546}