mockserver-client 7.0.0-alpha.1

An idiomatic Rust client for MockServer's control-plane API
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
//! The MockServer client and its builder.

use reqwest::blocking::Client;
use serde_json::Value;

use crate::breakpoint::{
    BreakpointMatcherList, BreakpointMatcherRegistration, BreakpointMatcherResponse,
    BreakpointRequestHandler, BreakpointResponseHandler, BreakpointStreamFrameHandler,
    BreakpointWebSocketClient,
};
use crate::error::{Error, Result};
use crate::model::*;

// ---------------------------------------------------------------------------
// ClientBuilder
// ---------------------------------------------------------------------------

/// Builder for constructing a [`MockServerClient`].
///
/// # Example
/// ```no_run
/// use mockserver_client::ClientBuilder;
///
/// let client = ClientBuilder::new("localhost", 1080)
///     .context_path("/api")
///     .secure(true)
///     .build()
///     .unwrap();
/// ```
pub struct ClientBuilder {
    host: String,
    port: u16,
    context_path: String,
    secure: bool,
    tls_verify: bool,
}

impl ClientBuilder {
    /// Create a new builder targeting the given host and port.
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
            context_path: String::new(),
            secure: false,
            tls_verify: true,
        }
    }

    /// Set a context path prefix (e.g., "/mockserver" if deployed behind a reverse proxy).
    pub fn context_path(mut self, path: impl Into<String>) -> Self {
        self.context_path = path.into();
        self
    }

    /// Use HTTPS instead of HTTP.
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    /// Whether to verify TLS certificates (default: true).
    pub fn tls_verify(mut self, verify: bool) -> Self {
        self.tls_verify = verify;
        self
    }

    /// Build the client.
    pub fn build(self) -> Result<MockServerClient> {
        let scheme = if self.secure { "https" } else { "http" };
        let ctx = if self.context_path.is_empty() {
            String::new()
        } else if self.context_path.starts_with('/') {
            self.context_path
        } else {
            format!("/{}", self.context_path)
        };
        let base_url = format!("{scheme}://{}:{}{ctx}", self.host, self.port);

        let http_client = Client::builder()
            .danger_accept_invalid_certs(!self.tls_verify)
            .build()?;

        Ok(MockServerClient {
            base_url,
            http: http_client,
            breakpoint_ws: std::sync::Mutex::new(None),
        })
    }
}

// ---------------------------------------------------------------------------
// MockServerClient
// ---------------------------------------------------------------------------

/// A blocking client for the MockServer control-plane REST API.
///
/// Created via [`ClientBuilder`]. All methods are synchronous.
pub struct MockServerClient {
    pub(crate) base_url: String,
    http: Client,
    breakpoint_ws: std::sync::Mutex<Option<BreakpointWebSocketClient>>,
}

impl MockServerClient {
    // ------------------------------------------------------------------
    // Expectation creation
    // ------------------------------------------------------------------

