fuchsia_hyper_test_support/
fault_injection.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! These are Handler implementations that are specifically for injecting faults into the behavior
6//! of the server.
7
8use crate::Handler;
9use futures::future::{pending, BoxFuture};
10use futures::prelude::*;
11use hyper::header::CONTENT_LENGTH;
12use hyper::{Body, Request, Response, StatusCode};
13
14/// Handler that never sends bytes.
15pub struct Hang;
16
17impl Handler for Hang {
18    fn handles(&self, _: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> {
19        Some(pending().boxed())
20    }
21}
22
23/// Handler that sends the header but then never sends body bytes.
24pub struct HangBody {
25    content_length: u32,
26}
27
28impl HangBody {
29    /// Create a new HangBody handler which returns HTTP response headers, stating that it will
30    /// return a body of the given content length, and then never returns a body (hanging).
31    pub fn content_length(content_length: u32) -> Self {
32        Self { content_length }
33    }
34}
35
36impl Handler for HangBody {
37    fn handles(&self, _: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> {
38        let content_length = self.content_length;
39        Some(
40            async move {
41                Response::builder()
42                    .status(StatusCode::OK)
43                    .header(CONTENT_LENGTH, content_length)
44                    .body(Body::wrap_stream(futures::stream::pending::<Result<Vec<u8>, String>>()))
45                    .expect("valid response")
46            }
47            .boxed(),
48        )
49    }
50}