使用模擬用戶端編寫測試

Rust 適用的 Cloud 用戶端程式庫可讓您虛設常式實際用戶端實作,並插入模擬項目進行單元測試。使用模擬用戶端,即可編寫可控、可靠的單元測試,不會發出網路呼叫或產生費用。

事前準備

執行本文件中的程式碼前,請先按照「開始使用 Rust」一文的說明安裝 Rust,並設定 Cargo 專案。

依附元件

本文使用 mockall crate 做為模擬架構,並使用 Speech-to-Text 的 Speech 用戶端來說明工作流程。其他產生的用戶端也適用相同模式。

將用戶端程式庫和 google-cloud-gax 新增至 Cargo.toml 檔案:

cargo add google-cloud-speech-v2 google-cloud-gax

新增 mockall 和 tokio 做為開發依附元件:

cargo add --dev mockall
cargo add --dev tokio --features macros,rt-multi-thread

模擬用戶端

如要測試程式碼,而不進行網路呼叫,請在模擬結構體上實作服務的虛設常式特徵,並設定其預期。接著,使用 from_stub 建構用戶端,並傳遞至應用程式函式:

  1. 新增 use 別名,縮短 Crate 名稱:

    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;

  2. 編寫應用程式函式,接受 Speech 用戶端的參照、呼叫 get_recognizer,並處理伺服器回應:

    // An example application function.
    //
    // It makes an RPC, setting some field. In this case, it is the `GetRecognizer`
    // RPC, setting the name field.
    //
    // It processes the response from the server. In this case, it extracts the
    // display name of the recognizer.
    async fn my_application_function(client: &speech::client::Speech) -> gax::Result<String> {
        client
            .get_recognizer()
            .set_name("invalid-test-recognizer")
            .send()
            .await
            .map(|r| r.display_name)
    }

  3. 使用 mockall::mock! 定義實作 speech::stub::Speech 特徵的模擬結構體:

    mockall::mock! {
        #[derive(Debug)]
        Speech {}
        impl speech::stub::Speech for Speech {
            async fn get_recognizer(&self, req: speech::model::GetRecognizerRequest, _options: gax::options::RequestOptions) -> gax::Result<gax::response::Response<speech::model::Recognizer>>;
        }
    }

  4. 在測試中建立模擬例項。mockall::mock! 巨集會在結構體名稱前加上 Mock,建立 MockSpeech:

    let mut mock = MockSpeech::new();

  5. 設定模擬物件的預期行為,驗證傳入的要求欄位,並傳回模擬的 Recognizer 回應:

    mock.expect_get_recognizer()
        .withf(move |r, _|
            // Optionally, verify fields in the request.
            r.name == "invalid-test-recognizer")
        .return_once(|_, _| {
            Ok(gax::response::Response::from(
                speech::model::Recognizer::new().set_display_name("test-display-name"),
            ))
        });

  6. 使用 Speech::from_stub 從模擬物件建構 Speech 用戶端:

    let client = speech::client::Speech::from_stub(mock);

  7. 使用模擬用戶端呼叫應用程式函式:

    let display_name = my_application_function(&client).await?;

  8. 驗證傳回的值:

    assert_eq!(display_name, "test-display-name");

模擬錯誤

如要測試錯誤處理,請將模擬預期設為傳回以 Error::service 建構的 Err:

mock.expect_get_recognizer().return_once(|_, _| {
    // This time, return an error.
    use gax::error::Error;
    use gax::error::rpc::{Code, Status};
    let status = Status::default()
        .set_code(Code::NotFound)
        .set_message("Resource not found");
    Err(Error::service(status))
});

完整程式碼

以下範例將成功和錯誤單元測試合併為完整的測試模組:

#[cfg(test)]
mod tests {
    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;
    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

    // An example application function.
    //
    // It makes an RPC, setting some field. In this case, it is the `GetRecognizer`
    // RPC, setting the name field.
    //
    // It processes the response from the server. In this case, it extracts the
    // display name of the recognizer.
    async fn my_application_function(client: &speech::client::Speech) -> gax::Result<String> {
        client
            .get_recognizer()
            .set_name("invalid-test-recognizer")
            .send()
            .await
            .map(|r| r.display_name)
    }

    mockall::mock! {
        #[derive(Debug)]
        Speech {}
        impl speech::stub::Speech for Speech {
            async fn get_recognizer(&self, req: speech::model::GetRecognizerRequest, _options: gax::options::RequestOptions) -> gax::Result<gax::response::Response<speech::model::Recognizer>>;
        }
    }

    #[tokio::test]
    async fn basic_success() -> Result<()> {
        // Create a mock, and set expectations on it.
        let mut mock = MockSpeech::new();
        mock.expect_get_recognizer()
            .withf(move |r, _|
                // Optionally, verify fields in the request.
                r.name == "invalid-test-recognizer")
            .return_once(|_, _| {
                Ok(gax::response::Response::from(
                    speech::model::Recognizer::new().set_display_name("test-display-name"),
                ))
            });

        // Create a client, implemented by the mock.
        let client = speech::client::Speech::from_stub(mock);

        // Call our function.
        let display_name = my_application_function(&client).await?;

        // Verify the final result of the RPC.
        assert_eq!(display_name, "test-display-name");

        Ok(())
    }

    #[tokio::test]
    async fn basic_fail() -> Result<()> {
        let mut mock = MockSpeech::new();
        mock.expect_get_recognizer().return_once(|_, _| {
            // This time, return an error.
            use gax::error::Error;
            use gax::error::rpc::{Code, Status};
            let status = Status::default()
                .set_code(Code::NotFound)
                .set_message("Resource not found");
            Err(Error::service(status))
        });

        // Create a client, implemented by the mock.
        let client = speech::client::Speech::from_stub(mock);

        // Call our function.
        let display_name = my_application_function(&client).await;

        // Verify the final result of the RPC.
        assert!(display_name.is_err(), "{display_name:?}");

        Ok(())
    }
}

執行 cargo test 即可執行單元測試:

cargo test