Fixed linter errors and fixed tests
- Added error handling for JSON encoding in ServersHandler and ServersDetailHandler. - Updated test cases to reflect changes in handler functions and improved mock expectations. - Refactored server initialization to include ReadHeaderTimeout for better request handling. - Modified GitHubDeviceAuth to accept context in ValidateToken and checkOrgMembership methods. - Improved error messages in database import functions for better debugging. - Updated memory and mongo database list functions to accept context and improved filtering logic. - Enhanced logging in publisher tool for better visibility during execution. - Cleaned up code formatting and comments for better readability and maintainability.
This commit is contained in:
parent
c74a7af000
commit
b6c141a721
11 changed files with 317 additions and 225 deletions
|
|
@ -64,11 +64,14 @@ func StartAuthHandler(authService auth.Service) http.HandlerFunc {
|
|||
// Return successful response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"flow_info": flowInfo,
|
||||
"status_token": statusToken,
|
||||
"expires_in": 300, // 5 minutes
|
||||
})
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -95,9 +98,12 @@ func CheckAuthStatusHandler(authService auth.Service) http.HandlerFunc {
|
|||
// Auth is still pending
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": "pending",
|
||||
})
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -109,9 +115,12 @@ func CheckAuthStatusHandler(authService auth.Service) http.HandlerFunc {
|
|||
// Authentication completed successfully
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": "complete",
|
||||
"token": token,
|
||||
})
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,16 +10,18 @@ import (
|
|||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
GitHubClientId string `json:"github_client_id"`
|
||||
GitHubClientID string `json:"github_client_id"`
|
||||
}
|
||||
|
||||
// HealthHandler returns a handler for health check endpoint
|
||||
func HealthHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(HealthResponse{
|
||||
if err := json.NewEncoder(w).Encode(HealthResponse{
|
||||
Status: "ok",
|
||||
GitHubClientId: cfg.GithubClientID,
|
||||
})
|
||||
GitHubClientID: cfg.GithubClientID,
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
package v0
|
||||
package v0_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
|
@ -16,7 +18,7 @@ func TestHealthHandler(t *testing.T) {
|
|||
name string
|
||||
config *config.Config
|
||||
expectedStatus int
|
||||
expectedBody HealthResponse
|
||||
expectedBody v0.HealthResponse
|
||||
}{
|
||||
{
|
||||
name: "returns health status with github client id",
|
||||
|
|
@ -24,9 +26,9 @@ func TestHealthHandler(t *testing.T) {
|
|||
GithubClientID: "test-github-client-id",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedBody: HealthResponse{
|
||||
expectedBody: v0.HealthResponse{
|
||||
Status: "ok",
|
||||
GitHubClientId: "test-github-client-id",
|
||||
GitHubClientID: "test-github-client-id",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -35,9 +37,9 @@ func TestHealthHandler(t *testing.T) {
|
|||
GithubClientID: "",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedBody: HealthResponse{
|
||||
expectedBody: v0.HealthResponse{
|
||||
Status: "ok",
|
||||
GitHubClientId: "",
|
||||
GitHubClientID: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -45,10 +47,10 @@ func TestHealthHandler(t *testing.T) {
|
|||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create handler with the test config
|
||||
handler := HealthHandler(tc.config)
|
||||
handler := v0.HealthHandler(tc.config)
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequest("GET", "/health", nil)
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/health", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
@ -66,7 +68,7 @@ func TestHealthHandler(t *testing.T) {
|
|||
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var resp HealthResponse
|
||||
var resp v0.HealthResponse
|
||||
err = json.NewDecoder(rr.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
|
@ -83,11 +85,18 @@ func TestHealthHandlerIntegration(t *testing.T) {
|
|||
GithubClientID: "integration-test-client-id",
|
||||
}
|
||||
|
||||
server := httptest.NewServer(HealthHandler(cfg))
|
||||
server := httptest.NewServer(v0.HealthHandler(cfg))
|
||||
defer server.Close()
|
||||
|
||||
// Send request to the test server
|
||||
resp, err := http.Get(server.URL)
|
||||
ctx := context.Background()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create request: %v", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to send request: %v", err)
|
||||
}
|
||||
|
|
@ -100,14 +109,14 @@ func TestHealthHandlerIntegration(t *testing.T) {
|
|||
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var healthResp HealthResponse
|
||||
var healthResp v0.HealthResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&healthResp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Check the response body
|
||||
expectedResp := HealthResponse{
|
||||
expectedResp := v0.HealthResponse{
|
||||
Status: "ok",
|
||||
GitHubClientId: "integration-test-client-id",
|
||||
GitHubClientID: "integration-test-client-id",
|
||||
}
|
||||
assert.Equal(t, expectedResp, healthResp)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ func PingHandler(cfg *config.Config) http.HandlerFunc {
|
|||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ func PublishHandler(registry service.RegistryService, authService auth.Service)
|
|||
|
||||
valid, err := authService.ValidateAuth(r.Context(), a)
|
||||
if err != nil {
|
||||
if err == auth.ErrAuthRequired {
|
||||
if errors.Is(err, auth.ErrAuthRequired) {
|
||||
http.Error(w, "Authentication is required for publishing", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
|
@ -119,9 +119,12 @@ func PublishHandler(registry service.RegistryService, authService auth.Service)
|
|||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
if err := json.NewEncoder(w).Encode(map[string]string{
|
||||
"message": "Server publication successful",
|
||||
"id": serverDetail.ID,
|
||||
})
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
package v0
|
||||
package v0_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"github.com/modelcontextprotocol/registry/internal/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -20,17 +21,17 @@ type MockRegistryService struct {
|
|||
}
|
||||
|
||||
func (m *MockRegistryService) List(cursor string, limit int) ([]model.Server, string, error) {
|
||||
args := m.Called(cursor, limit)
|
||||
args := m.Mock.Called(cursor, limit)
|
||||
return args.Get(0).([]model.Server), args.String(1), args.Error(2)
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) GetByID(id string) (*model.ServerDetail, error) {
|
||||
args := m.Called(id)
|
||||
args := m.Mock.Called(id)
|
||||
return args.Get(0).(*model.ServerDetail), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) Publish(serverDetail *model.ServerDetail) error {
|
||||
args := m.Called(serverDetail)
|
||||
args := m.Mock.Called(serverDetail)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
|
|
@ -39,18 +40,20 @@ type MockAuthService struct {
|
|||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockAuthService) StartAuthFlow(ctx context.Context, method model.AuthMethod, repoRef string) (map[string]string, string, error) {
|
||||
args := m.Called(ctx, method, repoRef)
|
||||
func (m *MockAuthService) StartAuthFlow(
|
||||
ctx context.Context, method model.AuthMethod, repoRef string,
|
||||
) (map[string]string, string, error) {
|
||||
args := m.Mock.Called(ctx, method, repoRef)
|
||||
return args.Get(0).(map[string]string), args.String(1), args.Error(2)
|
||||
}
|
||||
|
||||
func (m *MockAuthService) CheckAuthStatus(ctx context.Context, statusToken string) (string, error) {
|
||||
args := m.Called(ctx, statusToken)
|
||||
args := m.Mock.Called(ctx, statusToken)
|
||||
return args.String(0), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockAuthService) ValidateAuth(ctx context.Context, authentication model.Authentication) (bool, error) {
|
||||
args := m.Called(ctx, authentication)
|
||||
args := m.Mock.Called(ctx, authentication)
|
||||
return args.Bool(0), args.Error(1)
|
||||
}
|
||||
|
||||
|
|
@ -87,12 +90,12 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
authHeader: "Bearer github_token_123",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.On("ValidateAuth", mock.Anything, model.Authentication{
|
||||
authSvc.Mock.On("ValidateAuth", mock.Anything, model.Authentication{
|
||||
Method: model.AuthMethodGitHub,
|
||||
Token: "github_token_123",
|
||||
RepoRef: "io.github.example/test-server",
|
||||
}).Return(true, nil)
|
||||
registry.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
registry.Mock.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
},
|
||||
expectedStatus: http.StatusCreated,
|
||||
expectedResponse: map[string]string{
|
||||
|
|
@ -122,12 +125,12 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
authHeader: "Bearer some_token",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.On("ValidateAuth", mock.Anything, model.Authentication{
|
||||
authSvc.Mock.On("ValidateAuth", mock.Anything, model.Authentication{
|
||||
Method: model.AuthMethodNone,
|
||||
Token: "some_token",
|
||||
RepoRef: "example/test-server",
|
||||
}).Return(true, nil)
|
||||
registry.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
registry.Mock.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
},
|
||||
expectedStatus: http.StatusCreated,
|
||||
expectedResponse: map[string]string{
|
||||
|
|
@ -140,7 +143,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
method: http.MethodGet,
|
||||
requestBody: nil,
|
||||
authHeader: "",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {},
|
||||
setupMocks: func(_ *MockRegistryService, _ *MockAuthService) {},
|
||||
expectedStatus: http.StatusMethodNotAllowed,
|
||||
expectedError: "Method not allowed",
|
||||
},
|
||||
|
|
@ -149,7 +152,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
method: http.MethodPost,
|
||||
requestBody: "",
|
||||
authHeader: "",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {},
|
||||
setupMocks: func(_ *MockRegistryService, _ *MockAuthService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Invalid request payload:",
|
||||
},
|
||||
|
|
@ -169,7 +172,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
authHeader: "",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {},
|
||||
setupMocks: func(_ *MockRegistryService, _ *MockAuthService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Name is required",
|
||||
},
|
||||
|
|
@ -189,7 +192,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
authHeader: "",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {},
|
||||
setupMocks: func(_ *MockRegistryService, _ *MockAuthService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Version is required",
|
||||
},
|
||||
|
|
@ -209,7 +212,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
authHeader: "", // Missing auth header
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {},
|
||||
setupMocks: func(_ *MockRegistryService, _ *MockAuthService) {},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Authorization header is required",
|
||||
},
|
||||
|
|
@ -229,8 +232,8 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
authHeader: "Bearer token",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.On("ValidateAuth", mock.Anything, mock.Anything).Return(false, auth.ErrAuthRequired)
|
||||
setupMocks: func(_ *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.Mock.On("ValidateAuth", mock.Anything, mock.Anything).Return(false, auth.ErrAuthRequired)
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Authentication is required for publishing",
|
||||
|
|
@ -251,8 +254,8 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
authHeader: "Bearer invalid_token",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.On("ValidateAuth", mock.Anything, mock.Anything).Return(false, nil)
|
||||
setupMocks: func(_ *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.Mock.On("ValidateAuth", mock.Anything, mock.Anything).Return(false, nil)
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid authentication credentials",
|
||||
|
|
@ -274,8 +277,8 @@ func TestPublishHandler(t *testing.T) {
|
|||
},
|
||||
authHeader: "Bearer token",
|
||||
setupMocks: func(registry *MockRegistryService, authSvc *MockAuthService) {
|
||||
authSvc.On("ValidateAuth", mock.Anything, mock.Anything).Return(true, nil)
|
||||
registry.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(assert.AnError)
|
||||
authSvc.Mock.On("ValidateAuth", mock.Anything, mock.Anything).Return(true, nil)
|
||||
registry.Mock.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(assert.AnError)
|
||||
},
|
||||
expectedStatus: http.StatusInternalServerError,
|
||||
expectedError: "Failed to publish server details:",
|
||||
|
|
@ -292,7 +295,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
tc.setupMocks(mockRegistry, mockAuthService)
|
||||
|
||||
// Create handler
|
||||
handler := PublishHandler(mockRegistry, mockAuthService)
|
||||
handler := v0.PublishHandler(mockRegistry, mockAuthService)
|
||||
|
||||
// Prepare request body
|
||||
var requestBody []byte
|
||||
|
|
@ -303,7 +306,7 @@ func TestPublishHandler(t *testing.T) {
|
|||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequest(tc.method, "/publish", bytes.NewBuffer(requestBody))
|
||||
req, err := http.NewRequestWithContext(context.Background(), tc.method, "/publish", bytes.NewBuffer(requestBody))
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Set auth header if provided
|
||||
|
|
@ -337,8 +340,8 @@ func TestPublishHandler(t *testing.T) {
|
|||
}
|
||||
|
||||
// Assert that all expectations were met
|
||||
mockRegistry.AssertExpectations(t)
|
||||
mockAuthService.AssertExpectations(t)
|
||||
mockRegistry.Mock.AssertExpectations(t)
|
||||
mockAuthService.Mock.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -377,12 +380,12 @@ func TestPublishHandlerBearerTokenParsing(t *testing.T) {
|
|||
mockAuthService := new(MockAuthService)
|
||||
|
||||
// Setup mock to capture the actual token passed
|
||||
mockAuthService.On("ValidateAuth", mock.Anything, mock.MatchedBy(func(auth model.Authentication) bool {
|
||||
mockAuthService.Mock.On("ValidateAuth", mock.Anything, mock.MatchedBy(func(auth model.Authentication) bool {
|
||||
return auth.Token == tc.expectedToken
|
||||
})).Return(true, nil)
|
||||
mockRegistry.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
mockRegistry.Mock.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
|
||||
handler := PublishHandler(mockRegistry, mockAuthService)
|
||||
handler := v0.PublishHandler(mockRegistry, mockAuthService)
|
||||
|
||||
serverDetail := model.ServerDetail{
|
||||
Server: model.Server{
|
||||
|
|
@ -400,7 +403,7 @@ func TestPublishHandlerBearerTokenParsing(t *testing.T) {
|
|||
requestBody, err := json.Marshal(serverDetail)
|
||||
assert.NoError(t, err)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/publish", bytes.NewBuffer(requestBody))
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/publish", bytes.NewBuffer(requestBody))
|
||||
assert.NoError(t, err)
|
||||
req.Header.Set("Authorization", tc.authHeader)
|
||||
|
||||
|
|
@ -408,7 +411,7 @@ func TestPublishHandlerBearerTokenParsing(t *testing.T) {
|
|||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
mockAuthService.AssertExpectations(t)
|
||||
mockAuthService.Mock.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -442,12 +445,12 @@ func TestPublishHandlerAuthMethodSelection(t *testing.T) {
|
|||
mockAuthService := new(MockAuthService)
|
||||
|
||||
// Setup mock to capture the auth method
|
||||
mockAuthService.On("ValidateAuth", mock.Anything, mock.MatchedBy(func(auth model.Authentication) bool {
|
||||
mockAuthService.Mock.On("ValidateAuth", mock.Anything, mock.MatchedBy(func(auth model.Authentication) bool {
|
||||
return auth.Method == tc.expectedAuthMethod
|
||||
})).Return(true, nil)
|
||||
mockRegistry.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
mockRegistry.Mock.On("Publish", mock.AnythingOfType("*model.ServerDetail")).Return(nil)
|
||||
|
||||
handler := PublishHandler(mockRegistry, mockAuthService)
|
||||
handler := v0.PublishHandler(mockRegistry, mockAuthService)
|
||||
|
||||
serverDetail := model.ServerDetail{
|
||||
Server: model.Server{
|
||||
|
|
@ -465,7 +468,7 @@ func TestPublishHandlerAuthMethodSelection(t *testing.T) {
|
|||
requestBody, err := json.Marshal(serverDetail)
|
||||
assert.NoError(t, err)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "/publish", bytes.NewBuffer(requestBody))
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/publish", bytes.NewBuffer(requestBody))
|
||||
assert.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer test_token")
|
||||
|
||||
|
|
@ -473,7 +476,7 @@ func TestPublishHandlerAuthMethodSelection(t *testing.T) {
|
|||
handler.ServeHTTP(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
mockAuthService.AssertExpectations(t)
|
||||
mockAuthService.Mock.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,7 +89,10 @@ func ServersHandler(registry service.RegistryService) http.HandlerFunc {
|
|||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -123,6 +126,9 @@ func ServersDetailHandler(registry service.RegistryService) http.HandlerFunc {
|
|||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(serverDetail)
|
||||
if err := json.NewEncoder(w).Encode(serverDetail); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package v0
|
||||
package v0_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
|
@ -8,6 +9,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
|
@ -21,7 +23,7 @@ func TestServersHandler(t *testing.T) {
|
|||
setupMocks func(*MockRegistryService)
|
||||
expectedStatus int
|
||||
expectedServers []model.Server
|
||||
expectedMeta *Metadata
|
||||
expectedMeta *v0.Metadata
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
|
|
@ -60,7 +62,7 @@ func TestServersHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
}
|
||||
registry.On("List", "", 30).Return(servers, "", nil)
|
||||
registry.Mock.On("List", "", 30).Return(servers, "", nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []model.Server{
|
||||
|
|
@ -119,7 +121,7 @@ func TestServersHandler(t *testing.T) {
|
|||
},
|
||||
}
|
||||
nextCursor := uuid.New().String()
|
||||
registry.On("List", mock.AnythingOfType("string"), 10).Return(servers, nextCursor, nil)
|
||||
registry.Mock.On("List", mock.AnythingOfType("string"), 10).Return(servers, nextCursor, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []model.Server{
|
||||
|
|
@ -139,7 +141,7 @@ func TestServersHandler(t *testing.T) {
|
|||
},
|
||||
},
|
||||
},
|
||||
expectedMeta: &Metadata{
|
||||
expectedMeta: &v0.Metadata{
|
||||
NextCursor: "", // This will be dynamically set in the test
|
||||
Count: 1,
|
||||
},
|
||||
|
|
@ -150,7 +152,7 @@ func TestServersHandler(t *testing.T) {
|
|||
queryParams: "?limit=150",
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
servers := []model.Server{}
|
||||
registry.On("List", "", 100).Return(servers, "", nil)
|
||||
registry.Mock.On("List", "", 100).Return(servers, "", nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []model.Server{},
|
||||
|
|
@ -159,7 +161,7 @@ func TestServersHandler(t *testing.T) {
|
|||
name: "invalid cursor parameter",
|
||||
method: http.MethodGet,
|
||||
queryParams: "?cursor=invalid-uuid",
|
||||
setupMocks: func(registry *MockRegistryService) {},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Invalid cursor parameter",
|
||||
},
|
||||
|
|
@ -167,7 +169,7 @@ func TestServersHandler(t *testing.T) {
|
|||
name: "invalid limit parameter - non-numeric",
|
||||
method: http.MethodGet,
|
||||
queryParams: "?limit=abc",
|
||||
setupMocks: func(registry *MockRegistryService) {},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Invalid limit parameter",
|
||||
},
|
||||
|
|
@ -175,7 +177,7 @@ func TestServersHandler(t *testing.T) {
|
|||
name: "invalid limit parameter - zero",
|
||||
method: http.MethodGet,
|
||||
queryParams: "?limit=0",
|
||||
setupMocks: func(registry *MockRegistryService) {},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Limit must be greater than 0",
|
||||
},
|
||||
|
|
@ -183,7 +185,7 @@ func TestServersHandler(t *testing.T) {
|
|||
name: "invalid limit parameter - negative",
|
||||
method: http.MethodGet,
|
||||
queryParams: "?limit=-5",
|
||||
setupMocks: func(registry *MockRegistryService) {},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Limit must be greater than 0",
|
||||
},
|
||||
|
|
@ -191,7 +193,7 @@ func TestServersHandler(t *testing.T) {
|
|||
name: "registry service error",
|
||||
method: http.MethodGet,
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.On("List", "", 30).Return([]model.Server{}, "", errors.New("database connection error"))
|
||||
registry.Mock.On("List", "", 30).Return([]model.Server{}, "", errors.New("database connection error"))
|
||||
},
|
||||
expectedStatus: http.StatusInternalServerError,
|
||||
expectedError: "database connection error",
|
||||
|
|
@ -199,7 +201,7 @@ func TestServersHandler(t *testing.T) {
|
|||
{
|
||||
name: "method not allowed",
|
||||
method: http.MethodPost,
|
||||
setupMocks: func(registry *MockRegistryService) {},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusMethodNotAllowed,
|
||||
expectedError: "Method not allowed",
|
||||
},
|
||||
|
|
@ -212,11 +214,11 @@ func TestServersHandler(t *testing.T) {
|
|||
tc.setupMocks(mockRegistry)
|
||||
|
||||
// Create handler
|
||||
handler := ServersHandler(mockRegistry)
|
||||
handler := v0.ServersHandler(mockRegistry)
|
||||
|
||||
// Create request
|
||||
url := "/v0/servers" + tc.queryParams
|
||||
req, err := http.NewRequest(tc.method, url, nil)
|
||||
req, err := http.NewRequestWithContext(context.Background(), tc.method, url, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
@ -235,7 +237,7 @@ func TestServersHandler(t *testing.T) {
|
|||
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var resp PaginatedResponse
|
||||
var resp v0.PaginatedResponse
|
||||
err = json.NewDecoder(rr.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
|
@ -249,15 +251,13 @@ func TestServersHandler(t *testing.T) {
|
|||
assert.NotEmpty(t, resp.Metadata.NextCursor)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if tc.expectedError != "" {
|
||||
// Check error message for non-200 responses
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, rr.Body.String(), tc.expectedError)
|
||||
}
|
||||
assert.Contains(t, rr.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
// Verify mock expectations
|
||||
mockRegistry.AssertExpectations(t)
|
||||
mockRegistry.Mock.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -285,14 +285,21 @@ func TestServersHandlerIntegration(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
mockRegistry.On("List", "", 30).Return(servers, "", nil)
|
||||
mockRegistry.Mock.On("List", "", 30).Return(servers, "", nil)
|
||||
|
||||
// Create test server
|
||||
server := httptest.NewServer(ServersHandler(mockRegistry))
|
||||
server := httptest.NewServer(v0.ServersHandler(mockRegistry))
|
||||
defer server.Close()
|
||||
|
||||
// Send request to the test server
|
||||
resp, err := http.Get(server.URL)
|
||||
ctx := context.Background()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create request: %v", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to send request: %v", err)
|
||||
}
|
||||
|
|
@ -305,7 +312,7 @@ func TestServersHandlerIntegration(t *testing.T) {
|
|||
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var paginatedResp PaginatedResponse
|
||||
var paginatedResp v0.PaginatedResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&paginatedResp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
|
@ -314,7 +321,7 @@ func TestServersHandlerIntegration(t *testing.T) {
|
|||
assert.Empty(t, paginatedResp.Metadata.NextCursor)
|
||||
|
||||
// Verify mock expectations
|
||||
mockRegistry.AssertExpectations(t)
|
||||
mockRegistry.Mock.AssertExpectations(t)
|
||||
}
|
||||
|
||||
// TestServersDetailHandlerIntegration tests the servers detail handler with actual HTTP requests
|
||||
|
|
@ -342,17 +349,24 @@ func TestServersDetailHandlerIntegration(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
mockRegistry.On("GetByID", serverID).Return(serverDetail, nil)
|
||||
mockRegistry.Mock.On("GetByID", serverID).Return(serverDetail, nil)
|
||||
|
||||
// Create test server
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.SetPathValue("id", serverID)
|
||||
ServersDetailHandler(mockRegistry).ServeHTTP(w, r)
|
||||
v0.ServersDetailHandler(mockRegistry).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// Send request to the test server
|
||||
resp, err := http.Get(server.URL)
|
||||
ctx := context.Background()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create request: %v", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to send request: %v", err)
|
||||
}
|
||||
|
|
@ -373,5 +387,5 @@ func TestServersDetailHandlerIntegration(t *testing.T) {
|
|||
assert.Equal(t, *serverDetail, serverDetailResp)
|
||||
|
||||
// Verify mock expectations
|
||||
mockRegistry.AssertExpectations(t)
|
||||
mockRegistry.Mock.AssertExpectations(t)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
|
||||
_ "github.com/swaggo/files"
|
||||
_ "github.com/swaggo/files" // Swagger files needed for embedding
|
||||
httpSwagger "github.com/swaggo/http-swagger"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,9 @@ import (
|
|||
)
|
||||
|
||||
// RegisterV0Routes registers all v0 API routes to the provided router
|
||||
func RegisterV0Routes(mux *http.ServeMux, cfg *config.Config, registry service.RegistryService, authService auth.Service) {
|
||||
func RegisterV0Routes(
|
||||
mux *http.ServeMux, cfg *config.Config, registry service.RegistryService, authService auth.Service,
|
||||
) {
|
||||
// Register v0 endpoints
|
||||
mux.HandleFunc("/v0/health", v0.HealthHandler(cfg))
|
||||
mux.HandleFunc("/v0/servers", v0.ServersHandler(registry))
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/api/router"
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
|
|
@ -31,8 +32,9 @@ func NewServer(cfg *config.Config, registryService service.RegistryService, auth
|
|||
authService: authService,
|
||||
router: mux,
|
||||
server: &http.Server{
|
||||
Addr: cfg.ServerAddress,
|
||||
Handler: mux,
|
||||
Addr: cfg.ServerAddress,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue