cdp-server 0.1.0

Generic CDP (Chrome DevTools Protocol) server framework
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
413
414
415
416
417
418
419
// @trace TEST-CDS-001 [req:REQ-CDS-001] [level:unit]
// @trace TEST-CDS-002 [req:REQ-CDS-004] [level:unit]
// @trace TEST-CDS-003 [req:REQ-CDS-001] [level:unit]
// @trace TEST-CDS-004 [req:REQ-CDS-002] [level:unit]
// @trace TEST-CDS-005 [req:REQ-CDS-005] [level:unit]

use cdp_server::{CdpError, DomainHandler, DomainRegistry, EventSender, ServerConfig, TargetInfo};
use cdp_server::{CdpEvent, CdpMessage, CdpResponse};
use serde_json::{json, Value};

// ---------------------------------------------------------------------------
// Stub EventSender for tests
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct NoopEventSender;

impl EventSender for NoopEventSender {
    fn send_event(&self, _method: &str, _params: Value) {}
}

// ---------------------------------------------------------------------------
// Stub DomainHandler for tests
// ---------------------------------------------------------------------------

struct EchoHandler;

impl DomainHandler for EchoHandler {
    fn domain_name(&self) -> &'static str {
        "Echo"
    }
    fn handle_command(
        &self,
        command: &str,
        params: Value,
        _es: &dyn EventSender,
    ) -> Result<Value, CdpError> {
        match command {
            "Echo.ping" => Ok(json!({ "pong": true })),
            "Echo.reflect" => Ok(json!({ "echo": params })),
            _ => Err(CdpError {
                code: -32601,
                message: format!("'{}' wasn't found", command),
            }),
        }
    }
}

struct StatefulHandler {
    name: &'static str,
}

impl DomainHandler for StatefulHandler {
    fn domain_name(&self) -> &'static str {
        self.name
    }
    fn handle_command(
        &self,
        command: &str,
        _params: Value,
        _es: &dyn EventSender,
    ) -> Result<Value, CdpError> {
        Ok(json!({ "domain": self.name, "command": command }))
    }
    fn on_session_created(&self, session_id: &str) {
        let _ = session_id;
    }
    fn on_session_destroyed(&self, session_id: &str) {
        let _ = session_id;
    }
}

// ---------------------------------------------------------------------------
// TestDispatch — enum dispatch for multi-handler tests
// ---------------------------------------------------------------------------

enum TestDispatch {
    Echo(EchoHandler),
    Stateful(StatefulHandler),
}

impl DomainHandler for TestDispatch {
    fn domain_name(&self) -> &'static str {
        match self {
            Self::Echo(h) => h.domain_name(),
            Self::Stateful(h) => h.domain_name(),
        }
    }
    fn handle_command(
        &self,
        cmd: &str,
        params: Value,
        sender: &dyn EventSender,
    ) -> Result<Value, CdpError> {
        match self {
            Self::Echo(h) => h.handle_command(cmd, params, sender),
            Self::Stateful(h) => h.handle_command(cmd, params, sender),
        }
    }
    fn on_session_created(&self, session_id: &str) {
        match self {
            Self::Echo(h) => h.on_session_created(session_id),
            Self::Stateful(h) => h.on_session_created(session_id),
        }
    }
    fn on_session_destroyed(&self, session_id: &str) {
        match self {
            Self::Echo(h) => h.on_session_destroyed(session_id),
            Self::Stateful(h) => h.on_session_destroyed(session_id),
        }
    }
}

// ===========================================================================
// §1 Protocol parsing tests (TEST-CDS-001)
// ===========================================================================

fn parse_msg(raw: &str) -> Option<CdpMessage> {
    serde_json::from_str(raw).ok()
}

