pytest-grpc plugin

0.8.0 · active · verified Thu Apr 16

pytest-grpc is a pytest plugin for testing gRPC services. It provides fixtures to start and stop gRPC servers and clients, allowing interaction with gRPC services during tests. The current stable version is 0.8.0, with releases occurring as new features are added or significant bugs are fixed, often following `pytest` or `grpcio` releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `pytest-grpc` using `conftest.py` to provide a test servicer and its `add_to_server` function. It then shows how to write a basic test using the `grpc_stub` fixture, which automatically handles server setup and client stub creation, or using `grpc_channel` to create a stub manually. This setup assumes you have generated Python gRPC code from your `.proto` definitions.

# conftest.py
import pytest
import grpc

# Assuming you have compiled your_service.proto into your_service_pb2.py and your_service_pb2_grpc.py
# e.g., using 'python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. your_service.proto'
import your_service_pb2_grpc
from your_service_pb2 import HelloRequest, HelloReply

# Define your gRPC Servicer implementation
class MyTestServicer(your_service_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return HelloReply(message=f"Hello, {request.name} from test!")

# Provide the servicer instance
@pytest.fixture(scope='session')
def grpc_servicer():
    return MyTestServicer()

# Provide the 'add_to_server' function from your generated _grpc module
@pytest.fixture(scope='session')
def grpc_add_to_server():
    return your_service_pb2_grpc.add_GreeterServicer_to_server

# test_service.py
import your_service_pb2

def test_say_hello(grpc_stub):
    # grpc_stub is an automatically created stub for your service
    request = your_service_pb2.HelloRequest(name="World")
    response = grpc_stub.SayHello(request)
    assert response.message == "Hello, World from test!"

def test_say_hello_with_channel(grpc_channel):
    # You can also create a stub manually if needed
    stub = your_service_pb2_grpc.GreeterStub(grpc_channel)
    request = your_service_pb2.HelloRequest(name="ChannelUser")
    response = stub.SayHello(request)
    assert response.message == "Hello, ChannelUser from test!"

view raw JSON →