mn2022
mn2022

Reputation: 15

gRPC Python: Can't instantiate abstract class ServicerContext

I am trying to test the following method:

def my_method(self, request, context):
    context.set_details('Already exists')
    context.set_code(grpc.StatusCode.ALREADY_EXISTS)

To test it, I must pass in a request and a context (which is a grpc.ServicerContext object), like so:

import grcp

def test_my_method(self):
    request = {"something": "something-else"}
    context = grpc.ServicerContext()

    my_method(request, context)

    # Assert something here

The problem is, I get the following error when I run my tests:

TypeError: Can't instantiate abstract class ServicerContext with abstract methods add_callback, cancel, invocation_metadata, is_active, peer, send_initial_metadata, set_code, set_details, set_trailing_metadata, time_remaining

How can I get a grpc.ServicerContext object? If I can't, how do I test the method?

Upvotes: 1

Views: 985

Answers (1)

grpc.ServicerContext is an abstract class defined with the abc module. In your test you need to write your own concrete subclass of it and pass an instance of that to the method you are testing.

Upvotes: 2

Related Questions