grpc-mock
БесплатноБез исполняемых скриптовНе проверенUse when gRPC client code needs tests against a controllable fake server, or a gRPC interceptor needs tests: Go bufconn and mockgen, Python pytest-grpc, JVM…
от testland★ 18 звёзд на GitHubОб этом скилле
grpc-mock
Overview
Mocking a gRPC server lets client-side tests exercise success
paths, every grpc.StatusCode (per the status-code catalog in
grpc-streaming-test-author, references/status-codes.md),
timeouts, and streaming sequences without a real backend. The
in-process harness is also the substrate for interceptor tests -
see references/interceptors.md.
Three approaches dominate, picked by language:
| Approach | Mechanism |
|---|---|
| In-process gRPC server | A real grpc.Server listens on an in-memory transport (bufconn in Go, InProcessServerBuilder in JVM). Tests exercise the full client stack. |
| Interface mock | mockgen / gomock (Go) / Mockito (JVM) / unittest.mock (Python) replace the generated client stub with a programmable mock. Faster but skips marshalling. |
| Standalone mock server | Run a tool like grpcmock / dishwasher as a subprocess. Cross-language client testing. |
When to use
- Client-side tests need controllable gRPC responses (success + error matrix).
- Streaming-RPC tests need a server that sends a deterministic sequence.
- Mid-test failure injection (deadline / cancellation / status code).
- Tests must not depend on a running backend (offline CI).
- Cross-service contract testing: want the client to see what the contract says, not what the current server happens to do.
Authoring
Go: bufconn + in-process server
Per
pkg.go.dev/google.golang.org/grpc/test/bufconn,
bufconn.Listener is the canonical in-memory transport:
package myservice_test
import (
"context"
"net"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
pb "example.com/proto"
)
const bufSize = 1024 * 1024
type fakeServer struct {
pb.UnimplementedUserServiceServer
nextResponse *pb.User
nextErr error
}
func (f *fakeServer) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
if f.nextErr != nil {
return nil, f.nextErr
}
return f.nextResponse, nil
}
func setupClient(t *testing.T, fake *fakeServer) pb.UserServiceClient {
lis := bufconn.Listen(bufSize)
s := grpc.NewServer()
pb.RegisterUserServiceServer(s, fake)
go func() { _ = s.Serve(lis) }()
t.Cleanup(func() { s.Stop() })
conn, err := grpc.DialContext(context.Background(), "bufnet",
grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil { t.Fatal(err) }
t.Cleanup(func() { conn.Close() })
return pb.NewUserServiceClient(conn)
}
func TestGetUser_NotFound(t *testing.T) {
fake := &fakeServer{
nextErr: status.Error(codes.NotFound, "user does not exist"),
}
client := setupClient(t, fake)
_, err := client.GetUser(context.Background(), &pb.GetUserRequest{Id: "missing"})
st, _ := status.FromError(err)
if st.Code() != codes.NotFound {
t.Fatalf("got %v, want NotFound", st.Code())
}
}
Per the status-code catalog in grpc-streaming-test-author
(references/status-codes.md):
assert on status.Code(), not on error message strings.
Go: gomock / mockgen (interface mock)
For tests that don't need the marshalling/transport stack:
go install go.uber.org/mock/mockgen@latest
mockgen -source=gen/user_grpc.pb.go -destination=mocks/user_mock.go
import (
"testing"
"go.uber.org/mock/gomock"
pb "example.com/proto"
mocks "example.com/mocks"
)
func TestServiceWithMockClient(t *testing.T) {
ctrl := gomock.NewController(t)
mockClient := mocks.NewMockUserServiceClient(ctrl)
mockClient.EXPECT().
GetUser(gomock.Any(), gomock.Eq(&pb.GetUserRequest{Id: "u1"})).
Return(&pb.User{Id: "u1", Name: "Alice"}, nil)
// Test the code that uses mockClient ...
}
Tradeoff: doesn't exercise serialisation; faster, less fidelity.
Python: in-process server + pytest fixture
import grpc
import pytest
from concurrent import futures
from user_pb2 import User, GetUserRequest
from user_pb2_grpc import UserServiceServicer, add_UserServiceServicer_to_server, UserServiceStub
class FakeUserService(UserServiceServicer):
next_response = None
next_status = None
def GetUser(self, request, context):
if self.next_status is not None:
context.abort(self.next_status, "fake error")
return self.next_response
@pytest.fixture
def fake_service():
return FakeUserService()
@pytest.fixture
def grpc_channel(fake_service):
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
add_UserServiceServicer_to_server(fake_service, server)
port = server.add_insecure_port("[::]:
Установить grpc-mock в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл grpc-mock?
Use when gRPC client code needs tests against a controllable fake server, or a gRPC interceptor needs tests: Go bufconn and mockgen, Python pytest-grpc, JVM in-process servers, Node fake servers, with success, error and timeout responses. Streaming sequences are grpc-streaming-test-author.
Как установить скилл grpc-mock?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл grpc-mock запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic