feat: add candidate profile, questionnaire and company forms
This commit is contained in:
1 parent
3a61a8e8bb
commit
f81cd0ae09
68 files changed
+9517
-54
No files matched your search
@@ -0,0 +1,278 @@
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
fixtureEnabledName = "E2E_COMPANY_FIXTURE"
|
||||
fixtureAuthEnvName = "E2E_COMPANY_FIXTURE_TOKEN"
|
||||
fixtureListenAddr = ":8081"
|
||||
fixtureEndpoint = "/company/memberships/revoke"
|
||||
fixtureHealthPath = "/healthcheck"
|
||||
maxRequestBody = 1024
|
||||
maxFixtureRequests = 32
|
||||
requestTimeout = 5 * time.Second
|
||||
readHeaderTimeout = 3 * time.Second
|
||||
readTimeout = 5 * time.Second
|
||||
writeTimeout = 5 * time.Second
|
||||
idleTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error
|
||||
|
||||
type fixtureHandler struct {
|
||||
token string
|
||||
revoke membershipRevoker
|
||||
requests atomic.Uint32
|
||||
}
|
||||
|
||||
type revokeMembershipRequest struct {
|
||||
OrganizationID string `json:"organization_id"`
|
||||
UserID string `json:"user_id"`
|
||||
SuccessorUserID string `json:"successor_user_id"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
if err := checkHealth(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := serve(); err != nil {
|
||||
_, _ = io.WriteString(os.Stderr, "Company fixture could not start.\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func serve() error {
|
||||
if os.Getenv(fixtureEnabledName) != "1" {
|
||||
return errors.New("company fixture requires the isolated e2e environment")
|
||||
}
|
||||
token := os.Getenv(fixtureAuthEnvName)
|
||||
if !hasFixtureTokenStrength(token) {
|
||||
return errors.New("company fixture token must contain at least 32 random bytes")
|
||||
}
|
||||
databaseURL := os.Getenv("DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
return errors.New("company fixture database is not configured")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
|
||||
defer cancel()
|
||||
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
|
||||
if err != nil {
|
||||
return errors.New("company fixture could not open its database")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("company fixture database is unavailable")
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: fixtureListenAddr,
|
||||
Handler: &fixtureHandler{
|
||||
token: token,
|
||||
revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error {
|
||||
return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID)
|
||||
},
|
||||
},
|
||||
ReadHeaderTimeout: readHeaderTimeout,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
IdleTimeout: idleTimeout,
|
||||
MaxHeaderBytes: 4096,
|
||||
ErrorLog: log.New(io.Discard, "", 0),
|
||||
}
|
||||
return server.ListenAndServe()
|
||||
}
|
||||
|
||||
func checkHealth() error {
|
||||
client := http.Client{Timeout: time.Second}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8081"+fixtureHealthPath, nil)
|
||||
if err != nil {
|
||||
return errors.New("company fixture is not healthy")
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return errors.New("company fixture is not healthy")
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode != http.StatusNoContent {
|
||||
return errors.New("company fixture is not healthy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasFixtureTokenStrength(token string) bool {
|
||||
if decoded, err := hex.DecodeString(token); err == nil && len(decoded) >= 32 {
|
||||
return true
|
||||
}
|
||||
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
||||
return err == nil && len(decoded) >= 32
|
||||
}
|
||||
|
||||
func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case fixtureHealthPath:
|
||||
handler.serveHealthcheck(w, r)
|
||||
case fixtureEndpoint:
|
||||
handler.serveMembershipRevocation(w, r)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler *fixtureHandler) serveHealthcheck(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (handler *fixtureHandler) serveMembershipRevocation(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if handler.requests.Add(1) > maxFixtureRequests {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if !isJSONRequest(r) {
|
||||
w.WriteHeader(http.StatusUnsupportedMediaType)
|
||||
return
|
||||
}
|
||||
|
||||
request, status := decodeRevokeMembershipRequest(w, r)
|
||||
if status != 0 {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
if handler.revoke == nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
|
||||
defer cancel()
|
||||
if err := handler.revoke(ctx, request.organizationID, request.userID, request.successorUserID); err != nil {
|
||||
w.WriteHeader(statusForFixtureError(err))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type parsedRevokeMembershipRequest struct {
|
||||
organizationID uuid.UUID
|
||||
userID uuid.UUID
|
||||
successorUserID uuid.UUID
|
||||
}
|
||||
|
||||
func decodeRevokeMembershipRequest(w http.ResponseWriter, r *http.Request) (parsedRevokeMembershipRequest, int) {
|
||||
request, status := decodeRevokeRequest(w, r)
|
||||
if status != 0 {
|
||||
return parsedRevokeMembershipRequest{}, status
|
||||
}
|
||||
organizationID, err := uuid.Parse(request.OrganizationID)
|
||||
if err != nil || organizationID == uuid.Nil {
|
||||
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
||||
}
|
||||
userID, err := uuid.Parse(request.UserID)
|
||||
if err != nil || userID == uuid.Nil {
|
||||
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
||||
}
|
||||
successorUserID, err := uuid.Parse(request.SuccessorUserID)
|
||||
if err != nil || successorUserID == uuid.Nil || successorUserID == userID {
|
||||
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
||||
}
|
||||
return parsedRevokeMembershipRequest{
|
||||
organizationID: organizationID,
|
||||
userID: userID,
|
||||
successorUserID: successorUserID,
|
||||
}, 0
|
||||
}
|
||||
|
||||
func isJSONRequest(r *http.Request) bool {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
return err == nil && strings.EqualFold(mediaType, "application/json")
|
||||
}
|
||||
|
||||
func decodeRevokeRequest(w http.ResponseWriter, r *http.Request) (revokeMembershipRequest, int) {
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody))
|
||||
decoder.DisallowUnknownFields()
|
||||
var request revokeMembershipRequest
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
return revokeMembershipRequest{}, statusForDecodeError(err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return revokeMembershipRequest{}, statusForDecodeError(err)
|
||||
}
|
||||
if request.OrganizationID == "" || request.UserID == "" {
|
||||
return revokeMembershipRequest{}, http.StatusBadRequest
|
||||
}
|
||||
return request, 0
|
||||
}
|
||||
|
||||
func statusForDecodeError(err error) int {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return http.StatusRequestEntityTooLarge
|
||||
}
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
|
||||
func statusForFixtureError(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, postgres.ErrCompanyFixtureScope),
|
||||
errors.Is(err, outbound.ErrUserNotFound),
|
||||
errors.Is(err, outbound.ErrMembershipNotFound),
|
||||
errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, outbound.ErrTransactionConflict):
|
||||
return http.StatusConflict
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
func hasFixtureBearerToken(header, token string) bool {
|
||||
prefix, supplied, ok := strings.Cut(header, " ")
|
||||
if !ok || prefix != "Bearer" || supplied == "" {
|
||||
return false
|
||||
}
|
||||
expectedDigest := sha256.Sum256([]byte(token))
|
||||
suppliedDigest := sha256.Sum256([]byte(supplied))
|
||||
return subtle.ConstantTimeCompare(expectedDigest[:], suppliedDigest[:]) == 1
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestFixtureHandlerRevokesOnlyWithConfiguredBearer(t *testing.T) {
|
||||
organizationID := uuid.New()
|
||||
userID := uuid.New()
|
||||
successorUserID := uuid.New()
|
||||
called := false
|
||||
handler := &fixtureHandler{
|
||||
token: strings.Repeat("ab", 32),
|
||||
revoke: func(_ context.Context, gotOrganizationID, gotUserID, gotSuccessorUserID uuid.UUID) error {
|
||||
called = true
|
||||
if gotOrganizationID != organizationID || gotUserID != userID || gotSuccessorUserID != successorUserID {
|
||||
t.Fatalf("revoke IDs = %s/%s/%s, want %s/%s/%s", gotOrganizationID, gotUserID, gotSuccessorUserID, organizationID, userID, successorUserID)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
body := `{"organization_id":"` + organizationID.String() + `","user_id":"` + userID.String() + `","successor_user_id":"` + successorUserID.String() + `"}`
|
||||
|
||||
unauthorized := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json")
|
||||
if unauthorized.Code != http.StatusUnauthorized || called {
|
||||
t.Fatalf("unauthorized response = %d, revoke called = %t", unauthorized.Code, called)
|
||||
}
|
||||
if len(unauthorized.Body.Bytes()) != 0 {
|
||||
t.Fatalf("unauthorized response exposed a body: %q", unauthorized.Body.String())
|
||||
}
|
||||
|
||||
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json; charset=utf-8")
|
||||
if response.Code != http.StatusNoContent || !called {
|
||||
t.Fatalf("authorized response = %d, revoke called = %t", response.Code, called)
|
||||
}
|
||||
if len(response.Body.Bytes()) != 0 {
|
||||
t.Fatalf("success response exposed a body: %q", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureHandlerRejectsInvalidRequestsWithoutCallingRevoker(t *testing.T) {
|
||||
called := false
|
||||
handler := &fixtureHandler{
|
||||
token: strings.Repeat("ab", 32),
|
||||
revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error {
|
||||
called = true
|
||||
return nil
|
||||
},
|
||||
}
|
||||
validBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`
|
||||
userID := uuid.NewString()
|
||||
sameUserBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + userID + `","successor_user_id":"` + userID + `"}`
|
||||
largeBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `","padding":"` + strings.Repeat("x", maxRequestBody) + `"}`
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
authority string
|
||||
contentType string
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "unknown path", method: http.MethodPost, path: "/other", wantStatus: http.StatusNotFound},
|
||||
{name: "wrong method", method: http.MethodGet, path: fixtureEndpoint, wantStatus: http.StatusMethodNotAllowed},
|
||||
{name: "wrong content type", method: http.MethodPost, path: fixtureEndpoint, body: validBody, authority: "Bearer " + handler.token, contentType: "text/plain", wantStatus: http.StatusUnsupportedMediaType},
|
||||
{name: "unknown field", method: http.MethodPost, path: fixtureEndpoint, body: strings.TrimSuffix(validBody, "}") + `,"extra":"value"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
|
||||
{name: "malformed UUID", method: http.MethodPost, path: fixtureEndpoint, body: `{"organization_id":"bad","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
|
||||
{name: "same owner and successor", method: http.MethodPost, path: fixtureEndpoint, body: sameUserBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
|
||||
{name: "trailing JSON", method: http.MethodPost, path: fixtureEndpoint, body: validBody + `{}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
|
||||
{name: "oversized body", method: http.MethodPost, path: fixtureEndpoint, body: largeBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusRequestEntityTooLarge},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
response := fixtureRequest(handler, test.method, test.path, test.body, test.authority, test.contentType)
|
||||
if response.Code != test.wantStatus {
|
||||
t.Fatalf("response status = %d, want %d", response.Code, test.wantStatus)
|
||||
}
|
||||
if len(response.Body.Bytes()) != 0 {
|
||||
t.Fatalf("response exposed a body: %q", response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
if called {
|
||||
t.Fatal("revoker was called for an invalid request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureHandlerBoundsControlRequests(t *testing.T) {
|
||||
handler := &fixtureHandler{token: strings.Repeat("ab", 32)}
|
||||
for range maxFixtureRequests {
|
||||
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json")
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("request before limit status = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json")
|
||||
if response.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("request after limit status = %d, want %d", response.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureHandlerMapsStorageErrorsToEmptyResponses(t *testing.T) {
|
||||
handler := &fixtureHandler{
|
||||
token: strings.Repeat("ab", 32),
|
||||
revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error {
|
||||
return errors.Join(errors.New("private database detail"), outbound.ErrTransactionConflict)
|
||||
},
|
||||
}
|
||||
body := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`
|
||||
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json")
|
||||
if response.Code != http.StatusConflict {
|
||||
t.Fatalf("response status = %d, want %d", response.Code, http.StatusConflict)
|
||||
}
|
||||
if len(response.Body.Bytes()) != 0 {
|
||||
t.Fatalf("response exposed internal error: %q", response.Body.String())
|
||||
}
|
||||
if got := statusForFixtureError(postgres.ErrCompanyFixtureScope); got != http.StatusNotFound {
|
||||
t.Fatalf("fixture scope status = %d, want %d", got, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureHealthIsMinimal(t *testing.T) {
|
||||
handler := &fixtureHandler{}
|
||||
response := fixtureRequest(handler, http.MethodGet, fixtureHealthPath, "", "", "")
|
||||
if response.Code != http.StatusNoContent || len(response.Body.Bytes()) != 0 {
|
||||
t.Fatalf("health response = %d %q, want empty %d", response.Code, response.Body.String(), http.StatusNoContent)
|
||||
}
|
||||
wrongMethod := fixtureRequest(handler, http.MethodPost, fixtureHealthPath, "", "", "")
|
||||
if wrongMethod.Code != http.StatusMethodNotAllowed || wrongMethod.Header().Get("Allow") != http.MethodGet {
|
||||
t.Fatalf("health wrong-method response = %d, Allow = %q", wrongMethod.Code, wrongMethod.Header().Get("Allow"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixtureTokenStrengthAcceptsOnlyAtLeast32Bytes(t *testing.T) {
|
||||
bytes32 := bytes.Repeat([]byte{0x4a}, 32)
|
||||
for name, token := range map[string]string{
|
||||
"hex": hex.EncodeToString(bytes32),
|
||||
"base64": base64.RawURLEncoding.EncodeToString(bytes32),
|
||||
"too short": hex.EncodeToString(bytes32[:31]),
|
||||
"invalid": "not-a-token",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
want := name == "hex" || name == "base64"
|
||||
if got := hasFixtureTokenStrength(token); got != want {
|
||||
t.Fatalf("hasFixtureTokenStrength() = %t, want %t", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func fixtureRequest(handler http.Handler, method, path, body, authorization, contentType string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if authorization != "" {
|
||||
request.Header.Set("Authorization", authorization)
|
||||
}
|
||||
if contentType != "" {
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
@@ -34,7 +34,9 @@ func main() {
|
||||
_, _ = fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Fprintln(os.Stdout, "Consent browser fixture seeded.")
|
||||
if _, err := fmt.Fprintln(os.Stdout, "Consent browser fixture seeded."); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
|
||||
@@ -76,7 +76,7 @@ func healthcheck() error {
|
||||
if err != nil {
|
||||
return errors.New("main.healthcheck - mail fixture is not ready")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode != http.StatusNoContent {
|
||||
return errors.New("main.healthcheck - mail fixture is not ready")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
const (
|
||||
fixtureEnabledName = "E2E_QUESTIONNAIRE_FIXTURE"
|
||||
fixtureTimeout = 90 * time.Second
|
||||
maxFixtureFamilies = 200
|
||||
|
||||
fixtureBundleName = "e2e-questionnaire-bank"
|
||||
fixtureAuthor = "operator:questionnaire-fixture-author"
|
||||
fixtureReviewer = "operator:questionnaire-fixture-reviewer"
|
||||
fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher")
|
||||
fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener")
|
||||
fixtureFamilyStem = "e2e-questionnaire-family-"
|
||||
fixtureCategory = domain.AssessmentCategory("backend")
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(context.Background(), os.Args[1:], os.LookupEnv); err != nil {
|
||||
if _, writeErr := fmt.Fprintln(os.Stderr, err); writeErr != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
if _, err := fmt.Fprintln(os.Stdout, "Questionnaire bank fixture is ready."); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(
|
||||
parent context.Context,
|
||||
args []string,
|
||||
lookupEnv func(string) (string, bool),
|
||||
) error {
|
||||
if len(args) != 0 {
|
||||
return errors.New("questionnaire fixture accepts no arguments")
|
||||
}
|
||||
enabled, _ := lookupEnv(fixtureEnabledName)
|
||||
if enabled != "1" {
|
||||
return errors.New("questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1")
|
||||
}
|
||||
databaseURL, _ := lookupEnv("DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
return errors.New("questionnaire fixture database is not configured")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(parent, fixtureTimeout)
|
||||
defer cancel()
|
||||
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
|
||||
if err != nil {
|
||||
return errors.New("questionnaire fixture could not open its database")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("questionnaire fixture database is unavailable")
|
||||
}
|
||||
if err := seedQuestionnaireBank(ctx, pool); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
const location = "questionnaire fixture"
|
||||
occupied, err := backendQuestionnaireBankOccupied(ctx, pool)
|
||||
if err != nil {
|
||||
return errors.New(location + " could not inspect backend bank state")
|
||||
}
|
||||
if occupied {
|
||||
return errors.New(location + " refuses existing backend openings or published families")
|
||||
}
|
||||
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
currentPolicy, err := currentProductPolicy(ctx, transactor)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return errors.New(location + " requires a current product assessment policy")
|
||||
}
|
||||
return errors.New(location + " could not read the current product policy")
|
||||
}
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(currentPolicy.Policy())
|
||||
if err != nil || required < 1 || required > maxFixtureFamilies {
|
||||
return errors.New(location + " current policy has an unsupported family threshold")
|
||||
}
|
||||
bundle, err := reviewedQuestionnaireBundle(int(required))
|
||||
if err != nil {
|
||||
return errors.New(location + " reviewed family fixture is invalid")
|
||||
}
|
||||
|
||||
bank := assessment.NewBank(transactor)
|
||||
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
|
||||
return errors.New(location + " could not import reviewed families")
|
||||
}
|
||||
for _, family := range bundle.Families {
|
||||
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
||||
return errors.New(location + " could not publish reviewed families")
|
||||
}
|
||||
}
|
||||
metadata, err := questionnaireCatalogMetadata()
|
||||
if err != nil {
|
||||
return errors.New(location + " public catalog mapping is invalid")
|
||||
}
|
||||
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: fixtureCategory, GradingPolicyID: currentPolicy.ID(), OpenedBy: fixtureOpener,
|
||||
CatalogMetadata: &metadata,
|
||||
}); err != nil {
|
||||
return errors.New(location + " could not open the reviewed catalog mapping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, error) {
|
||||
return domain.NewAssessmentCategoryCatalogMetadata(
|
||||
domain.SpecializationBackend,
|
||||
domain.GradeJunior,
|
||||
[]domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
)
|
||||
}
|
||||
|
||||
func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
||||
var occupied bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
EXISTS (SELECT 1 FROM assessment_category_openings WHERE category = $1)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM assessment_families
|
||||
WHERE category = $1 AND lifecycle = 'published'
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM assessment_families
|
||||
WHERE category = $1 AND family_key LIKE $2
|
||||
)`, string(fixtureCategory), fixtureFamilyStem+"%").Scan(&occupied)
|
||||
return occupied, err
|
||||
}
|
||||
|
||||
func currentProductPolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
|
||||
var version domain.PolicyVersion
|
||||
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
version, err = unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime)
|
||||
return err
|
||||
})
|
||||
return version, err
|
||||
}
|
||||
|
||||
func reviewedQuestionnaireBundle(count int) (assessment.Bundle, error) {
|
||||
if count < 1 || count > maxFixtureFamilies {
|
||||
return assessment.Bundle{}, errors.New("questionnaire fixture family count is outside the supported range")
|
||||
}
|
||||
bundle := assessment.Bundle{
|
||||
Name: fixtureBundleName, Category: string(fixtureCategory), Author: fixtureAuthor,
|
||||
Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer},
|
||||
Families: make([]assessment.BundleFamily, 0, count),
|
||||
}
|
||||
requestsMinimum := int32(12)
|
||||
for index := range count {
|
||||
familyNumber := index + 1
|
||||
family := assessment.BundleFamily{
|
||||
Key: fmt.Sprintf("%s%03d", fixtureFamilyStem, familyNumber), Version: 1,
|
||||
Specialization: "rate-limiting", Title: fmt.Sprintf("Sliding-window fixture case %03d", familyNumber),
|
||||
SeedGenerator: domain.AssessmentSeedGenerator{
|
||||
Algorithm: "rate_limit_window.v1",
|
||||
Parameters: map[string]domain.AssessmentParameterRange{
|
||||
"requests": {Min: requestsMinimum, Max: requestsMinimum + 8},
|
||||
"window": {Min: 3, Max: 15},
|
||||
"limit": {Min: 2, Max: 6},
|
||||
"max_gap": {Min: 1, Max: 5},
|
||||
},
|
||||
StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?",
|
||||
},
|
||||
AnswerKey: domain.AssessmentAnswerKey{
|
||||
AnswerFormat: domain.AnswerFormatInteger,
|
||||
ReferenceSolution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it. Each request enters and leaves the queue at most once.",
|
||||
},
|
||||
Rubric: domain.AssessmentRubric{
|
||||
Principle: "The answer is the exact number of rejected requests for the generated arrival sequence. The rubric has criteria but no points or pass mark.",
|
||||
Criteria: []domain.AssessmentRubricCriterion{
|
||||
{ID: "correct_answer", Description: "The submitted integer equals the generated reference answer."},
|
||||
{ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."},
|
||||
{ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."},
|
||||
{ID: "queue_approach", Description: "The approach processes each arrival at most once when entering and once when leaving the queue."},
|
||||
},
|
||||
},
|
||||
}
|
||||
bundle.Families = append(bundle.Families, family)
|
||||
requestsMinimum++
|
||||
}
|
||||
if _, err := bundle.Drafts(); err != nil {
|
||||
return assessment.Bundle{}, err
|
||||
}
|
||||
return bundle, nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestRunRequiresExactE2EGuardBeforeDatabase(t *testing.T) {
|
||||
lookup := func(name string) (string, bool) {
|
||||
if name == "DATABASE_URL" {
|
||||
return "postgres://fixture.invalid/test", true
|
||||
}
|
||||
return "true", true
|
||||
}
|
||||
err := run(context.Background(), nil, lookup)
|
||||
if err == nil || err.Error() != "questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1" {
|
||||
t.Fatalf("run(disabled) error = %v, want exact E2E guard refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsArgumentsAndMissingDatabase(t *testing.T) {
|
||||
enabled := func(name string) (string, bool) {
|
||||
if name == fixtureEnabledName {
|
||||
return "1", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if err := run(context.Background(), []string{"seed"}, enabled); err == nil || err.Error() != "questionnaire fixture accepts no arguments" {
|
||||
t.Fatalf("run(with argument) error = %v, want argument refusal", err)
|
||||
}
|
||||
if err := run(context.Background(), nil, enabled); err == nil || err.Error() != "questionnaire fixture database is not configured" {
|
||||
t.Fatalf("run(without database) error = %v, want missing database refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewedQuestionnaireBundleValidatesIndependentFamilies(t *testing.T) {
|
||||
const count = 13
|
||||
bundle, err := reviewedQuestionnaireBundle(count)
|
||||
if err != nil {
|
||||
t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v", count, err)
|
||||
}
|
||||
if bundle.Category != string(fixtureCategory) || bundle.Review.Status != string(domain.AssessmentReviewApproved) ||
|
||||
bundle.Author == bundle.Review.Reviewer || len(bundle.Families) != count {
|
||||
t.Fatalf("reviewed fixture bundle metadata = category %q, review %q by %q, author %q, families %d",
|
||||
bundle.Category, bundle.Review.Status, bundle.Review.Reviewer, bundle.Author, len(bundle.Families))
|
||||
}
|
||||
drafts, err := bundle.Drafts()
|
||||
if err != nil || len(drafts) != count {
|
||||
t.Fatalf("Bundle.Drafts() = %d, %v; want %d valid reviewed families", len(drafts), err, count)
|
||||
}
|
||||
seen := make(map[domain.AssessmentFamilyKey]struct{}, count)
|
||||
for _, draft := range drafts {
|
||||
core := draft.Core()
|
||||
if core.Category != fixtureCategory || core.Reviewer == "" || string(core.Reviewer) == string(core.Author) {
|
||||
t.Fatalf("draft review identity/category is not independent: category %q reviewer %q author %q", core.Category, core.Reviewer, core.Author)
|
||||
}
|
||||
if _, exists := seen[core.Key]; exists {
|
||||
t.Fatalf("duplicate synthetic family key %q", core.Key)
|
||||
}
|
||||
seen[core.Key] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewedQuestionnaireBundleRejectsUnsupportedThreshold(t *testing.T) {
|
||||
for _, count := range []int{0, maxFixtureFamilies + 1} {
|
||||
if _, err := reviewedQuestionnaireBundle(count); err == nil {
|
||||
t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v; want a fixture threshold error", count, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuestionnaireCatalogMetadataUsesTheReviewedE2EProjection(t *testing.T) {
|
||||
metadata, err := questionnaireCatalogMetadata()
|
||||
if err != nil {
|
||||
t.Fatalf("questionnaireCatalogMetadata() error = %v", err)
|
||||
}
|
||||
if metadata.Specialization() != domain.SpecializationBackend || metadata.Grade() != domain.GradeJunior ||
|
||||
len(metadata.TaskLanguages()) != 1 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo {
|
||||
t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go",
|
||||
metadata.Specialization(), metadata.Grade(), metadata.TaskLanguages())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user