8

Recently I have been getting my hand dirty to mock gRPC calls in python using MagicMock() but I have been not successful in mocking gRPC response message which I have got. Here is the piece of code python client code

def senor_read(self, server_end_point)
with grpc.insecure_channel(server_end_point) as grpc_channel:
    grpc_stub = sensorservice_pb2_grpc.getsensorinfostub(grpc_channel)
    sensor_response = yield grpc_stub.getsensorreading(sensorservice_pb2_grpc.request(
                    sensorname=name, account=account))
    if sensor_response.ok:
        print(" Successful sensor reading")
    elf sensor_resonse.error:
        raise Sensor_ErrorReading(why="Not able to read sensor)

    return convert_resoonse_to_dict(sensor_response)

here is the way i have mocked it (Still novice learning mocking framework)

sensorservice_pb2_grpc = MagicMock()
sensorservice_pb2_grpc.getsensorinfostub = MagicMock()
mock_grpc_stub = MagicMock()
mock_grpc_channel = MagicMock()
mock_grpc_channel.grpc.insecure_channel = MagicMock()
mock_grpc_channel.grpc_channel = MagicMock()
mock_grpc_response = MagicMock(mock_grpc_stub.getsensorreading)
type(mock_grpc_response.return_value).error = PropertyMock(return_value=True)

Flow is python function senor_read() does a gRPC request to the remote server and fetches the reading and passes back to the caller.

The intention of this test is to make the code execute in "eif" case and catch the exception. 1) When i execute the test code, it doesn't go to "elf" if case and i see some other exception is sent to the caller. Am I setting the state correctly in gRPC response mocking?

2) Are my mocking steps correct for mocking gRPC calls?

3) Also when I run I am not able to see print messages upon success but only on failure test case prints. Also, the prints in actual function are not printed?

I did search a lot, couldn't find much info on mocking gRPC in python.

pkumarn
  • 1,383
  • 4
  • 22
  • 29
  • the func could be broken into more functions, it is easier to do a validation test, but too complicated to do a real unittest and mock – Gang Jan 17 '19 at 23:50
  • How about using a real gRPC server with response that you want in test? Like this answer: https://stackoverflow.com/a/55500209/5238892 – Cloud Jun 28 '19 at 13:41

0 Answers0