victauri-test 0.1.0

Test assertion helpers for Victauri-powered Tauri app testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use serde_json::{Value, json};

use crate::error::TestError;

/// Typed HTTP client for the Victauri MCP server.
///
/// Manages session lifecycle (initialize → tool calls → cleanup) and provides
/// convenient methods for common test operations.
pub struct VictauriClient {
    http: reqwest::Client,
    base_url: String,
    session_id: String,
    next_id: u64,
}

impl VictauriClient {
    /// Connect to a Victauri MCP server on the given port.
    /// Sends `initialize` and `notifications/initialized` automatically.
    pub async fn connect(port: u16) -> Result<Self, TestError> {
        Self::connect_with_token(port, None).await
    }

    /// Connect with an optional Bearer auth token.
    pub async fn connect_with_token(port: u16, token: Option<&str>) -> Result<Self, TestError> {
        let base_url = format!("http://127.0.0.1:{port}");
        let http = reqwest::Client::new();

        let mut init_req = http
            .post(format!("{base_url}/mcp"))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json, text/event-stream")
            .json(&json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2025-03-26",
                    "capabilities": {},
                    "clientInfo": {"name": "victauri-test", "version": env!("CARGO_PKG_VERSION")}
                }
            }));

        if let Some(t) = token {
            init_req = init_req.header("Authorization", format!("Bearer {t}"));
        }

        let init_resp = init_req
            .send()
            .await
            .map_err(|e| TestError::Connection(e.to_string()))?;

        if !init_resp.status().is_success() {
            return Err(TestError::Connection(format!(
                "initialize returned {}",
                init_resp.status()
            )));
        }

        let session_id = init_resp
            .headers()
            .get("mcp-session-id")
            .and_then(|v| v.to_str().ok())
            .ok_or_else(|| TestError::Connection("no mcp-session-id header".into()))?
            .to_string();

        let mut notify_req = http
            .post(format!("{base_url}/mcp"))
            .header("Content-Type", "application/json")
            .header("mcp-session-id", &session_id)
            .json(&json!({
                "jsonrpc": "2.0",
                "method": "notifications/initialized"
            }));

        if let Some(t) = token {
            notify_req = notify_req.header("Authorization", format!("Bearer {t}"));
        }

        notify_req.send().await?;

        Ok(Self {
            http,
            base_url,
            session_id,
            next_id: 10,
        })
    }

    /// Call an MCP tool by name and return the result content as JSON.
    pub async fn call_tool(&mut self, name: &str, arguments: Value) -> Result<Value, TestError> {
        let id = self.next_id;
        self.next_id += 1;

        let resp = self
            .http
            .post(format!("{}/mcp", self.base_url))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json, text/event-stream")
            .header("mcp-session-id", &self.session_id)
            .json(&json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": "tools/call",
                "params": {
                    "name": name,
                    "arguments": arguments
                }
            }))
            .send()
            .await?;

        let body: Value = resp.json().await?;

        if let Some(error) = body.get("error") {
            return Err(TestError::Mcp {
                code: error["code"].as_i64().unwrap_or(-1),
                message: error["message"].as_str().unwrap_or("unknown").to_string(),
            });
        }

        let content = &body["result"]["content"];
        if let Some(arr) = content.as_array()
            && let Some(first) = arr.first()
            && let Some(text) = first["text"].as_str()
        {
            if let Ok(parsed) = serde_json::from_str::<Value>(text) {
                return Ok(parsed);
            }
            return Ok(Value::String(text.to_string()));
        }

        Ok(body)
    }

    /// Evaluate JavaScript in the webview and return the result.
    pub async fn eval_js(&mut self, code: &str) -> Result<Value, TestError> {
        self.call_tool("eval_js", json!({"code": code})).await
    }

    /// Get a DOM snapshot of the current page.
    pub async fn dom_snapshot(&mut self) -> Result<Value, TestError> {
        self.call_tool("dom_snapshot", json!({})).await
    }

    /// Click an element by ref handle ID.
    pub async fn click(&mut self, ref_id: &str) -> Result<Value, TestError> {
        self.call_tool("click", json!({"ref_id": ref_id})).await
    }

    /// Fill an input element with a value.
    pub async fn fill(&mut self, ref_id: &str, value: &str) -> Result<Value, TestError> {
        self.call_tool("fill", json!({"ref_id": ref_id, "value": value}))
            .await
    }

    /// Type text into an element character by character.
    pub async fn type_text(&mut self, ref_id: &str, text: &str) -> Result<Value, TestError> {
        self.call_tool("type_text", json!({"ref_id": ref_id, "text": text}))
            .await
    }

    /// List all window labels.
    pub async fn list_windows(&mut self) -> Result<Value, TestError> {
        self.call_tool("list_windows", json!({})).await
    }

    /// Get the state of a specific window (or all windows).
    pub async fn get_window_state(&mut self, label: Option<&str>) -> Result<Value, TestError> {
        let args = match label {
            Some(l) => json!({"label": l}),
            None => json!({}),
        };
        self.call_tool("get_window_state", args).await
    }

    /// Take a screenshot and return base64-encoded PNG.
    pub async fn screenshot(&mut self) -> Result<Value, TestError> {
        self.call_tool("screenshot", json!({})).await
    }

    /// Invoke a Tauri command by name with optional arguments.
    pub async fn invoke_command(
        &mut self,
        command: &str,
        args: Option<Value>,
    ) -> Result<Value, TestError> {
        let mut params = json!({"command": command});
        if let Some(a) = args {
            params["args"] = a;
        }
        self.call_tool("invoke_command", params).await
    }

    /// Get the IPC call log.
    pub async fn get_ipc_log(&mut self, limit: Option<usize>) -> Result<Value, TestError> {
        let args = match limit {
            Some(n) => json!({"limit": n}),
            None => json!({}),
        };
        self.call_tool("get_ipc_log", args).await
    }

    /// Verify frontend state against backend state.
    pub async fn verify_state(
        &mut self,
        frontend_expr: &str,
        backend_state: Value,
    ) -> Result<Value, TestError> {
        self.call_tool(
            "verify_state",
            json!({
                "frontend_expr": frontend_expr,
                "backend_state": backend_state,
            }),
        )
        .await
    }

    /// Detect ghost commands (registered but never called, or called but not registered).
    pub async fn detect_ghost_commands(&mut self) -> Result<Value, TestError> {
        self.call_tool("detect_ghost_commands", json!({})).await
    }

    /// Check IPC call health (pending, stale, errored).
    pub async fn check_ipc_integrity(&mut self) -> Result<Value, TestError> {
        self.call_tool("check_ipc_integrity", json!({})).await
    }

    /// Run a semantic assertion against a JS expression.
    pub async fn assert_semantic(
        &mut self,
        expression: &str,
        label: &str,
        condition: &str,
        expected: Value,
    ) -> Result<Value, TestError> {
        self.call_tool(
            "assert_semantic",
            json!({
                "expression": expression,
                "label": label,
                "condition": condition,
                "expected": expected,
            }),
        )
        .await
    }

    /// Run an accessibility audit.
    pub async fn audit_accessibility(&mut self) -> Result<Value, TestError> {
        self.call_tool("audit_accessibility", json!({})).await
    }

    /// Get performance metrics (timing, heap, resources).
    pub async fn get_performance_metrics(&mut self) -> Result<Value, TestError> {
        self.call_tool("get_performance_metrics", json!({})).await
    }

    /// Get the command registry.
    pub async fn get_registry(&mut self) -> Result<Value, TestError> {
        self.call_tool("get_registry", json!({})).await
    }

    /// Get process memory statistics.
    pub async fn get_memory_stats(&mut self) -> Result<Value, TestError> {
        self.call_tool("get_memory_stats", json!({})).await
    }

    /// Read plugin info (version, uptime, tool count).
    pub async fn get_plugin_info(&mut self) -> Result<Value, TestError> {
        self.call_tool("get_plugin_info", json!({})).await
    }

    /// Wait for a JS condition to become truthy, polling at an interval.
    pub async fn wait_for(
        &mut self,
        condition: &str,
        timeout_ms: Option<u64>,
        interval_ms: Option<u64>,
    ) -> Result<Value, TestError> {
        let mut args = json!({"condition": condition});
        if let Some(t) = timeout_ms {
            args["timeout_ms"] = json!(t);
        }
        if let Some(i) = interval_ms {
            args["interval_ms"] = json!(i);
        }
        self.call_tool("wait_for", args).await
    }

    /// Start a time-travel recording session.
    pub async fn start_recording(&mut self, session_id: Option<&str>) -> Result<Value, TestError> {
        let args = match session_id {
            Some(id) => json!({"session_id": id}),
            None => json!({}),
        };
        self.call_tool("start_recording", args).await
    }

    /// Stop the recording and return the session.
    pub async fn stop_recording(&mut self) -> Result<Value, TestError> {
        self.call_tool("stop_recording", json!({})).await
    }

    /// Export the current recording session as JSON.
    pub async fn export_session(&mut self) -> Result<Value, TestError> {
        self.call_tool("export_session", json!({})).await
    }

    /// Get the server base URL.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Get the MCP session ID.
    pub fn session_id(&self) -> &str {
        &self.session_id
    }
}

