fdf_component/
testing.rs

1// Copyright 2025 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//! Provides a driver unit testing library.
6
7mod dut;
8pub mod harness;
9pub mod node;
10
11use crate::{Driver, server};
12use fidl::endpoints::{RequestStream, ServerEnd};
13use fidl_fuchsia_logger as flogger;
14use fuchsia_component::client::connect_channel_to_protocol;
15use std::sync::Arc;
16
17/// Returns a reference to the driver, if it has been started.
18///
19/// # Safety
20///
21/// The caller must ensure that the `driver_token` is a valid pointer to the `DriverServer`
22/// that was returned by the `initialize` function.
23pub(crate) unsafe fn get_driver_from_token<'a, T: Driver>(driver_token: usize) -> Option<&'a T> {
24    let driver_server = unsafe { &*(driver_token as *const server::DriverServer<T>) };
25    driver_server.testing_get_driver()
26}
27
28/// Can be used to forward logsink requests to the test's.
29pub(crate) fn logsink_connector(server_end: ServerEnd<flogger::LogSinkMarker>) {
30    let (stream, handle) = server_end.into_stream_and_control_handle();
31
32    // Since we are using the already initialized logsink, we need to emulate this
33    // notification, otherwise the log init on the driver side hangs.
34    handle
35        .send_on_init(flogger::LogSinkOnInitRequest {
36            buffer: None,
37            interest: None,
38            ..Default::default()
39        })
40        .expect("failed to send on init");
41
42    drop(handle);
43
44    let inner = stream.into_inner().0;
45    let server_inner = Arc::into_inner(inner).expect("no other refs.");
46    let channel = server_inner.into_channel().into_zx_channel();
47
48    // Just forward it to the test's logger.
49    if let Err(e) = connect_channel_to_protocol::<flogger::LogSinkMarker>(channel) {
50        log::warn!("Failed to connect to LogSink: {:?}", e);
51    }
52}