モック クライアントを使用してテストを作成する

Rust 用 Cloud クライアント ライブラリを使用すると、実際のクライアント実装をスタブ化し、単体テスト用のモックを挿入できます。モック クライアントを使用すると、ネットワーク呼び出しを行わず、請求料金が発生しない、制御された信頼性の高い単体テストを作成できます。

始める前に

このドキュメントのコードを実行する前に、Rust を使ってみるに沿って Rust をインストールし、Cargo プロジェクトを設定します。

依存関係

このドキュメントでは、モック フレームワークとして mockall クレートを使用し、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 エイリアスを追加して、クレート名を短縮します。

    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