BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / tests / wake.rs

wake.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
wake.rs 4.2 KiB Download Raw
1use std::collections::VecDeque;
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4
5use futures_util::{SinkExt, StreamExt};
6use serde_json::{Value, json};
7use session::{Method, Scope, Session, SessionConfig};
8use tokio::io::{AsyncReadExt, AsyncWriteExt};
9use tokio::net::{TcpListener, TcpStream};
10use tokio_tungstenite::tungstenite::Message;
11
12type Calls = Arc<Mutex<Vec<(String, Value)>>>;
13type Script = Arc<Mutex<VecDeque<Value>>>;
14
15async fn start_browser(tab_url: &'static str, outcomes: Vec<Value>) -> (String, Calls) {
16 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
17 let port = listener.local_addr().unwrap().port();
18 let calls: Calls = Arc::new(Mutex::new(Vec::new()));
19 let script: Script = Arc::new(Mutex::new(outcomes.into()));
20 let seen = calls.clone();
21 tokio::spawn(async move {
22 loop {
23 let (stream, _) = listener.accept().await.unwrap();
24 tokio::spawn(serve(stream, port, tab_url, script.clone(), seen.clone()));
25 }
26 });
27 (format!("http://127.0.0.1:{port}"), calls)
28}
29
30async fn serve(
31 mut stream: TcpStream,
32 port: u16,
33 tab_url: &'static str,
34 script: Script,
35 calls: Calls,
36) {
37 let mut peek = [0u8; 16];
38 let count = stream.peek(&mut peek).await.unwrap();
39 if !peek[..count].starts_with(b"GET /json") {
40 let mut websocket = tokio_tungstenite::accept_async(stream).await.unwrap();
41 while let Some(Ok(Message::Text(text))) = websocket.next().await {
42 let call: Value = serde_json::from_str(text.as_str()).unwrap();
43 let method = call["method"].as_str().unwrap().to_owned();
44 calls
45 .lock()
46 .unwrap()
47 .push((method.clone(), call["params"].clone()));
48 let result = if method == "Runtime.evaluate" {
49 let outcome = script
50 .lock()
51 .unwrap()
52 .pop_front()
53 .expect("script exhausted");
54 json!({"result": {"type": "object", "value": outcome}})
55 } else {
56 json!({})
57 };
58 websocket
59 .send(Message::text(
60 json!({"id": call["id"], "result": result}).to_string(),
61 ))
62 .await
63 .unwrap();
64 }
65 return;
66 }
67 let mut discard = [0u8; 1024];
68 let _ = stream.read(&mut discard).await.unwrap();
69 let targets = json!([{"type": "page", "url": tab_url, "webSocketDebuggerUrl": format!("ws://127.0.0.1:{port}/devtools/page/0")}]);
70 let body = targets.to_string();
71 let response = format!(
72 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
73 body.len()
74 );
75 stream.write_all(response.as_bytes()).await.unwrap();
76}
77
78fn fast_config() -> SessionConfig {
79 SessionConfig {
80 token_wait: Duration::from_secs(2),
81 token_poll: Duration::from_millis(20),
82 ..SessionConfig::default()
83 }
84}
85
86async fn navigations(tab_url: &'static str) -> Vec<(String, Value)> {
87 let missing = json!({"noToken": true, "refreshError": "invalid_grant"});
88 let ok = json!({"results": [{"status": 200, "body": {"ok": true}}]});
89 let (endpoint, calls) = start_browser(tab_url, vec![missing, ok]).await;
90 let session = Session::connect_with(&endpoint, fast_config())
91 .await
92 .unwrap();
93 session
94 .request(
95 Method::Get,
96 "https://graph.microsoft.com/v1.0/me",
97 &Scope::graph("User.Read"),
98 None,
99 )
100 .await
101 .unwrap();
102 let recorded = calls.lock().unwrap().clone();
103 recorded
104 .into_iter()
105 .filter(|(method, _)| method == "Page.navigate" || method == "Page.reload")
106 .collect()
107}
108
109#[tokio::test]
110async fn parked_tab_is_woken_by_navigating_to_the_start_url() {
111 let wake = navigations("https://teams.cloud.microsoft/robots.txt").await;
112 assert_eq!(wake.len(), 1);
113 assert_eq!(wake[0].0, "Page.navigate");
114 assert_eq!(wake[0].1["url"], "https://teams.cloud.microsoft/");
115}
116
117#[tokio::test]
118async fn live_app_tab_is_reloaded() {
119 let wake = navigations("https://teams.cloud.microsoft/v2/").await;
120 assert_eq!(wake.len(), 1);
121 assert_eq!(wake[0].0, "Page.reload");
122}