Scrivere test utilizzando un client simulato

Le librerie client di Cloud per Rust ti consentono di creare stub di implementazioni client reali e di inserire un mock per i test delle unità. L'utilizzo di un client fittizio ti consente di scrivere test delle unità controllati e affidabili che non effettuano chiamate di rete o addebiti.

Prima di iniziare

Prima di eseguire il codice in questo documento, segui Inizia a utilizzare Rust per installare Rust e configurare un progetto Cargo.

Dipendenze

Questo documento utilizza il crate mockall come framework di simulazione e il client Speech di Speech-to-Text per illustrare il workflow. Lo stesso pattern si applica ad altri client generati.

Aggiungi la libreria client e google-cloud-gax al file Cargo.toml:

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

Aggiungi mockall e tokio come dipendenze di sviluppo:

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

Simula un client

Per testare il codice senza chiamate di rete, implementa il tratto stub del servizio su una struttura fittizia e configura le relative aspettative. Quindi, crea un client con from_stub e passalo alla funzione dell'applicazione:

  1. Aggiungi alias use per abbreviare i nomi dei crate:

    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;

  2. Scrivi una funzione dell'applicazione che accetti un riferimento al client Speech, chiami get_recognizer ed elabori la risposta del server:

    // 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. Definisci una struttura fittizia che implementi il tratto speech::stub::Speech utilizzando mockall::mock!:

    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. Nel test, crea un'istanza del mock. La macro mockall::mock! antepone Mock al nome della struttura per creare MockSpeech:

    let mut mock = MockSpeech::new();

  5. Configura le aspettative sul mock per convalidare i campi della richiesta in entrata e restituire una risposta Recognizer simulata:

    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. Crea un client Speech dal mock utilizzando Speech::from_stub:

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

  7. Chiama la funzione dell'applicazione con il client fittizio:

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

  8. Verifica il valore restituito:

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

Simula errori

Per testare la gestione degli errori, configura l'aspettativa fittizia in modo che restituisca un Err creato con Error::service:

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))
});

Completamento del codice

L'esempio seguente combina i test delle unità di esito positivo e di errore in un modulo di test completo:

#[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(())
    }
}

Esegui cargo test per eseguire i test delle unità:

cargo test