Testing GCP Cloud Function trigger with PubSub testcontainer

487 Views Asked by At

Is there any way to do integration tests for the Cloud Function using PubSubEmulatorContainer?

My Cloud Function is triggered by the message in the PubSub topic as follows

@Component
@RequiredArgsConstructor
public class MessageIngest implements Consumer<PubSubMessage> {

    private final MessageResource msgResource;
    private final ObjectMapper objectMapper;


    @Override
    public void accept(PubSubMessage pubSubMessage) {
        var message = new String(Base64.getDecoder().decode(pubSubMessage.getData()), UTF_8);
        msgResource.ingest(objectMapper.readValue(message, Message.class));
    }
}

So far what I found about using PubSubEmulatorContainer for the integration testing is to publish there or subscribe from nothing about how to listen to the topic and trigger the test on publishing to the topic. My assumption is that I need to do that within the contextLoads() test.

For the live code trigger is provided during the deployment as an argument

gcloud functions deploy myCloudFunction --trigger-topic=$TOPIC_TO_LISTEN

PS. Provided example from the comments fails for me on testconainers version 1.18.0

testSend() errors out as

[ault-executor-0] c.g.c.s.p.c.p.PubSubPublisherTemplate    : Publishing to test-topic topic failed.
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Topic not found
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Subscription does not exist

and testWorker() as

[ault-executor-0] c.g.c.s.p.c.p.PubSubPublisherTemplate    : Publishing to test-topic topic failed.
com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Topic not found
com.google.api.gax.rpc.NotFoundException: com.google.api.gax.rpc.NotFoundException: io.grpc.StatusRuntimeException: NOT_FOUND: Subscription does not exist (resource=test-subscription)
1

There are 1 best solutions below

0
Joevanie On
There is a way to do integration tests for the Cloud Function using PubSubEmulatorContainer. You can follow this documentation.