#[test]
fn test_parse_valid_message() {
    let msg =
        parse_msg(r#"{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}"#)
            .unwrap();
    assert_eq!(msg.id, Some(1));
    assert_eq!(msg.method, "Page.navigate");
    assert_eq!(
        msg.params.as_ref().unwrap().get("url").unwrap().as_str(),
        Some("https://example.com")
    );
}

#[test]
fn test_parse_message_without_params() {
    let msg = parse_msg(r#"{"id":42,"method":"Page.enable"}"#).unwrap();
    assert_eq!(msg.id, Some(42));
    assert_eq!(msg.method, "Page.enable");
    assert!(msg.params.is_none());
}

#[test]
fn test_parse_message_without_id() {
    let msg = parse_msg(r#"{"method":"Runtime.consoleAPICalled","params":{}}"#).unwrap();
    assert!(msg.id.is_none());
    assert_eq!(msg.method, "Runtime.consoleAPICalled");
}

#[test]
fn test_parse_invalid_json_returns_none() {
    assert!(parse_msg("not json at all").is_none());
    assert!(parse_msg("").is_none());
    assert!(parse_msg("{{{invalid").is_none());
}

#[test]
fn test_parse_with_session_id() {
    let msg = parse_msg(r#"{"id":1,"method":"Runtime.evaluate","sessionId":"abc123"}"#).unwrap();
    assert_eq!(msg.session_id.as_deref(), Some("abc123"));
}

// ===========================================================================
// §2 DomainRegistry tests (TEST-CDS-002 / REQ-CDS-004)
// ===========================================================================

#[test]
fn test_registry_register_and_dispatch() {
    let registry = DomainRegistry::<TestDispatch>::new();
    registry.register(TestDispatch::Echo(EchoHandler)).unwrap();

    let es = NoopEventSender;
    let result = registry.dispatch_command("Echo.ping", json!({}), &es);
    assert!(result.is_some());
    let value = result.unwrap().unwrap();
    assert_eq!(value["pong"], true);
}

#[test]
fn test_registry_duplicate_registration_fails() {
    let registry = DomainRegistry::<TestDispatch>::new();
    registry.register(TestDispatch::Echo(EchoHandler)).unwrap();
    let err = registry.register(TestDispatch::Echo(EchoHandler));
    assert!(err.is_err());
    assert!(err.unwrap_err().contains("already registered"));
}

#[test]
fn test_registry_unknown_domain_returns_none() {
    let registry = DomainRegistry::<TestDispatch>::new();
    let es = NoopEventSender;
    assert!(registry
        .dispatch_command("Unknown.method", json!({}), &es)
        .is_none());
}

#[test]
fn test_registry_has_domain() {
    let registry = DomainRegistry::<TestDispatch>::new();
    assert!(!registry.has_domain("Echo"));
    registry.register(TestDispatch::Echo(EchoHandler)).unwrap();
    assert!(registry.has_domain("Echo"));
}

#[test]
fn test_registry_multiple_domains() {
    let registry = DomainRegistry::<TestDispatch>::new();
    registry
        .register(TestDispatch::Stateful(StatefulHandler { name: "Page" }))
        .unwrap();
    registry
        .register(TestDispatch::Stateful(StatefulHandler { name: "Runtime" }))
        .unwrap();
    registry
        .register(TestDispatch::Stateful(StatefulHandler { name: "DOM" }))
        .unwrap();

    let es = NoopEventSender;

    let result = registry
        .dispatch_command("Page.navigate", json!({}), &es)
        .unwrap()
        .unwrap();
    assert_eq!(result["domain"], "Page");

    let result = registry
        .dispatch_command("Runtime.evaluate", json!({}), &es)
        .unwrap()
        .unwrap();
    assert_eq!(result["domain"], "Runtime");

    let result = registry
        .dispatch_command("DOM.getDocument", json!({}), &es)
        .unwrap()
        .unwrap();
    assert_eq!(result["domain"], "DOM");
}

#[test]
fn test_registry_command_not_found() {
    let registry = DomainRegistry::<TestDispatch>::new();
    registry.register(TestDispatch::Echo(EchoHandler)).unwrap();

    let es = NoopEventSender;
    let result = registry.dispatch_command("Echo.nonexistent", json!({}), &es);
    assert!(result.is_some());
    let err = result.unwrap().unwrap_err();
    assert_eq!(err.code, -32601);
}

#[test]
fn test_registry_dispatch_extracts_domain() {
    let registry = DomainRegistry::<TestDispatch>::new();
    registry.register(TestDispatch::Echo(EchoHandler)).unwrap();

    let es = NoopEventSender;
    let result = registry.dispatch_command("Echo.reflect", json!({"key": "value"}), &es);
    let value = result.unwrap().unwrap();
    assert_eq!(value["echo"]["key"], "value");
}

// ===========================================================================
// §3 Transport parsing tests (TEST-CDS-003 / REQ-CDS-001)
// ===========================================================================

mod transport_tests {
    // Transport functions are private, so we test through exported types.

    #[test]
    fn target_info_serialization() {
        let info = cdp_server::TargetInfo {
            id: "abc123".into(),
            target_type: "page".into(),
            title: "Test Page".into(),
            url: "https://example.com".into(),
            web_socket_debugger_url: "ws://127.0.0.1:9222/devtools/page/abc123".into(),
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains(r#""id":"abc123""#));
        assert!(json.contains(r#""type":"page""#));
        assert!(json.contains(r#""title":"Test Page""#));
        assert!(json.contains(r#""url":"https://example.com""#));
    }

    #[test]
    fn target_info_deserialization() {
        let json =
            r#"{"id":"xyz","type":"page","title":"T","url":"U","web_socket_debugger_url":"W"}"#;
        let info: cdp_server::TargetInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.id, "xyz");
        assert_eq!(info.target_type, "page");
    }
}

// ===========================================================================
// §4 ServerConfig builder tests (TEST-CDS-004 / REQ-CDS-008)
// ===========================================================================

#[test]
fn test_server_config_default() {
    let config = ServerConfig::default();
    assert_eq!(config.host, "127.0.0.1");
    assert_eq!(config.port, 9222);
    assert_eq!(config.max_sessions, 100);
    assert_eq!(config.protocol_version, "1.3");
}

#[test]
fn test_server_config_builder() {
    let config = ServerConfig::builder()
        .host("0.0.0.0")
        .port(9333)
        .max_sessions(50)
        .browser_name("TestBrowser/1.0")
        .user_agent("TestAgent")
        .v8_version("SM")
        .webkit_version("Servo")
        .build();

    assert_eq!(config.host, "0.0.0.0");
    assert_eq!(config.port, 9333);
    assert_eq!(config.max_sessions, 50);
    assert_eq!(config.browser_name, "TestBrowser/1.0");
    assert_eq!(config.user_agent.as_deref(), Some("TestAgent"));
    assert_eq!(config.v8_version.as_deref(), Some("SM"));
    assert_eq!(config.webkit_version.as_deref(), Some("Servo"));
}

#[test]
fn test_server_config_builder_partial() {
    let config = ServerConfig::builder().port(8080).build();
    assert_eq!(config.port, 8080);
    assert_eq!(config.host, "127.0.0.1"); // default preserved
}

// ===========================================================================
// §5 EventSender trait contract tests (TEST-CDS-005 / REQ-CDS-005)
// ===========================================================================

#[test]
fn test_noop_event_sender_satisfies_trait() {
    let sender = NoopEventSender;
    sender.send_event("Page.loadEventFired", json!({}));
    // No panic = pass
}

#[test]
fn test_event_serialization() {
    let event = CdpEvent {
        method: "Page.loadEventFired".to_string(),
        params: Some(json!({ "timestamp": 12345 })),
    };
    let json_str = serde_json::to_string(&event).unwrap();
    assert!(json_str.contains("Page.loadEventFired"));
    assert!(json_str.contains("12345"));
}

#[test]
fn test_response_serialization_success() {
    let resp = CdpResponse {
        id: Some(1),
        result: Some(json!({ "value": 42 })),
        error: None,
    };
    let json_str = serde_json::to_string(&resp).unwrap();
    assert!(json_str.contains(r#""result""#));
    assert!(!json_str.contains(r#""error""#));
}

#[test]
fn test_response_serialization_error() {
    let resp = CdpResponse {
        id: Some(2),
        result: None,
        error: Some(CdpError {
            code: -32601,
            message: "not found".into(),
        }),
    };
    let json_str = serde_json::to_string(&resp).unwrap();
    assert!(json_str.contains(r#""error""#));
    assert!(json_str.contains("-32601"));
    assert!(!json_str.contains(r#""result""#));
}

// ===========================================================================
// §6 Error code constants tests
// ===========================================================================

#[test]
fn test_cdp_error_codes() {
    let err = CdpError {
        code: -32601,
        message: "test".into(),
    };
    assert_eq!(err.code, -32601);
    assert_eq!(err.message, "test");

    let json = serde_json::to_string(&err).unwrap();
    assert!(json.contains("-32601"));
}

// ===========================================================================
// §7 DomainHandler lifecycle tests
// ===========================================================================

#[test]
fn test_handler_on_session_created_noop() {
    let handler = EchoHandler;
    handler.on_session_created("session-1");
    // No panic = pass (default impl is noop)
}

#[test]
fn test_handler_on_session_destroyed_noop() {
    let handler = EchoHandler;
    handler.on_session_destroyed("session-1");
    // No panic = pass
}