spikard-http 0.13.0

High-performance HTTP server for Spikard with tower-http middleware stack
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Core test client for Spikard applications
//!
//! This module provides a language-agnostic TestClient that can be wrapped by
//! language bindings (PyO3, napi-rs, magnus) to provide Pythonic, JavaScripty, and
//! Ruby-like APIs respectively.
//!
//! The core client handles all HTTP method dispatch, query params, header management,
//! body encoding (JSON, form-data, multipart), and response snapshot capture.

use super::{ResponseSnapshot, SnapshotError, snapshot_response};
use axum::http::{HeaderName, HeaderValue, Method};
use axum_test::TestServer;
use bytes::Bytes;
use serde_json::Value;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::timeout;
use urlencoding::encode;

type MultipartPayload = Option<(Vec<(String, String)>, Vec<super::MultipartFilePart>)>;
const GRAPHQL_WS_MESSAGE_TIMEOUT: Duration = Duration::from_secs(2);
const GRAPHQL_WS_MAX_CONTROL_MESSAGES: usize = 32;

/// Snapshot of a GraphQL subscription exchange over WebSocket.
#[derive(Debug, Clone, PartialEq)]
pub struct GraphQLSubscriptionSnapshot {
    /// Operation id used for the subscription request.
    pub operation_id: String,
    /// Whether the server acknowledged the GraphQL WebSocket connection.
    pub acknowledged: bool,
    /// First `next.payload` received for this subscription, if any.
    pub event: Option<Value>,
    /// GraphQL protocol errors emitted by the server.
    pub errors: Vec<Value>,
    /// Whether a `complete` frame was observed for this operation.
    pub complete_received: bool,
}

/// Core test client for making HTTP requests to a Spikard application.
///
/// This struct wraps axum-test's TestServer and provides a language-agnostic
/// interface for making HTTP requests, sending WebSocket connections, and
/// handling Server-Sent Events. Language bindings wrap this to provide
/// native API surfaces.
pub struct TestClient {
    mock_server: Arc<TestServer>,
    router: axum::Router,
    http_server: Mutex<Option<Arc<TestServer>>>,
}

impl TestClient {
    /// Create a new test client from an Axum router
    pub fn from_router(router: axum::Router) -> Result<Self, String> {
        let mock_server =
            TestServer::try_new(router.clone()).map_err(|e| format!("Failed to create test server: {}", e))?;

        Ok(Self {
            mock_server: Arc::new(mock_server),
            router,
            http_server: Mutex::new(None),
        })
    }

    /// Get or initialize the underlying socket-backed test server for WebSocket traffic.
    pub fn http_server(&self) -> Result<Arc<TestServer>, SnapshotError> {
        let mut guard = self
            .http_server
            .lock()
            .map_err(|_| SnapshotError::Decompression("Failed to lock HTTP test server state".to_string()))?;

        if let Some(server) = guard.as_ref() {
            return Ok(Arc::clone(server));
        }

        if tokio::runtime::Handle::try_current().is_err() {
            return Err(SnapshotError::Decompression(
                "WebSocket test transport requires an active Tokio runtime".to_string(),
            ));
        }

        let server = Arc::new(
            TestServer::builder()
                .http_transport()
                .try_build(self.router.clone())
                .map_err(|e| SnapshotError::Decompression(format!("Failed to create test server: {}", e)))?,
        );
        *guard = Some(Arc::clone(&server));
        Ok(server)
    }

