115 lines
2.7 KiB
Go
115 lines
2.7 KiB
Go
package rest_test
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/domain"
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/router/rest/internal/mock"
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/router/rest/internal/model"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func TestUser_getAuthenticated(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
now := time.Now()
|
|
apiKey := uuid.NewString()
|
|
tests := []struct {
|
|
name string
|
|
setup func(apiKeySvc *mock.FakeAPIKeyVerifier)
|
|
apiKey string
|
|
expectedStatus int
|
|
target any
|
|
expectedResponse any
|
|
}{
|
|
{
|
|
name: "OK",
|
|
setup: func(apiKeySvc *mock.FakeAPIKeyVerifier) {
|
|
apiKeySvc.VerifyCalls(func(ctx context.Context, key string) (domain.User, error) {
|
|
if key != apiKey {
|
|
return domain.User{}, domain.APIKeyNotFoundError{
|
|
Key: key,
|
|
}
|
|
}
|
|
|
|
return domain.User{
|
|
ID: 111,
|
|
Name: "name",
|
|
CreatedAt: now,
|
|
}, nil
|
|
})
|
|
},
|
|
apiKey: apiKey,
|
|
expectedStatus: http.StatusOK,
|
|
target: &model.GetUserResp{},
|
|
expectedResponse: &model.GetUserResp{
|
|
Data: model.User{
|
|
ID: 111,
|
|
Name: "name",
|
|
CreatedAt: now,
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "ERR: apiKey == \"\"",
|
|
setup: func(apiKeySvc *mock.FakeAPIKeyVerifier) {},
|
|
apiKey: "",
|
|
expectedStatus: http.StatusUnauthorized,
|
|
target: &model.ErrorResp{},
|
|
expectedResponse: &model.ErrorResp{
|
|
Error: model.APIError{
|
|
Code: "unauthorized",
|
|
Message: "invalid API key",
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "ERR: unexpected API key",
|
|
setup: func(apiKeySvc *mock.FakeAPIKeyVerifier) {
|
|
apiKeySvc.VerifyCalls(func(ctx context.Context, key string) (domain.User, error) {
|
|
if key != apiKey {
|
|
return domain.User{}, domain.APIKeyNotFoundError{
|
|
Key: key,
|
|
}
|
|
}
|
|
|
|
return domain.User{
|
|
ID: 111,
|
|
Name: "name",
|
|
CreatedAt: now,
|
|
}, nil
|
|
})
|
|
},
|
|
apiKey: uuid.NewString(),
|
|
expectedStatus: http.StatusUnauthorized,
|
|
target: &model.ErrorResp{},
|
|
expectedResponse: &model.ErrorResp{
|
|
Error: model.APIError{
|
|
Code: "unauthorized",
|
|
Message: "invalid API key",
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
tt := tt
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
apiKeySvc := &mock.FakeAPIKeyVerifier{}
|
|
tt.setup(apiKeySvc)
|
|
|
|
router := newRouter(withAPIKeyVerifier(apiKeySvc))
|
|
|
|
resp := doRequest(router, http.MethodGet, "/v1/user", tt.apiKey, nil)
|
|
defer resp.Body.Close()
|
|
assertJSONResponse(t, resp, tt.expectedStatus, tt.expectedResponse, tt.target)
|
|
})
|
|
}
|
|
}
|