// ── Assertion Helpers ────────────────────────────────────────────────────────

/// Assert that a JSON value at the given pointer equals the expected value.
///
/// ```rust,ignore
/// let state = client.get_window_state(Some("main")).await?;
/// victauri_test::assert_json_eq(&state, "/visible", &json!(true));
/// ```
pub fn assert_json_eq(value: &Value, pointer: &str, expected: &Value) {
    let actual = value.pointer(pointer);
    assert!(
        actual == Some(expected),
        "JSON pointer {pointer}: expected {expected}, got {}",
        actual.map_or("missing".to_string(), |v| v.to_string())
    );
}

/// Assert that a JSON value at the given pointer is truthy (not null/false/0/"").
pub fn assert_json_truthy(value: &Value, pointer: &str) {
    let actual = value.pointer(pointer);
    let is_truthy = match actual {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(Value::Number(n)) => n.as_f64().unwrap_or(0.0) != 0.0,
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Array(a)) => !a.is_empty(),
        Some(Value::Object(_)) => true,
    };
    assert!(
        is_truthy,
        "JSON pointer {pointer}: expected truthy, got {}",
        actual.map_or("missing".to_string(), |v| v.to_string())
    );
}

/// Assert that an accessibility audit has zero violations.
pub fn assert_no_a11y_violations(audit: &Value) {
    let violations = audit
        .pointer("/summary/violations")
        .and_then(|v| v.as_u64())
        .unwrap_or(u64::MAX);
    assert_eq!(
        violations, 0,
        "expected 0 accessibility violations, got {violations}"
    );
}

/// Assert that all performance metrics are within budget.
pub fn assert_performance_budget(metrics: &Value, max_load_ms: f64, max_heap_mb: f64) {
    if let Some(load) = metrics
        .pointer("/navigation/load_event_end")
        .and_then(|v| v.as_f64())
    {
        assert!(
            load <= max_load_ms,
            "load event took {load}ms, budget is {max_load_ms}ms"
        );
    }

    if let Some(heap) = metrics.pointer("/js_heap/used_mb").and_then(|v| v.as_f64()) {
        assert!(
            heap <= max_heap_mb,
            "JS heap is {heap}MB, budget is {max_heap_mb}MB"
        );
    }
}

/// Assert that IPC integrity is healthy (no stale or errored calls).
pub fn assert_ipc_healthy(integrity: &Value) {
    let healthy = integrity
        .get("healthy")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    assert!(
        healthy,
        "IPC integrity check failed: {}",
        serde_json::to_string_pretty(integrity).unwrap_or_default()
    );
}

/// Assert that state verification passed with no divergences.
pub fn assert_state_matches(verification: &Value) {
    let passed = verification
        .get("passed")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    assert!(
        passed,
        "state verification failed: {}",
        serde_json::to_string_pretty(verification).unwrap_or_default()
    );
}