    /// Make a GET request
    pub async fn get(
        &self,
        path: &str,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.get(&full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a POST request
    pub async fn post(
        &self,
        path: &str,
        json: Option<Value>,
        form_data: Option<Vec<(String, String)>>,
        multipart: MultipartPayload,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.post(&full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        if let Some((form_fields, files)) = multipart {
            let (body, boundary) = super::build_multipart_body(&form_fields, &files);
            let content_type = format!("multipart/form-data; boundary={}", boundary);
            request = request.add_header("content-type", &content_type);
            request = request.bytes(Bytes::from(body));
        } else if let Some(form_fields) = form_data {
            let fields_value = serde_json::to_value(&form_fields)
                .map_err(|e| SnapshotError::Decompression(format!("Failed to serialize form fields: {}", e)))?;
            let encoded = super::encode_urlencoded_body(&fields_value)
                .map_err(|e| SnapshotError::Decompression(format!("Form encoding failed: {}", e)))?;
            request = request.add_header("content-type", "application/x-www-form-urlencoded");
            request = request.bytes(Bytes::from(encoded));
        } else if let Some(json_value) = json {
            request = request.json(&json_value);
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a request with a raw body payload.
    pub async fn request_raw(
        &self,
        method: Method,
        path: &str,
        body: Bytes,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.method(method, &full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        request = request.bytes(body);
        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a PUT request
    pub async fn put(
        &self,
        path: &str,
        json: Option<Value>,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.put(&full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        if let Some(json_value) = json {
            request = request.json(&json_value);
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a PATCH request
    pub async fn patch(
        &self,
        path: &str,
        json: Option<Value>,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.patch(&full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        if let Some(json_value) = json {
            request = request.json(&json_value);
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a DELETE request
    pub async fn delete(
        &self,
        path: &str,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.delete(&full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make an OPTIONS request
    pub async fn options(
        &self,
        path: &str,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.method(Method::OPTIONS, &full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a HEAD request
    pub async fn head(
        &self,
        path: &str,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.method(Method::HEAD, &full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Make a TRACE request
    pub async fn trace(
        &self,
        path: &str,
        query_params: Option<Vec<(String, String)>>,
        headers: Option<Vec<(String, String)>>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let full_path = build_full_path(path, query_params.as_deref());
        let mut request = self.mock_server.method(Method::TRACE, &full_path);

        if let Some(headers_vec) = headers {
            request = self.add_headers(request, headers_vec)?;
        }

        let response = request.await;
        snapshot_response(response).await
    }

    /// Send a GraphQL query/mutation to a custom endpoint
    pub async fn graphql_at(
        &self,
        endpoint: &str,
        query: &str,
        variables: Option<Value>,
        operation_name: Option<&str>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        let body = build_graphql_body(query, variables, operation_name);
        self.post(endpoint, Some(body), None, None, None, None).await
    }

    /// Send a GraphQL query/mutation
    pub async fn graphql(
        &self,
        query: &str,
        variables: Option<Value>,
        operation_name: Option<&str>,
    ) -> Result<ResponseSnapshot, SnapshotError> {
        self.graphql_at("/graphql", query, variables, operation_name).await
    }

    /// Send a GraphQL query and return HTTP status code separately
    ///
    /// This method allows tests to distinguish between:
    /// - HTTP-level errors (400/422 for invalid requests)
    /// - GraphQL-level errors (200 with errors in response body)
    ///
    /// # Example
    /// ```ignore
    /// let (status, snapshot) = client.graphql_with_status(
    ///     "query { invalid syntax",
    ///     None,
    ///     None
    /// ).await?;
    /// assert_eq!(status, 400); // HTTP parse error
    /// ```
    pub async fn graphql_with_status(
        &self,
        query: &str,
        variables: Option<Value>,
        operation_name: Option<&str>,
    ) -> Result<(u16, ResponseSnapshot), SnapshotError> {
        let snapshot = self.graphql(query, variables, operation_name).await?;
        let status = snapshot.status;
        Ok((status, snapshot))
    }

    /// Send a GraphQL subscription (WebSocket) to a custom endpoint.
    ///
    /// Uses the `graphql-transport-ws` protocol and captures the first `next` payload.
    /// After the first payload is received, this client sends `complete` to unsubscribe.
    pub async fn graphql_subscription_at(
        &self,
        endpoint: &str,
        query: &str,
        variables: Option<Value>,
        operation_name: Option<&str>,
    ) -> Result<GraphQLSubscriptionSnapshot, SnapshotError> {
        let operation_id = "spikard-subscription-1".to_string();
        let http_server = self.http_server()?;
        let upgrade = http_server
            .get_websocket(endpoint)
            .add_header("sec-websocket-protocol", "graphql-transport-ws")
            .await;

        if upgrade.status_code().as_u16() != 101 {
            return Err(SnapshotError::Decompression(format!(
                "GraphQL subscription upgrade failed with status {}",
                upgrade.status_code()
            )));
        }

        let mut websocket = super::WebSocketConnection::new(upgrade.into_websocket().await);

        websocket
            .send_json(&serde_json::json!({"type": "connection_init"}))
            .await;
        wait_for_graphql_ack(&mut websocket).await?;

        websocket
            .send_json(&serde_json::json!({
                "id": operation_id,
                "type": "subscribe",
                "payload": build_graphql_body(query, variables, operation_name),
            }))
            .await;

        let mut event = None;
        let mut errors = Vec::new();
        let mut complete_received = false;

        for _ in 0..GRAPHQL_WS_MAX_CONTROL_MESSAGES {
            let message = timeout(
                GRAPHQL_WS_MESSAGE_TIMEOUT,
                receive_graphql_protocol_message(&mut websocket),
            )
            .await
            .map_err(|_| {
                SnapshotError::Decompression("Timed out waiting for GraphQL subscription message".to_string())
            })??;

            let message_type = message.get("type").and_then(Value::as_str).unwrap_or_default();
            match message_type {
                "next"
                    if message
                        .get("id")
                        .and_then(Value::as_str)
                        .is_none_or(|id| id == operation_id) =>
                {
                    event = message.get("payload").cloned();

                    websocket
                        .send_json(&serde_json::json!({
                            "id": operation_id,
                            "type": "complete",
                        }))
                        .await;

                    if let Ok(next_message) = timeout(
                        GRAPHQL_WS_MESSAGE_TIMEOUT,
                        receive_graphql_protocol_message(&mut websocket),
                    )
                    .await
                        && let Ok(next_message) = next_message
                        && next_message.get("type").and_then(Value::as_str) == Some("complete")
                        && next_message
                            .get("id")
                            .and_then(Value::as_str)
                            .is_none_or(|id| id == operation_id)
                    {
                        complete_received = true;
                    }
                    break;
                }
                "error" => {
                    errors.push(message.get("payload").cloned().unwrap_or(message));
                    break;
                }
                "complete"
                    if message
                        .get("id")
                        .and_then(Value::as_str)
                        .is_none_or(|id| id == operation_id) =>
                {
                    complete_received = true;
                    break;
                }
                "ping" => {
                    let mut pong = serde_json::json!({"type": "pong"});
                    if let Some(payload) = message.get("payload") {
                        pong["payload"] = payload.clone();
                    }
                    websocket.send_json(&pong).await;
                }
                "pong" => {}
                _ => {}
            }
        }

        websocket.close().await;

        if event.is_none() && errors.is_empty() && !complete_received {
            return Err(SnapshotError::Decompression(
                "No GraphQL subscription event received before timeout".to_string(),
            ));
        }

        Ok(GraphQLSubscriptionSnapshot {
            operation_id,
            acknowledged: true,
            event,
            errors,
            complete_received,
        })
    }

    /// Send a GraphQL subscription (WebSocket).
    ///
    /// Uses `/graphql` as the default subscription endpoint.
    pub async fn graphql_subscription(
        &self,
        query: &str,
        variables: Option<Value>,
        operation_name: Option<&str>,
    ) -> Result<GraphQLSubscriptionSnapshot, SnapshotError> {
        self.graphql_subscription_at("/graphql", query, variables, operation_name)
            .await
    }

    /// Add headers to a test request builder
    fn add_headers(
        &self,
        mut request: axum_test::TestRequest,
        headers: Vec<(String, String)>,
    ) -> Result<axum_test::TestRequest, SnapshotError> {
        for (key, value) in headers {
            let header_name = HeaderName::from_bytes(key.as_bytes())
                .map_err(|e| SnapshotError::InvalidHeader(format!("Invalid header name: {}", e)))?;
            let header_value = HeaderValue::from_str(&value)
                .map_err(|e| SnapshotError::InvalidHeader(format!("Invalid header value: {}", e)))?;
            request = request.add_header(header_name, header_value);
        }
        Ok(request)
    }
}

async fn wait_for_graphql_ack(websocket: &mut super::WebSocketConnection) -> Result<(), SnapshotError> {
    for _ in 0..GRAPHQL_WS_MAX_CONTROL_MESSAGES {
        let message = timeout(GRAPHQL_WS_MESSAGE_TIMEOUT, receive_graphql_protocol_message(websocket))
            .await
            .map_err(|_| SnapshotError::Decompression("Timed out waiting for GraphQL connection_ack".to_string()))??;

        match message.get("type").and_then(Value::as_str).unwrap_or_default() {
            "connection_ack" => return Ok(()),
            "ping" => {
                let mut pong = serde_json::json!({"type": "pong"});
                if let Some(payload) = message.get("payload") {
                    pong["payload"] = payload.clone();
                }
                websocket.send_json(&pong).await;
            }
            "connection_error" | "error" => {
                return Err(SnapshotError::Decompression(format!(
                    "GraphQL subscription rejected during init: {}",
                    message
                )));
            }
            _ => {}
        }
    }

    Err(SnapshotError::Decompression(
        "No GraphQL connection_ack received".to_string(),
    ))
}

async fn receive_graphql_protocol_message(websocket: &mut super::WebSocketConnection) -> Result<Value, SnapshotError> {
    loop {
        match websocket.receive_message().await {
            super::WebSocketMessage::Text(text) => {
                return serde_json::from_str::<Value>(&text).map_err(|e| {
                    SnapshotError::Decompression(format!("Failed to parse GraphQL WebSocket message as JSON: {}", e))
                });
            }
            super::WebSocketMessage::Binary(bytes) => {
                return serde_json::from_slice::<Value>(&bytes).map_err(|e| {
                    SnapshotError::Decompression(format!(
                        "Failed to parse GraphQL binary WebSocket message as JSON: {}",
                        e
                    ))
                });
            }
            super::WebSocketMessage::Ping(_) | super::WebSocketMessage::Pong(_) => continue,
            super::WebSocketMessage::Close(reason) => {
                return Err(SnapshotError::Decompression(format!(
                    "GraphQL WebSocket connection closed before response: {:?}",
                    reason
                )));
            }
        }
    }
}

/// Build a GraphQL request body from query, variables, and operation name
pub fn build_graphql_body(query: &str, variables: Option<Value>, operation_name: Option<&str>) -> Value {
    let mut body = serde_json::json!({ "query": query });
    if let Some(vars) = variables {
        body["variables"] = vars;
    }
    if let Some(op_name) = operation_name {
        body["operationName"] = Value::String(op_name.to_string());
    }
    body
}

/// Build a full path with query parameters
fn build_full_path(path: &str, query_params: Option<&[(String, String)]>) -> String {
    match query_params {
        None | Some(&[]) => path.to_string(),
        Some(params) => {
            let query_string: Vec<String> = params
                .iter()
                .map(|(k, v)| format!("{}={}", encode(k), encode(v)))
                .collect();

            if path.contains('?') {
                format!("{}&{}", path, query_string.join("&"))
            } else {
                format!("{}?{}", path, query_string.join("&"))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Router,
        extract::ws::{Message, WebSocketUpgrade},
        routing::get,
    };

    #[test]
    fn build_full_path_no_params() {
        let path = "/users";
        assert_eq!(build_full_path(path, None), "/users");
        assert_eq!(build_full_path(path, Some(&[])), "/users");
    }

    #[test]
    fn build_full_path_with_params() {
        let path = "/users";
        let params = vec![
            ("id".to_string(), "123".to_string()),
            ("name".to_string(), "test user".to_string()),
        ];
        let result = build_full_path(path, Some(&params));
        assert!(result.starts_with("/users?"));
        assert!(result.contains("id=123"));
        assert!(result.contains("name=test%20user"));
    }

    #[test]
    fn build_full_path_existing_query() {
        let path = "/users?active=true";
        let params = vec![("id".to_string(), "123".to_string())];
        let result = build_full_path(path, Some(&params));
        assert_eq!(result, "/users?active=true&id=123");
    }

    #[test]
    fn test_graphql_query_builder() {
        let query = "{ users { id name } }";
        let variables = Some(serde_json::json!({ "limit": 10 }));
        let op_name = Some("GetUsers");

        let mut body = serde_json::json!({ "query": query });
        if let Some(vars) = variables {
            body["variables"] = vars;
        }
        if let Some(op_name) = op_name {
            body["operationName"] = Value::String(op_name.to_string());
        }

        assert_eq!(body["query"], query);
        assert_eq!(body["variables"]["limit"], 10);
        assert_eq!(body["operationName"], "GetUsers");
    }

    #[test]
    fn test_graphql_with_status_method() {
        let query = "query { hello }";
        let body = serde_json::json!({
            "query": query,
            "variables": null,
            "operationName": null
        });

        // This test validates the method signature and return type
        // Actual HTTP status testing will happen in integration tests
        let expected_fields = vec!["query", "variables", "operationName"];
        for field in expected_fields {
            assert!(body.get(field).is_some(), "Missing field: {}", field);
        }
    }

    #[test]
    fn test_build_graphql_body_basic() {
        let query = "{ users { id name } }";
        let body = build_graphql_body(query, None, None);

        assert_eq!(body["query"], query);
        assert!(body.get("variables").is_none() || body["variables"].is_null());
        assert!(body.get("operationName").is_none() || body["operationName"].is_null());
    }

    #[test]
    fn test_build_graphql_body_with_variables() {
        let query = "query GetUser($id: ID!) { user(id: $id) { name } }";
        let variables = Some(serde_json::json!({ "id": "123" }));
        let body = build_graphql_body(query, variables, None);

        assert_eq!(body["query"], query);
        assert_eq!(body["variables"]["id"], "123");
    }

    #[test]
    fn test_build_graphql_body_with_operation_name() {
        let query = "query GetUsers { users { id } }";
        let op_name = Some("GetUsers");
        let body = build_graphql_body(query, None, op_name);

        assert_eq!(body["query"], query);
        assert_eq!(body["operationName"], "GetUsers");
    }

    #[test]
    fn test_build_graphql_body_all_fields() {
        let query = "mutation CreateUser($name: String!) { createUser(name: $name) { id } }";
        let variables = Some(serde_json::json!({ "name": "Alice" }));
        let op_name = Some("CreateUser");
        let body = build_graphql_body(query, variables, op_name);

        assert_eq!(body["query"], query);
        assert_eq!(body["variables"]["name"], "Alice");
        assert_eq!(body["operationName"], "CreateUser");
    }

    #[tokio::test]
    async fn graphql_subscription_returns_first_event_and_completes() {
        let app = Router::new().route(
            "/graphql",
            get(|ws: WebSocketUpgrade| async move {
                ws.on_upgrade(|mut socket| async move {
                    while let Some(result) = socket.recv().await {
                        let Ok(Message::Text(text)) = result else {
                            continue;
                        };
                        let Ok(message): Result<Value, _> = serde_json::from_str(&text) else {
                            continue;
                        };

                        match message.get("type").and_then(Value::as_str) {
                            Some("connection_init") => {
                                let _ = socket
                                    .send(Message::Text(
                                        serde_json::json!({"type":"connection_ack"}).to_string().into(),
                                    ))
                                    .await;
                            }
                            Some("subscribe") => {
                                let id = message.get("id").and_then(Value::as_str).unwrap_or("1");
                                let _ = socket
                                    .send(Message::Text(
                                        serde_json::json!({
                                            "id": id,
                                            "type": "next",
                                            "payload": {"data": {"ticker": "AAPL"}},
                                        })
                                        .to_string()
                                        .into(),
                                    ))
                                    .await;

                                if let Some(Ok(Message::Text(complete_text))) = socket.recv().await {
                                    let Ok(complete_message): Result<Value, _> = serde_json::from_str(&complete_text)
                                    else {
                                        break;
                                    };
                                    if complete_message.get("type").and_then(Value::as_str) == Some("complete") {
                                        let _ = socket
                                            .send(Message::Text(
                                                serde_json::json!({"id": id, "type":"complete"}).to_string().into(),
                                            ))
                                            .await;
                                    }
                                }
                                break;
                            }
                            _ => {}
                        }
                    }
                })
            }),
        );

        let client = TestClient::from_router(app).expect("client");
        assert!(client.http_server.lock().expect("lock").is_none());

        let snapshot = client
            .graphql_subscription("subscription { ticker }", None, None)
            .await
            .expect("subscription snapshot");

        assert!(snapshot.acknowledged);
        assert_eq!(snapshot.errors, Vec::<Value>::new());
        assert_eq!(snapshot.event, Some(serde_json::json!({"data": {"ticker": "AAPL"}})));
        assert!(snapshot.complete_received);
        assert!(client.http_server.lock().expect("lock").is_some());
    }

    #[tokio::test]
    async fn graphql_subscription_surfaces_connection_error() {
        let app = Router::new().route(
            "/graphql",
            get(|ws: WebSocketUpgrade| async move {
                ws.on_upgrade(|mut socket| async move {
                    while let Some(result) = socket.recv().await {
                        let Ok(Message::Text(text)) = result else {
                            continue;
                        };
                        let Ok(message): Result<Value, _> = serde_json::from_str(&text) else {
                            continue;
                        };

                        if message.get("type").and_then(Value::as_str) == Some("connection_init") {
                            let _ = socket
                                .send(Message::Text(
                                    serde_json::json!({
                                        "type": "connection_error",
                                        "payload": {"message": "not authorized"},
                                    })
                                    .to_string()
                                    .into(),
                                ))
                                .await;
                            break;
                        }
                    }
                })
            }),
        );

        let client = TestClient::from_router(app).expect("client");
        assert!(client.http_server.lock().expect("lock").is_none());

        let error = client
            .graphql_subscription("subscription { privateFeed }", None, None)
            .await
            .expect_err("expected connection error");

        assert!(error.to_string().contains("connection_error"));
        assert!(client.http_server.lock().expect("lock").is_some());
    }

    #[tokio::test]
    async fn http_requests_do_not_initialize_socket_transport() {
        let app = Router::new().route("/health", get(|| async { "ok" }));

        let client = TestClient::from_router(app).expect("client");
        assert!(client.http_server.lock().expect("lock").is_none());

        let snapshot = client.get("/health", None, None).await.expect("response snapshot");

        assert_eq!(snapshot.status, 200);
        assert_eq!(snapshot.text().expect("body"), "ok");
        assert!(client.http_server.lock().expect("lock").is_none());
    }
}