update_package/
board.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//! Typesafe wrappers around verifying the board file.
6
7use fidl_fuchsia_io as fio;
8use thiserror::Error;
9use zx_status::Status;
10
11/// An error encountered while verifying the board.
12#[derive(Debug, Error)]
13#[allow(missing_docs)]
14pub enum VerifyBoardError {
15    #[error("while opening the file: {0}")]
16    OpenFile(#[from] fuchsia_fs::node::OpenError),
17
18    #[error("while reading the file: {0}")]
19    ReadFile(#[from] fuchsia_fs::file::ReadError),
20
21    #[error("expected board name {} found {}", expected, found)]
22    VerifyContents { expected: String, found: String },
23}
24
25pub(crate) async fn verify_board(
26    proxy: &fio::DirectoryProxy,
27    expected_contents: &str,
28) -> Result<(), VerifyBoardError> {
29    let file = match fuchsia_fs::directory::open_file(proxy, "board", fio::PERM_READABLE).await {
30        Ok(file) => Ok(file),
31        Err(fuchsia_fs::node::OpenError::OpenError(Status::NOT_FOUND)) => return Ok(()),
32        Err(e) => Err(e),
33    }
34    .map_err(VerifyBoardError::OpenFile)?;
35
36    let contents =
37        fuchsia_fs::file::read_to_string(&file).await.map_err(VerifyBoardError::ReadFile)?;
38
39    if expected_contents != contents {
40        return Err(VerifyBoardError::VerifyContents {
41            expected: expected_contents.to_string(),
42            found: contents,
43        });
44    }
45
46    Ok(())
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use crate::TestUpdatePackage;
53    use assert_matches::assert_matches;
54    use fuchsia_async as fasync;
55
56    #[fasync::run_singlethreaded(test)]
57    async fn verify_board_success_file_exists() {
58        let p = TestUpdatePackage::new().add_file("board", "kourtney").await;
59        assert_matches!(p.verify_board("kourtney").await, Ok(()));
60    }
61
62    #[fasync::run_singlethreaded(test)]
63    async fn verify_board_success_file_does_not_exist() {
64        let p = TestUpdatePackage::new();
65        assert_matches!(p.verify_board("kim").await, Ok(()));
66    }
67
68    #[fasync::run_singlethreaded(test)]
69    async fn verify_board_failure_verify_contents() {
70        let p = TestUpdatePackage::new().add_file("board", "khloe").await;
71        assert_matches!(
72            p.verify_board("kendall").await,
73            Err(VerifyBoardError::VerifyContents { expected, found })
74                if expected=="kendall" && found=="khloe"
75        );
76    }
77}