Tests failing when using ClientInterceptor to add headers to the stub

1.1k views Asked by At

In the following code MetadataUtils.attachHeaders is deprecated (I'm using grpc 1.45.1):

    "request without bearer token should fail" {
        val channel: ManagedChannel = ManagedChannelBuilder.forAddress(address, port)
            .usePlaintext()
            .build()
        var stub = RuleAPIGrpc.newBlockingStub(channel)

        val metadata = Metadata()
        metadata.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), "no token ")
        stub = MetadataUtils.attachHeaders(stub, metadata)

        val exception = shouldThrow<StatusRuntimeException> {
            stub.getRule(
                RuleApiProto.GetRuleRequest.newBuilder().build()
            )
        }

        exception.status.code.name shouldBe Code.UNAUTHENTICATED.name
        exception.status.description shouldBe Errors.MISSING_BEARER_TOKEN.name

        channel.shutdown()
    }

I tried to replace it with:

stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata))

But then tests are failing, because of missing AUTH header. When I add the interceptor to the channel:

.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata))

then everything works fine.

And ideas why it doesn't work for the stub?

1

There are 1 answers

2
San P On

Not clear from your description if you are already doing this, but you'll need to use the returned value of the stub from withInterceptors() like this:

stub 
  = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));

stub.getRule(...)...