account_capability_handler_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package handler
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  6. "github.com/Wei-Shaw/sub2api/internal/service"
  7. "github.com/gin-gonic/gin"
  8. "github.com/stretchr/testify/require"
  9. "net/http"
  10. "net/http/httptest"
  11. "testing"
  12. )
  13. type capabilityRepo struct {
  14. service.IntelligentTestRepository
  15. visible bool
  16. user int64
  17. }
  18. func (r *capabilityRepo) PublicGet(_ context.Context, user, id int64) (*service.PublicAccountTest, error) {
  19. r.user = user
  20. if !r.visible {
  21. return nil, service.ErrIntelligentTestNotFound
  22. }
  23. return &service.PublicAccountTest{ID: id, Result: "visible result"}, nil
  24. }
  25. func TestIntelligentPublicHandlerUsesCurrentVisibilityAndIdentity(t *testing.T) {
  26. gin.SetMode(gin.TestMode)
  27. repo := &capabilityRepo{}
  28. h := NewAccountCapabilityHandler(service.NewIntelligentTestService(repo, nil))
  29. engine := gin.New()
  30. engine.Use(func(c *gin.Context) { c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 27}) })
  31. engine.GET("/results/:id", h.Get)
  32. engine.GET("/results/:id/image", h.Image)
  33. for _, path := range []string{"/results/1", "/results/1/image"} {
  34. w := httptest.NewRecorder()
  35. engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
  36. require.Equal(t, 404, w.Code)
  37. require.EqualValues(t, 27, repo.user)
  38. }
  39. repo.visible = true
  40. w := httptest.NewRecorder()
  41. engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/results/1", nil))
  42. require.Equal(t, 200, w.Code)
  43. var body map[string]any
  44. require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
  45. data := body["data"].(map[string]any)
  46. for _, key := range []string{"credentials", "notes", "input", "raw_response", "error_message", "config_snapshot", "evaluation"} {
  47. _, exists := data[key]
  48. require.False(t, exists, key)
  49. }
  50. repo.visible = false
  51. w = httptest.NewRecorder()
  52. engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/results/1", nil))
  53. require.Equal(t, 404, w.Code)
  54. }