-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add MockJSONRPCServer test utility for JSON-RPC service mocking #7723
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: TT-16492-json-rpc-mcp-request-handling
Are you sure you want to change the base?
Add MockJSONRPCServer test utility for JSON-RPC service mocking #7723
Conversation
This extends the test framework with utilities to simplify testing JSON-RPC endpoints: - MockJSONRPCServer: A configurable mock server that can return static or dynamic responses, record received requests, and support assertions - Request builders: Helper functions for creating tools/call, resources/read, and prompts/get JSON-RPC payloads - Integration tests: Demonstrates usage for rate limiting and ACL testing Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
|
This PR introduces a comprehensive test utility, The utility includes:
Files Changed Analysis
This pull request consists entirely of new files, adding 1,211 lines of code dedicated to enhancing the gateway's test framework without modifying any existing production logic. Architecture & Impact Assessment
Test ArchitectureThe following diagram illustrates how graph TD
subgraph Test Environment
A[Gateway Integration Test] --> B(Tyk Gateway Instance);
B --> C{MockJSONRPCServer};
A -- asserts on --> C;
end
A -- 1. Sends JSON-RPC request --> B;
B -- 2. Proxies request to upstream --> C;
C -- 3. Returns mocked response --> B;
B -- 4. Returns final response --> A;
A -- 5. Verifies recorded requests --> C;
style C fill:#f9f,stroke:#333,stroke-width:2px
Scope Discovery & Context ExpansionThis utility is a direct dependency for testing the JSON-RPC/MCP features introduced in PR #7719. The tests included in this PR (e.g., To understand the full context, a reviewer should examine the gateway's middleware and proxying logic that handles requests for APIs marked as MCP endpoints (via Metadata
Powered by Visor from Probelabs Last updated: 2026-02-01T10:56:06.215Z | Triggered by: pr_updated | Commit: 0307347 💡 TIP: You can chat with Visor using |
Security Issues (2)
Architecture Issues (2)
Performance Issues (1)
Quality Issues (3)
Powered by Visor from Probelabs Last updated: 2026-02-01T10:56:09.036Z | Triggered by: pr_updated | Commit: 0307347 💡 TIP: You can chat with Visor using |
|
API Changes --- prev.txt 2026-02-01 10:55:33.145210574 +0000
+++ current.txt 2026-02-01 10:55:23.208306883 +0000
@@ -9274,6 +9274,18 @@
func AuthFailed(m TykMiddleware, r *http.Request, token string)
TODO: move this method to base middleware?
+func BuildJSONRPCRequest(method string, params any, id any) map[string]any
+ BuildJSONRPCRequest builds a JSON-RPC 2.0 request payload.
+
+func BuildPromptsGetRequest(name string, arguments map[string]any, id any) map[string]any
+ BuildPromptsGetRequest builds a JSON-RPC request for prompts/get.
+
+func BuildResourcesReadRequest(uri string, id any) map[string]any
+ BuildResourcesReadRequest builds a JSON-RPC request for resources/read.
+
+func BuildToolsCallRequest(toolName string, arguments map[string]any, id any) map[string]any
+ BuildToolsCallRequest builds a JSON-RPC request for tools/call.
+
func CheckPortWhiteList(w map[string]config.PortWhiteList, listenPort int, protocol string) error
func CoProcessLog(CMessage, CLogLevel *C.char)
CoProcessLog is a bridge for using Tyk log from CP.
@@ -9367,6 +9379,9 @@
WithQuotaKey overrides quota key manually
func WrappedCharsetReader(s string, i io.Reader) (io.Reader, error)
+func ParseJSONRPCResponse(data []byte) (*jsonRPCResponse, error)
+ ParseJSONRPCResponse parses a JSON-RPC response from a byte slice.
+
TYPES
@@ -10832,6 +10847,10 @@
}
JSONRPCErrorResponse represents a JSON-RPC 2.0 error response.
+type JSONRPCHandler func(t *testing.T, method string, params json.RawMessage) (result any, errCode int, errMsg string)
+ JSONRPCHandler is a function that handles a JSON-RPC request and returns a
+ result or error.
+
type JSONRPCMiddleware struct {
*BaseMiddleware
}
@@ -10858,6 +10877,15 @@
}
JSONRPCRequest represents a JSON-RPC 2.0 request structure.
+type JSONRPCTestCase struct {
+ Method string // JSON-RPC method to call
+ Params any // Parameters for the method
+ ID any // Request ID (default: 1)
+ ExpectErr bool // Whether to expect a JSON-RPC error
+ ErrCode int // Expected error code (if ExpectErr is true)
+}
+ JSONRPCTestCase extends test.TestCase with JSON-RPC specific fields.
+
type JSVM struct {
Spec *APISpec
VM *otto.Otto `json:"-"`
@@ -11102,6 +11130,53 @@
func (e *MockErrorReader) Read(_ []byte) (n int, err error)
+type MockJSONRPCServer struct {
+ Server *httptest.Server
+
+ // Has unexported fields.
+}
+ MockJSONRPCServer provides a configurable mock JSON-RPC 2.0 server for
+ testing. It supports static mock responses, dynamic handlers for assertions,
+ and request recording.
+
+func NewMockJSONRPCServer() *MockJSONRPCServer
+ NewMockJSONRPCServer creates a new mock JSON-RPC server.
+
+func (m *MockJSONRPCServer) Close()
+ Close shuts down the mock server.
+
+func (m *MockJSONRPCServer) MockMethod(method string, result any)
+ MockMethod sets a static response for a JSON-RPC method. The result will be
+ returned in the "result" field of the JSON-RPC response.
+
+func (m *MockJSONRPCServer) MockMethodHandler(method string, handler JSONRPCHandler)
+ MockMethodHandler sets a dynamic handler for a JSON-RPC method. The handler
+ can perform assertions and return dynamic results.
+
+func (m *MockJSONRPCServer) MockMethodRaw(method string, rawResult json.RawMessage)
+ MockMethodRaw sets a raw JSON response for a JSON-RPC method.
+
+func (m *MockJSONRPCServer) ReceivedRequests() []ReceivedJSONRPCRequest
+ ReceivedRequests returns all received JSON-RPC requests.
+
+func (m *MockJSONRPCServer) ReceivedRequestsForMethod(method string) []ReceivedJSONRPCRequest
+ ReceivedRequestsForMethod returns all received requests for a specific
+ method.
+
+func (m *MockJSONRPCServer) Reset()
+ Reset clears all mocked methods, handlers, and recorded requests.
+
+func (m *MockJSONRPCServer) SetDefaultResponse(result any)
+ SetDefaultResponse sets a default response for unmocked methods. If set,
+ errorOnUnmocked is automatically set to false.
+
+func (m *MockJSONRPCServer) SetErrorOnUnmocked(enabled bool)
+ SetErrorOnUnmocked controls whether unmocked methods return an error
+ (default: true).
+
+func (m *MockJSONRPCServer) URL() string
+ URL returns the URL of the mock server.
+
type MockReadCloser struct {
Reader io.Reader
CloseError error
@@ -11599,6 +11674,15 @@
ProcessRequest will run any checks on the request on the way through the
system, return an error to have the chain fail
+type ReceivedJSONRPCRequest struct {
+ Method string
+ Params json.RawMessage
+ ID any
+ Headers http.Header // HTTP headers received with the request
+}
+ ReceivedJSONRPCRequest records a received JSON-RPC request for later
+ assertions.
+
type RedisAnalyticsHandler struct {
Store storage.AnalyticsHandler
GeoIPDB *maxminddb.Reader |
… transformations This commit extends the test suite for PR #7723 with five new integration test scenarios: 1. TestJSONRPC_MethodLevelAllowList: Validates that method-level allow lists correctly proxy allowed tools and reject disallowed tools (Acceptance Criteria #1) 2. TestJSONRPC_ToolLevelAllowList: Validates that tool-level allow lists correctly handle multiple allowed tools and reject disallowed ones (Acceptance Criteria #2) 3. TestJSONRPC_MethodLevelRateLimiting: Validates that rate limits at the method level are correctly enforced (Acceptance Criteria #3) 4. TestJSONRPC_ToolLevelIndependentRateLimiting: Validates that rate limits for different tools are applied independently (Acceptance Criteria #4) 5. TestJSONRPC_CombinedHeaderTransformations: Validates that request transformation headers are correctly applied to upstream requests (Acceptance Criteria #5) Also extends MockJSONRPCServer to record HTTP headers for verification in the header transformation test, and adds TestMockJSONRPCServer_HeaderRecording unit test. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
🚨 Jira Linter FailedCommit: The Jira linter failed to validate your PR. Please check the error details below: 🔍 Click to view error detailsNext Steps
This comment will be automatically deleted once the linter passes. |
Summary
Extends the Tyk Gateway test framework with utilities for mocking JSON-RPC 2.0 services, making it easier to write integration tests for the new JSON-RPC/MCP features introduced in #7719.
MockJSONRPCServer: A configurable mock server that supports:
MockMethod()MockMethodHandler()Request builders: Helper functions to construct JSON-RPC payloads:
BuildToolsCallRequest()- for tools/callBuildResourcesReadRequest()- for resources/readBuildPromptsGetRequest()- for prompts/getBuildJSONRPCRequest()- generic builderIntegration tests: Demonstrates usage patterns for:
Test plan
🤖 Generated with Claude Code