Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/controller/base.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package controller

import (
"net/http"

"github.com/gin-gonic/gin"
"github.com/langgenius/dify-sandbox/internal/types"
)
Expand All @@ -18,7 +20,7 @@ func BindRequest[T any](r *gin.Context, success func(T)) {

if err != nil {
resp := types.ErrorResponse(-400, err.Error())
r.JSON(200, resp)
r.JSON(http.StatusBadRequest, resp)
return
}
success(request)
Expand Down
45 changes: 45 additions & 0 deletions internal/controller/base_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package controller

import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gin-gonic/gin"
"github.com/langgenius/dify-sandbox/internal/types"
)

func TestBindRequestReturnsBadRequestWhenJSONIsInvalid(t *testing.T) {
gin.SetMode(gin.TestMode)

recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/sandbox/run", strings.NewReader(`{"language"`))
ctx.Request.Header.Set("Content-Type", "application/json")

successCalled := false
BindRequest(ctx, func(req struct {
Language string `json:"language" binding:"required"`
}) {
successCalled = true
})

if successCalled {
t.Fatalf("success callback should not be called when request binding fails")
}

if recorder.Code != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, recorder.Code)
}

var resp types.DifySandboxResponse
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response body: %v", err)
}

if resp.Code != -400 {
t.Fatalf("expected response code -400, got %d", resp.Code)
}
}