Skip to main content

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
55    #[fuchsia::test]
56    async fn verify_board_success_file_exists() {
57        let p = TestUpdatePackage::new().add_file("board", "kourtney").await;
58        assert_matches!(p.verify_board("kourtney").await, Ok(()));
59    }
60
61    #[fuchsia::test]
62    async fn verify_board_success_file_does_not_exist() {
63        let p = TestUpdatePackage::new();
64        assert_matches!(p.verify_board("kim").await, Ok(()));
65    }
66
67    #[fuchsia::test]
68    async fn verify_board_failure_verify_contents() {
69        let p = TestUpdatePackage::new().add_file("board", "khloe").await;
70        assert_matches!(
71            p.verify_board("kendall").await,
72            Err(VerifyBoardError::VerifyContents { expected, found })
73                if expected=="kendall" && found=="khloe"
74        );
75    }
76}