526 lines
24 KiB
Go
526 lines
24 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/usecase/practice"
|
|
)
|
|
|
|
const (
|
|
practiceRunnerTestTimeout = 8 * time.Minute
|
|
// practiceRunnerBackoff moves the test clock past the first backoff of a
|
|
// failed try (10 s in the queue rig).
|
|
practiceRunnerBackoff = 11 * time.Second
|
|
)
|
|
|
|
// TestAssessmentPracticeRunnerProtocol drives practice runs through the real
|
|
// router, the real queue worker, and the real TLS client of the code runner
|
|
// against a local fixture of the runner protocol. The fixture does not run
|
|
// code; see practiceRunnerFixture for what it decides.
|
|
func TestAssessmentPracticeRunnerProtocol(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), practiceRunnerTestTimeout)
|
|
defer cancel()
|
|
harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) {
|
|
return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true)
|
|
})
|
|
clock := &practiceQueueClock{}
|
|
runner := newPracticeRunnerFixture(t)
|
|
queue := newPracticeQueueRig(t, harness.pool, runner.client(t), clock)
|
|
|
|
t.Run("python and go public runs finish and show the output of their own submission", func(t *testing.T) {
|
|
alpha := newPracticeCandidate(ctx, t, harness, "runner-alpha", 10)
|
|
beta := newPracticeCandidate(ctx, t, harness, "runner-beta", 20)
|
|
// Each candidate's own test expects a wrong sum, so the diagnostic of
|
|
// the failed test shows what that program printed for that input.
|
|
alphaRun := createPracticeRun(t, harness, alpha, "python", practiceRunnerPythonSource("alpha"),
|
|
[]domain.PracticeTest{{Input: "40 2\n", ExpectedOutput: "41\n"}}, "runner-alpha-run")
|
|
betaRun := createPracticeRun(t, harness, beta, "go", practiceRunnerGoSource("beta"),
|
|
[]domain.PracticeTest{{Input: "100 23\n", ExpectedOutput: "124\n"}}, "runner-beta-run")
|
|
if alphaRun.State != "queued" || betaRun.State != "queued" {
|
|
t.Fatalf("created runs are %q and %q, want queued", alphaRun.State, betaRun.State)
|
|
}
|
|
runsBefore := runner.runCount()
|
|
queue.drain(t, ctx)
|
|
|
|
for _, expected := range []struct {
|
|
candidate practiceCandidate
|
|
run practiceRunnerRun
|
|
marker string
|
|
language string
|
|
output string
|
|
email string
|
|
}{
|
|
{alpha, alphaRun, "alpha", "python3", "got 42", "runner-alpha@example.test"},
|
|
{beta, betaRun, "beta", "go", "got 123", "runner-beta@example.test"},
|
|
} {
|
|
read := readPracticeRunnerRun(t, harness, expected.candidate, expected.run.ID)
|
|
if read.State != "finished" || read.FailureReason != nil || read.FinishedAt == nil || read.Result == nil || read.Result.Outcome != "wrong_answer" {
|
|
t.Fatalf("run of %s = %+v, want finished with a wrong answer of the candidate's own test", expected.marker, read)
|
|
}
|
|
if len(read.Result.Tests) != 3 {
|
|
t.Fatalf("run of %s lists %d tests, want the 2 examples and the candidate's test", expected.marker, len(read.Result.Tests))
|
|
}
|
|
for _, example := range read.Result.Tests[:2] {
|
|
if example.Source != "example" || example.Outcome != "accepted" || example.Diagnostic != nil {
|
|
t.Fatalf("example of %s = %+v, want accepted without a diagnostic", expected.marker, example)
|
|
}
|
|
}
|
|
own := read.Result.Tests[2]
|
|
if own.Source != "candidate" || own.Index != 1 || own.Outcome != "wrong_answer" || own.Diagnostic == nil || *own.Diagnostic != expected.output {
|
|
t.Fatalf("candidate test of %s = %+v, want a wrong answer with the output %q", expected.marker, own, expected.output)
|
|
}
|
|
|
|
// The run behind the stored result belongs to this submission: the
|
|
// job keeps its runner run ID, and the runner started that run from
|
|
// this candidate's source.
|
|
job := readRunnerJob(t, ctx, harness.pool, expected.run.ID)
|
|
if job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.attempts != 0 || job.generation != 0 {
|
|
t.Fatalf("job of %s = %+v, want finished once with a runner run ID", expected.marker, job)
|
|
}
|
|
held, found := runner.run(job.runnerRunID.String())
|
|
if !found || !strings.Contains(held.Request.Source, "marker: "+expected.marker+"\n") || string(held.Request.Language) != expected.language {
|
|
t.Fatalf("runner run %s = %+v (found %v), want the %s source of %s", job.runnerRunID, held.Request, found, expected.language, expected.marker)
|
|
}
|
|
requireRunnerRequestIsolated(t, runner, job.runnerRunID.String(), runnerIsolation{
|
|
candidate: expected.candidate, email: expected.email, submissionID: expected.run.ID,
|
|
groups: []string{practice.PublicGroupID, practice.CustomGroupID}, forbidden: []string{practiceHiddenMarker, "hidden"},
|
|
})
|
|
}
|
|
if started := len(runner.runIDsSince(runsBefore)); started != 2 {
|
|
t.Fatalf("the runner started %d runs for two submissions, want 2", started)
|
|
}
|
|
// A candidate reads only their own run.
|
|
requireSessionProblem(t, practiceRunRead(t, harness, beta, alpha.attemptID, alphaRun.ID), http.StatusNotFound, "not_found")
|
|
requireSessionProblem(t, practiceRunRead(t, harness, beta, beta.attemptID, alphaRun.ID), http.StatusNotFound, "not_found")
|
|
assertPracticeStatus(t, ctx, harness.pool, alpha.practiceID, "not_started", "")
|
|
})
|
|
|
|
t.Run("a response cut after the runner accepted the run is repeated without a second run or result", func(t *testing.T) {
|
|
gamma := newPracticeCandidate(ctx, t, harness, "runner-gamma", 30)
|
|
runsBefore := runner.runCount()
|
|
runner.failNextAccept("cut")
|
|
submitPracticeFinal(t, ctx, harness, gamma, "runner-gamma-final")
|
|
submissionID := latestPracticeSubmission(t, ctx, harness.pool, gamma.practiceID, "final")
|
|
|
|
if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
|
t.Fatalf("try with a cut response = %q claimed %v, error %v; want retry", outcome, claimed, err)
|
|
}
|
|
job := readRunnerJob(t, ctx, harness.pool, submissionID)
|
|
if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil {
|
|
t.Fatalf("job after the cut = %+v, want queued on the same run key without a result", job)
|
|
}
|
|
assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "pending", "")
|
|
if accepted := runner.runIDsSince(runsBefore); len(accepted) != 1 {
|
|
t.Fatalf("the runner accepted %d runs before the repeat, want 1", len(accepted))
|
|
}
|
|
if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed {
|
|
t.Fatalf("claim before the backoff = %v, error %v; want none", claimed, err)
|
|
}
|
|
|
|
clock.advance(practiceRunnerBackoff)
|
|
if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished {
|
|
t.Fatalf("repeat after the backoff = %q, error %v; want finished", outcome, err)
|
|
}
|
|
accepted := runner.runIDsSince(runsBefore)
|
|
job = readRunnerJob(t, ctx, harness.pool, submissionID)
|
|
if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] || job.generation != 0 {
|
|
t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted)
|
|
}
|
|
assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "finished", "")
|
|
assertFinalResultCount(t, ctx, harness.pool, gamma.practiceID, 1)
|
|
requireRunnerRequestIsolated(t, runner, accepted[0], runnerIsolation{
|
|
candidate: gamma, email: "runner-gamma@example.test", submissionID: submissionID,
|
|
groups: []string{"hidden-1", "hidden-2", "hidden-3"}, forbidden: []string{"public", "custom"},
|
|
})
|
|
})
|
|
|
|
t.Run("a run that outlasts the request timeout is joined on the repeat", func(t *testing.T) {
|
|
delta := newPracticeCandidate(ctx, t, harness, "runner-delta", 40)
|
|
runsBefore := runner.runCount()
|
|
runner.failNextAccept("stall")
|
|
run := createPracticeRun(t, harness, delta, "python", practiceRunnerPythonSource("delta"), nil, "runner-delta-run")
|
|
|
|
if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
|
t.Fatalf("try that timed out = %q claimed %v, error %v; want retry", outcome, claimed, err)
|
|
}
|
|
job := readRunnerJob(t, ctx, harness.pool, run.ID)
|
|
if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored {
|
|
t.Fatalf("job after the timeout = %+v, want queued on the same run key", job)
|
|
}
|
|
if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "queued" || read.FailureReason != nil || read.Result != nil {
|
|
t.Fatalf("run while the try is repeated = %+v, want queued", read)
|
|
}
|
|
|
|
clock.advance(practiceRunnerBackoff)
|
|
if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished {
|
|
t.Fatalf("repeat after the timeout = %q, error %v; want finished", outcome, err)
|
|
}
|
|
accepted := runner.runIDsSince(runsBefore)
|
|
job = readRunnerJob(t, ctx, harness.pool, run.ID)
|
|
if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] {
|
|
t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted)
|
|
}
|
|
if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" {
|
|
t.Fatalf("run after the repeat = %+v, want finished and accepted", read)
|
|
}
|
|
})
|
|
|
|
t.Run("a worker restarted with a new client joins the run of the dead one", func(t *testing.T) {
|
|
epsilon := newPracticeCandidate(ctx, t, harness, "runner-epsilon", 50)
|
|
submitPracticeFinal(t, ctx, harness, epsilon, "runner-epsilon-final")
|
|
submissionID := latestPracticeSubmission(t, ctx, harness.pool, epsilon.practiceID, "final")
|
|
runsBefore := runner.runCount()
|
|
runner.hold(true)
|
|
defer runner.hold(false)
|
|
|
|
crashedPool := newPoolFor(ctx, t, harness.databaseURL)
|
|
crashed := queue.workerOn(t, crashedPool)
|
|
crashCtx, crash := context.WithCancel(ctx)
|
|
crashedDone := make(chan struct{})
|
|
go func() {
|
|
defer close(crashedDone)
|
|
_, _, _ = crashed.worker.RunOnce(crashCtx)
|
|
}()
|
|
waitForRunnerRuns(t, ctx, runner, runsBefore+1)
|
|
// The process dies: its connections are gone, so the lease keeps the
|
|
// job running.
|
|
crashedPool.Close()
|
|
crash()
|
|
<-crashedDone
|
|
started := runner.runIDsSince(runsBefore)
|
|
if len(started) != 1 {
|
|
t.Fatalf("the dead worker started %d runs, want 1", len(started))
|
|
}
|
|
|
|
// The new process builds a new client from the same settings.
|
|
restartedRig := newPracticeQueueRig(t, harness.pool, runner.client(t), clock)
|
|
clock.advance(practiceQueueLease + time.Second)
|
|
runner.hold(false)
|
|
if outcome, claimed, err := restartedRig.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished {
|
|
t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err)
|
|
}
|
|
job := readRunnerJob(t, ctx, harness.pool, submissionID)
|
|
if job.state != "finished" || job.attempts != 1 || job.generation != 0 || job.runnerRunID == nil || job.runnerRunID.String() != started[0] || !job.resultStored {
|
|
t.Fatalf("recovered job = %+v, want finished on the run %s with one counted takeover", job, started[0])
|
|
}
|
|
if all := runner.runIDsSince(runsBefore); len(all) != 1 {
|
|
t.Fatalf("the runner holds %d runs for the submission, want 1", len(all))
|
|
}
|
|
assertFinalResultCount(t, ctx, harness.pool, epsilon.practiceID, 1)
|
|
assertPracticeStatus(t, ctx, harness.pool, epsilon.practiceID, "finished", "")
|
|
})
|
|
|
|
t.Run("a stopped runner leaves a retryable state and changes nothing about the candidate", func(t *testing.T) {
|
|
stopped := newPracticeRunnerFixture(t)
|
|
stoppedQueue := newPracticeQueueRig(t, harness.pool, stopped.client(t), clock)
|
|
stopped.stop()
|
|
|
|
zeta := newPracticeCandidate(ctx, t, harness, "runner-zeta", 60)
|
|
before := candidateGradeState(t, ctx, harness.pool, zeta)
|
|
run := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta"), nil, "runner-zeta-run")
|
|
|
|
// Two tries fail and wait for their backoff; the run stays queued,
|
|
// which tells the client to read it again.
|
|
for try := 1; try <= 2; try++ {
|
|
if outcome, claimed, err := stoppedQueue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry {
|
|
t.Fatalf("try %d on a stopped runner = %q claimed %v, error %v; want retry", try, outcome, claimed, err)
|
|
}
|
|
read := readPracticeRunnerRun(t, harness, zeta, run.ID)
|
|
if read.State != "queued" || read.FailureReason != nil || read.Result != nil || read.FinishedAt != nil {
|
|
t.Fatalf("run after try %d = %+v, want queued without a verdict", try, read)
|
|
}
|
|
clock.advance(practiceRunnerBackoff * 2)
|
|
}
|
|
if outcome, _, err := stoppedQueue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFailed {
|
|
t.Fatalf("last try on a stopped runner = %q, error %v; want failed without a verdict", outcome, err)
|
|
}
|
|
read := readPracticeRunnerRun(t, harness, zeta, run.ID)
|
|
if read.State != "failed" || read.FailureReason == nil || *read.FailureReason != "sandbox_error" || read.Result != nil || read.FinishedAt == nil {
|
|
t.Fatalf("run after the last try = %+v, want failed with sandbox_error and no result", read)
|
|
}
|
|
job := readRunnerJob(t, ctx, harness.pool, run.ID)
|
|
if job.state != "failed" || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil {
|
|
t.Fatalf("job after the last try = %+v, want failed with no result and no runner run", job)
|
|
}
|
|
if after := candidateGradeState(t, ctx, harness.pool, zeta); after != before {
|
|
t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", before, after)
|
|
}
|
|
assertPracticeStatus(t, ctx, harness.pool, zeta.practiceID, "not_started", "")
|
|
|
|
// The failure is retryable: the same practice takes a new run, and the
|
|
// working runner finishes it.
|
|
again := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta-again"), nil, "runner-zeta-again")
|
|
queue.drain(t, ctx)
|
|
if read := readPracticeRunnerRun(t, harness, zeta, again.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" {
|
|
t.Fatalf("run after the runner came back = %+v, want finished and accepted", read)
|
|
}
|
|
|
|
// A final solution is no verdict either: the practice fails without a
|
|
// grade and accepts the solution again.
|
|
eta := newPracticeCandidate(ctx, t, harness, "runner-eta", 70)
|
|
etaBefore := candidateGradeState(t, ctx, harness.pool, eta)
|
|
submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final")
|
|
stoppedQueue.drain(t, ctx)
|
|
assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "failed", "sandbox_error")
|
|
assertNoPracticeResult(t, ctx, harness.pool, eta.practiceID)
|
|
if after := candidateGradeState(t, ctx, harness.pool, eta); after != etaBefore {
|
|
t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", etaBefore, after)
|
|
}
|
|
submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final-again")
|
|
queue.drain(t, ctx)
|
|
assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "finished", "")
|
|
assertFinalResultCount(t, ctx, harness.pool, eta.practiceID, 1)
|
|
})
|
|
|
|
assertEverySubmissionHasOneJob(t, ctx, harness.pool)
|
|
assertEveryRunnerRunHasOneResult(t, ctx, harness.pool)
|
|
}
|
|
|
|
func practiceRunnerPythonSource(marker string) string {
|
|
return practicePythonSum + "# marker: " + marker + "\n"
|
|
}
|
|
|
|
func practiceRunnerGoSource(marker string) string {
|
|
return practiceGoSum + "// marker: " + marker + "\n"
|
|
}
|
|
|
|
// practiceRunnerRun is a created run as the API answers it.
|
|
type practiceRunnerRun struct {
|
|
ID uuid.UUID
|
|
State string
|
|
}
|
|
|
|
func createPracticeRun(
|
|
t *testing.T,
|
|
harness *practiceHarness,
|
|
candidate practiceCandidate,
|
|
language, source string,
|
|
tests []domain.PracticeTest,
|
|
key string,
|
|
) practiceRunnerRun {
|
|
t.Helper()
|
|
response := practiceRunRequest(t, harness, candidate, practiceRunBody(t, candidate.practiceID, language, source, tests), key)
|
|
if response.Code != http.StatusAccepted {
|
|
t.Fatalf("create %s run = %d %s", language, response.Code, response.Body.String())
|
|
}
|
|
run := decodePracticeRun(t, response)
|
|
return practiceRunnerRun{ID: run.ID, State: run.State}
|
|
}
|
|
|
|
// practiceRunnerRunBody decodes the fields of a run that these tests read.
|
|
type practiceRunnerRunBody struct {
|
|
ID uuid.UUID `json:"id"`
|
|
State string `json:"state"`
|
|
FinishedAt *time.Time `json:"finished_at"`
|
|
FailureReason *string `json:"failure_reason"`
|
|
Result *struct {
|
|
Outcome string `json:"outcome"`
|
|
Tests []struct {
|
|
Source string `json:"source"`
|
|
Index int `json:"index"`
|
|
Outcome string `json:"outcome"`
|
|
Diagnostic *string `json:"diagnostic"`
|
|
} `json:"tests"`
|
|
} `json:"result"`
|
|
}
|
|
|
|
// readPracticeRunnerRun reads a run of the candidate's own attempt through
|
|
// the API and checks that the response is public.
|
|
func readPracticeRunnerRun(t *testing.T, harness *practiceHarness, candidate practiceCandidate, runID uuid.UUID) practiceRunnerRunBody {
|
|
t.Helper()
|
|
response := practiceRunRead(t, harness, candidate, candidate.attemptID, runID)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("read run = %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertPracticeResponseIsPublic(t, response)
|
|
var run practiceRunnerRunBody
|
|
if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID != runID {
|
|
t.Fatalf("run response %s: %v", response.Body.String(), err)
|
|
}
|
|
return run
|
|
}
|
|
|
|
// runnerJobRow is the execution job of a submission with its stored outcome.
|
|
type runnerJobRow struct {
|
|
state string
|
|
attempts int
|
|
generation int
|
|
errorClass string
|
|
runnerRunID *uuid.UUID
|
|
resultStored bool
|
|
}
|
|
|
|
func readRunnerJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID) runnerJobRow {
|
|
t.Helper()
|
|
var job runnerJobRow
|
|
var class *string
|
|
if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.runner_run_id,
|
|
submission.result IS NOT NULL
|
|
FROM assessment_practice_jobs AS job
|
|
JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id
|
|
WHERE job.submission_id = $1`, submissionID).Scan(
|
|
&job.state, &job.attempts, &job.generation, &class, &job.runnerRunID, &job.resultStored); err != nil {
|
|
t.Fatalf("read practice job: %v", err)
|
|
}
|
|
if class != nil {
|
|
job.errorClass = *class
|
|
}
|
|
return job
|
|
}
|
|
|
|
func assertFinalResultCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, want int) {
|
|
t.Helper()
|
|
var stored int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions
|
|
WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil {
|
|
t.Fatalf("count final results: %v", err)
|
|
}
|
|
if stored != want {
|
|
t.Fatalf("%d final results stored, want %d", stored, want)
|
|
}
|
|
}
|
|
|
|
// assertEveryRunnerRunHasOneResult checks that a runner run ID belongs to one
|
|
// finished job that has a result, and that no unfinished job has one.
|
|
func assertEveryRunnerRunHasOneResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {
|
|
t.Helper()
|
|
var duplicated, withoutResult int
|
|
if err := pool.QueryRow(ctx, `SELECT
|
|
(SELECT count(*) FROM (SELECT runner_run_id FROM assessment_practice_jobs
|
|
WHERE runner_run_id IS NOT NULL GROUP BY runner_run_id HAVING count(*) > 1) AS repeated),
|
|
(SELECT count(*) FROM assessment_practice_jobs AS job
|
|
JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id
|
|
WHERE job.state = 'finished' AND job.runner_run_id IS NOT NULL AND submission.result IS NULL)`).Scan(&duplicated, &withoutResult); err != nil {
|
|
t.Fatalf("check runner runs: %v", err)
|
|
}
|
|
if duplicated != 0 || withoutResult != 0 {
|
|
t.Fatalf("%d runner runs repeat and %d have no result, want none", duplicated, withoutResult)
|
|
}
|
|
}
|
|
|
|
// candidateGradeState is what an infrastructure failure must not change: the
|
|
// confirmed categories, the results, and the state and version of the attempt.
|
|
func candidateGradeState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidate practiceCandidate) string {
|
|
t.Helper()
|
|
var state string
|
|
if err := pool.QueryRow(ctx, `SELECT jsonb_build_object(
|
|
'categories', coalesce((SELECT jsonb_agg(to_jsonb(category) ORDER BY category.specialization)
|
|
FROM candidate_assessment_categories AS category WHERE category.candidate_id = $1), '[]'::jsonb),
|
|
'results', (SELECT count(*) FROM assessment_attempt_results WHERE user_id = $1),
|
|
'attempt', (SELECT jsonb_build_object('state', attempt.state, 'version', attempt.version)
|
|
FROM assessment_attempts AS attempt WHERE attempt.id = $2))::text`,
|
|
candidate.userID, candidate.attemptID).Scan(&state); err != nil {
|
|
t.Fatalf("read candidate grade state: %v", err)
|
|
}
|
|
return state
|
|
}
|
|
|
|
func waitForRunnerRuns(t *testing.T, ctx context.Context, runner *practiceRunnerFixture, want int) {
|
|
t.Helper()
|
|
for ctx.Err() == nil {
|
|
if runner.runCount() >= want {
|
|
return
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
t.Fatalf("runner did not accept %d runs", want)
|
|
}
|
|
|
|
// runnerIsolation says what the runner may see of one submission.
|
|
type runnerIsolation struct {
|
|
candidate practiceCandidate
|
|
email string
|
|
submissionID uuid.UUID
|
|
// groups are the group IDs of the request, in order.
|
|
groups []string
|
|
// forbidden are texts that the request must not carry.
|
|
forbidden []string
|
|
}
|
|
|
|
// requireRunnerRequestIsolated checks the wire form of a run: the path holds
|
|
// an opaque run ID, the headers hold only the transport and the service
|
|
// token, and the body holds the language, the source, the limits, and the
|
|
// groups, with nothing about the candidate, the attempt, or the submission.
|
|
func requireRunnerRequestIsolated(t *testing.T, runner *practiceRunnerFixture, runID string, want runnerIsolation) {
|
|
t.Helper()
|
|
var puts []runnerCall
|
|
for _, call := range runner.callsFor(runID) {
|
|
if call.Method == http.MethodPut {
|
|
puts = append(puts, call)
|
|
}
|
|
}
|
|
if len(puts) == 0 {
|
|
t.Fatalf("the runner saw no PUT of run %s", runID)
|
|
}
|
|
identifiers := []string{
|
|
want.candidate.userID.String(), want.candidate.attemptID.String(), want.candidate.practiceID.String(),
|
|
want.candidate.additionalID.String(), want.submissionID.String(), want.email, want.candidate.cookie, want.candidate.csrf,
|
|
}
|
|
if slices.Contains(identifiers, runID) {
|
|
t.Fatalf("the run ID %s is a business identifier", runID)
|
|
}
|
|
parsed, err := uuid.Parse(runID)
|
|
if err != nil || parsed.Version() != 8 {
|
|
t.Fatalf("run ID %q is not an opaque version 8 UUID: %v", runID, err)
|
|
}
|
|
allowedHeaders := []string{"Accept", "Accept-Encoding", "Authorization", "Content-Length", "Content-Type", "User-Agent"}
|
|
for _, call := range puts {
|
|
for name, values := range call.Header {
|
|
if !slices.Contains(allowedHeaders, name) {
|
|
t.Fatalf("request to the runner carries the header %s", name)
|
|
}
|
|
for _, value := range values {
|
|
for _, identifier := range identifiers {
|
|
if strings.Contains(value, identifier) {
|
|
t.Fatalf("header %s carries an identifier of the candidate", name)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
body := string(call.Body)
|
|
for _, text := range append(append([]string(nil), identifiers...), want.forbidden...) {
|
|
if text != "" && strings.Contains(body, text) {
|
|
t.Fatalf("request to the runner carries %q: %s", text, body)
|
|
}
|
|
}
|
|
var fields map[string]json.RawMessage
|
|
if err := json.Unmarshal(call.Body, &fields); err != nil {
|
|
t.Fatalf("decode the request to the runner: %v", err)
|
|
}
|
|
names := make([]string, 0, len(fields))
|
|
for name := range fields {
|
|
names = append(names, name)
|
|
}
|
|
slices.Sort(names)
|
|
if !slices.Equal(names, []string{"groups", "language", "limits", "source"}) {
|
|
t.Fatalf("request to the runner has the fields %v, want groups, language, limits, and source only", names)
|
|
}
|
|
var groups []struct {
|
|
ID string `json:"id"`
|
|
}
|
|
if err := json.Unmarshal(fields["groups"], &groups); err != nil {
|
|
t.Fatalf("decode the groups sent to the runner: %v", err)
|
|
}
|
|
got := make([]string, 0, len(groups))
|
|
for _, group := range groups {
|
|
got = append(got, group.ID)
|
|
}
|
|
if !slices.Equal(got, want.groups) {
|
|
t.Fatalf("groups sent to the runner = %v, want %v", got, want.groups)
|
|
}
|
|
}
|
|
}
|