    /// Create one or more expectations on the server.
    ///
    /// Returns the created expectations as echoed by the server.
    pub fn upsert(&self, expectations: &[Expectation]) -> Result<Vec<Expectation>> {
        let body = serde_json::to_value(expectations)?;
        let resp = self
            .http
            .put(self.url("/mockserver/expectation"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(expectations.to_vec())
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Fluent API entry point
    // ------------------------------------------------------------------

    /// Begin building an expectation with the fluent `when(...).respond(...)` API.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// client.when(HttpRequest::new().method("GET").path("/foo"))
    ///     .respond(HttpResponse::new().status_code(200).body("bar"))
    ///     .unwrap();
    /// ```
    pub fn when(&self, request: HttpRequest) -> ForwardChainExpectation<'_> {
        ForwardChainExpectation {
            client: self,
            request,
            times: None,
            time_to_live: None,
            priority: None,
            id: None,
        }
    }

    // ------------------------------------------------------------------
    // Verify
    // ------------------------------------------------------------------

    /// Verify that a request was received the specified number of times.
    ///
    /// Returns `Ok(())` if verification passes, or
    /// `Err(Error::VerificationFailure)` with the server's failure message.
    pub fn verify(&self, request: HttpRequest, times: VerificationTimes) -> Result<()> {
        let verification = Verification {
            http_request: request,
            times: Some(times),
        };
        let resp = self
            .http
            .put(self.url("/mockserver/verify"))
            .json(&verification)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 202 => Ok(()),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Verify that requests were received in the given order.
    pub fn verify_sequence(&self, requests: Vec<HttpRequest>) -> Result<()> {
        let verification = VerificationSequence {
            http_requests: requests,
        };
        let resp = self
            .http
            .put(self.url("/mockserver/verifySequence"))
            .json(&verification)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 202 => Ok(()),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Clear / Reset
    // ------------------------------------------------------------------

    /// Clear expectations and/or logs matching the given request.
    ///
    /// If `request` is `None`, clears everything of the specified type.
    pub fn clear(
        &self,
        request: Option<&HttpRequest>,
        clear_type: Option<ClearType>,
    ) -> Result<()> {
        let mut url = self.url("/mockserver/clear");
        if let Some(ct) = clear_type {
            url = format!("{url}?type={}", ct.as_str());
        }

        let mut builder = self.http.put(&url);
        builder = builder.header("Content-Type", "application/json");
        if let Some(req) = request {
            builder = builder.json(req);
        } else {
            builder = builder.body("");
        }

        let resp = builder.send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Clear expectations by expectation ID.
    pub fn clear_by_id(
        &self,
        expectation_id: impl Into<String>,
        clear_type: Option<ClearType>,
    ) -> Result<()> {
        let mut url = self.url("/mockserver/clear");
        if let Some(ct) = clear_type {
            url = format!("{url}?type={}", ct.as_str());
        }

        let body = serde_json::json!({ "id": expectation_id.into() });
        let resp = self.http.put(&url).json(&body).send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Reset all expectations and recorded requests.
    pub fn reset(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/reset"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Retrieve
    // ------------------------------------------------------------------

    /// Retrieve recorded requests matching the optional filter.
    pub fn retrieve_recorded_requests(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<HttpRequest>> {
        let text =
            self.do_retrieve(request, RetrieveType::Requests, RetrieveFormat::Json)?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve active expectations matching the optional filter.
    pub fn retrieve_active_expectations(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<Expectation>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::ActiveExpectations,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve recorded expectations matching the optional filter.
    pub fn retrieve_recorded_expectations(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<Expectation>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::RecordedExpectations,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve log messages matching the optional filter.
    pub fn retrieve_log_messages(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<String>> {
        let text =
            self.do_retrieve(request, RetrieveType::Logs, RetrieveFormat::LogEntries)?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        // Log messages may be returned as a JSON array of strings or as a
        // separator-delimited block. Try JSON first.
        if let Ok(arr) = serde_json::from_str::<Vec<String>>(&text) {
            return Ok(arr);
        }
        // Fall back to splitting on the separator used by MockServer.
        Ok(text
            .split("------------------------------------\n")
            .map(|s| s.to_string())
            .filter(|s| !s.is_empty())
            .collect())
    }

    /// Retrieve recorded request/response pairs.
    pub fn retrieve_request_responses(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<Value>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::RequestResponses,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    // ------------------------------------------------------------------
    // Status / Bind
    // ------------------------------------------------------------------

    /// Query the server's listening ports.
    pub fn status(&self) -> Result<Ports> {
        let resp = self
            .http
            .put(self.url("/mockserver/status"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Bind additional listening ports.
    pub fn bind(&self, ports: &[u16]) -> Result<Ports> {
        let body = Ports {
            ports: ports.to_vec(),
        };
        let resp = self
            .http
            .put(self.url("/mockserver/bind"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Check if the MockServer has started (polls with retries).
    pub fn has_started(&self, attempts: u32, timeout_ms: u64) -> bool {
        for i in 0..attempts {
            match self.status() {
                Ok(_) => return true,
                Err(_) => {
                    if i < attempts - 1 {
                        std::thread::sleep(std::time::Duration::from_millis(timeout_ms));
                    }
                }
            }
        }
        false
    }

    // ------------------------------------------------------------------
    // Breakpoints
    // ------------------------------------------------------------------

    /// Ensure the breakpoint WebSocket client is connected and return the clientId.
    /// If the existing connection's read loop has exited, it is replaced transparently.
    fn ensure_breakpoint_ws(&self) -> Result<String> {
        let mut guard = self.breakpoint_ws.lock().unwrap();
        let needs_connect = match guard.as_ref() {
            None => true,
            Some(ws) => ws.is_dead(),
        };
        if needs_connect {
            // Close the old dead connection if present
            if let Some(old) = guard.take() {
                old.close();
            }
            let ws = BreakpointWebSocketClient::connect(&self.base_url)?;
            *guard = Some(ws);
        }
        Ok(guard.as_ref().unwrap().client_id.clone())
    }

    /// Register a breakpoint matcher with the given phases and handlers.
    /// Returns the server-assigned breakpoint id.
    pub fn add_breakpoint(
        &self,
        matcher: HttpRequest,
        phases: &[&str],
        request_handler: Option<BreakpointRequestHandler>,
        response_handler: Option<BreakpointResponseHandler>,
        stream_frame_handler: Option<BreakpointStreamFrameHandler>,
    ) -> Result<String> {
        if phases.is_empty() {
            return Err(Error::InvalidRequest(
                "At least one phase is required".into(),
            ));
        }

        let client_id = self.ensure_breakpoint_ws()?;

        let reg = BreakpointMatcherRegistration {
            http_request: matcher,
            phases: phases.iter().map(|s| s.to_string()).collect(),
            client_id: Some(client_id),
        };

        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher"))
            .json(&reg)
            .send()?;

        let status = resp.status().as_u16();
        let text = resp.text()?;
        if status >= 400 {
            return Err(Error::UnexpectedStatus {
                status,
                body: text,
            });
        }

        let result: BreakpointMatcherResponse = serde_json::from_str(&text)?;
        let id = result.id.clone();

        // Register handlers
        let guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.as_ref() {
            if let Some(h) = request_handler {
                ws.set_request_handler(&id, h);
            }
            if let Some(h) = response_handler {
                ws.set_response_handler(&id, h);
            }
            if let Some(h) = stream_frame_handler {
                ws.set_stream_frame_handler(&id, h);
            }
        }

        Ok(id)
    }

    /// Convenience: register a REQUEST-only breakpoint.
    pub fn add_request_breakpoint(
        &self,
        matcher: HttpRequest,
        handler: BreakpointRequestHandler,
    ) -> Result<String> {
        self.add_breakpoint(
            matcher,
            &[crate::breakpoint::phase::REQUEST],
            Some(handler),
            None,
            None,
        )
    }

    /// Convenience: register a REQUEST + RESPONSE breakpoint.
    pub fn add_request_response_breakpoint(
        &self,
        matcher: HttpRequest,
        request_handler: BreakpointRequestHandler,
        response_handler: BreakpointResponseHandler,
    ) -> Result<String> {
        self.add_breakpoint(
            matcher,
            &[
                crate::breakpoint::phase::REQUEST,
                crate::breakpoint::phase::RESPONSE,
            ],
            Some(request_handler),
            Some(response_handler),
            None,
        )
    }

    /// Convenience: register a streaming-phase breakpoint.
    pub fn add_stream_breakpoint(
        &self,
        matcher: HttpRequest,
        phases: &[&str],
        handler: BreakpointStreamFrameHandler,
    ) -> Result<String> {
        self.add_breakpoint(matcher, phases, None, None, Some(handler))
    }

    /// List all registered breakpoint matchers.
    pub fn list_breakpoint_matchers(&self) -> Result<BreakpointMatcherList> {
        let resp = self
            .http
            .get(self.url("/mockserver/breakpoint/matchers"))
            .send()?;

        let status = resp.status().as_u16();
        let text = resp.text()?;
        if status >= 400 {
            return Err(Error::UnexpectedStatus {
                status,
                body: text,
            });
        }

        Ok(serde_json::from_str(&text)?)
    }

    /// Remove a breakpoint matcher by id.
    pub fn remove_breakpoint_matcher(&self, id: impl Into<String>) -> Result<()> {
        let id = id.into();
        let body = serde_json::json!({ "id": &id });
        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher/remove"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let guard = self.breakpoint_ws.lock().unwrap();
                if let Some(ws) = guard.as_ref() {
                    ws.remove_handlers(&id);
                }
                Ok(())
            }
            404 => Err(Error::InvalidRequest(format!(
                "Breakpoint matcher not found: {id}"
            ))),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Remove all registered breakpoint matchers.
    pub fn clear_breakpoint_matchers(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher/clear"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        if status >= 400 {
            return Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            });
        }

        let guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.as_ref() {
            ws.clear_handlers();
        }
        Ok(())
    }

    /// Close the breakpoint callback WebSocket connection.
    pub fn close_breakpoint_websocket(&self) {
        let mut guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.take() {
            ws.close();
        }
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    fn url(&self, path: &str) -> String {
        format!("{}{path}", self.base_url)
    }

    fn do_retrieve(
        &self,
        request: Option<&HttpRequest>,
        retrieve_type: RetrieveType,
        format: RetrieveFormat,
    ) -> Result<String> {
        let url = format!(
            "{}?type={}&format={}",
            self.url("/mockserver/retrieve"),
            retrieve_type.as_str(),
            format.as_str(),
        );

        let mut builder = self.http.put(&url);
        builder = builder.header("Content-Type", "application/json");
        if let Some(req) = request {
            builder = builder.json(req);
        } else {
            builder = builder.body("");
        }

        let resp = builder.send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// ForwardChainExpectation (fluent builder)
// ---------------------------------------------------------------------------

/// Fluent builder for creating an expectation via `client.when(...).respond(...)`.
pub struct ForwardChainExpectation<'a> {
    client: &'a MockServerClient,
    request: HttpRequest,
    times: Option<Times>,
    time_to_live: Option<TimeToLive>,
    priority: Option<i32>,
    id: Option<String>,
}

impl<'a> ForwardChainExpectation<'a> {
    /// Set how many times this expectation should match.
    pub fn times(mut self, times: Times) -> Self {
        self.times = Some(times);
        self
    }

    /// Set the time-to-live for this expectation.
    pub fn time_to_live(mut self, ttl: TimeToLive) -> Self {
        self.time_to_live = Some(ttl);
        self
    }

    /// Set the priority for this expectation.
    pub fn priority(mut self, priority: i32) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Set the expectation ID (for upsert semantics).
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Complete the expectation with a response action.
    pub fn respond(self, response: HttpResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond(response);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a forward action.
    pub fn forward(self, forward: HttpForward) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.forward(forward);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with an error action.
    pub fn error(self, error: HttpError) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.error(error);
        client.upsert(&[expectation])
    }

    fn into_parts(self) -> (&'a MockServerClient, Expectation) {
        let ForwardChainExpectation {
            client,
            request,
            times,
            time_to_live,
            priority,
            id,
        } = self;
        let mut exp = Expectation::new(request);
        exp.times = times;
        exp.time_to_live = time_to_live;
        exp.priority = priority;
        exp.id = id;
        (client, exp)
    }
}