Escrever testes usando um cliente simulado

As bibliotecas de cliente do Cloud para Rust permitem que você faça o stub de implementações de cliente reais e injete um modelo para teste de unidade. O uso de um cliente simulado permite que você escreva testes de unidade controlados e confiáveis que não fazem chamadas de rede nem geram cobranças.

Antes de começar

Antes de executar o código neste documento, siga as instruções em Começar a usar o Rust para instalar o Rust e configurar um projeto do Cargo.

Dependências

Neste documento, usamos o crate mockall como framework de simulação e o cliente Speech do Speech-to-Text para ilustrar o fluxo de trabalho. O mesmo padrão se aplica a outros clientes gerados.

Adicione a biblioteca de cliente e google-cloud-gax ao arquivo Cargo.toml:

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

Adicione mockall e tokio como dependências de desenvolvimento:

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

Simular um cliente

Para testar o código sem chamadas de rede, implemente o atributo de stub do serviço em uma estrutura simulada e configure as expectativas. Em seguida, crie um cliente com from_stub e transmita-o para a função do aplicativo:

  1. Adicione aliases use para encurtar os nomes dos crates:

    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;

  2. Escreva uma função de aplicativo que aceite uma referência ao cliente Speech, chame get_recognizer e processe a resposta do servidor:

    // 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. Defina uma struct simulada que implemente a característica speech::stub::Speech usando 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. No teste, crie uma instância do simulado. A macro mockall::mock! anexa Mock ao nome do struct para criar MockSpeech:

    let mut mock = MockSpeech::new();

  5. Configure as expectativas no simulador para validar os campos de solicitação recebidos e retornar uma resposta Recognizer simulada:

    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. Crie um cliente Speech do simulado usando Speech::from_stub:

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

  7. Chame a função do aplicativo com o cliente simulado:

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

  8. Verifique o valor retornado:

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

Simular erros

Para testar o tratamento de erros, configure a expectativa simulada para retornar um Err construído com 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))
});

Preencher código

O exemplo a seguir combina os testes de unidade de sucesso e erro em um módulo de teste 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(())
    }
}

Execute cargo test para executar os testes de unidade:

cargo test