bt_fidl_mocks/
hci.rs

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
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::expect::{expect_call, Status};
use anyhow::Error;
use fidl_fuchsia_hardware_bluetooth::{
    HciTransportMarker, HciTransportProxy, HciTransportRequest, HciTransportRequestStream,
    SentPacket,
};
use zx::MonotonicDuration;

/// Provides a simple mock implementation of `fuchsia.hardware.bluetooth/HciTransport`.
pub struct HciTransportMock {
    stream: HciTransportRequestStream,
    timeout: MonotonicDuration,
}

impl HciTransportMock {
    pub fn new(timeout: MonotonicDuration) -> Result<(HciTransportProxy, HciTransportMock), Error> {
        let (proxy, stream) = fidl::endpoints::create_proxy_and_stream::<HciTransportMarker>();
        Ok((proxy, HciTransportMock { stream, timeout }))
    }

    pub fn from_stream(
        stream: HciTransportRequestStream,
        timeout: MonotonicDuration,
    ) -> HciTransportMock {
        HciTransportMock { stream, timeout }
    }

    pub async fn expect_send(&mut self, packet: SentPacket) -> Result<(), Error> {
        expect_call(&mut self.stream, self.timeout, move |req| match req {
            HciTransportRequest::Send_ { payload, responder } => {
                let _ = responder.send()?;
                if payload != packet {
                    return Ok(Status::Pending);
                }
                Ok(Status::Satisfied(()))
            }
            _ => Ok(Status::Pending),
        })
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::timeout_duration;
    use futures::join;

    #[fuchsia_async::run_until_stalled(test)]
    async fn test_expect_send() {
        let (proxy, mut mock) =
            HciTransportMock::new(timeout_duration()).expect("failed to create mock");
        let send_fut = proxy.send_(&SentPacket::Command(vec![0x03]));
        let expect_fut = mock.expect_send(SentPacket::Command(vec![0x03]));

        let (send_result, expect_result) = join!(send_fut, expect_fut);
        let _ = send_result.expect("send request failed");
        let _ = expect_result.expect("expectation not satisfied");
    }
}