424 lines
18 KiB
Go
424 lines
18 KiB
Go
package assessment
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
testOperator = domain.AssessmentOperator("operator:unit-publisher")
|
|
testCategory = domain.AssessmentCategory("backend")
|
|
)
|
|
|
|
// fakeBank is an in-memory outbound.AssessmentBankRepository. Methods that a
|
|
// test does not need panic through the nil embedded interface.
|
|
type fakeBank struct {
|
|
outbound.AssessmentBankRepository
|
|
|
|
calls []string
|
|
families map[string]domain.AssessmentFamily
|
|
// onCreate runs inside CreateFamily, to store a version as a concurrent
|
|
// import that wins the insert would.
|
|
onCreate func()
|
|
createErr error
|
|
markPubErr error
|
|
markRetErr error
|
|
openErr error
|
|
published int32
|
|
publishedFam *domain.AssessmentFamily
|
|
opening *domain.AssessmentCategoryOpening
|
|
}
|
|
|
|
func versionKey(key domain.AssessmentFamilyKey, version int32) string {
|
|
return fmt.Sprintf("%s/%d", key, version)
|
|
}
|
|
|
|
func (bank *fakeBank) GetFamilyVersion(_ context.Context, key domain.AssessmentFamilyKey, version int32) (domain.AssessmentFamily, error) {
|
|
bank.calls = append(bank.calls, "get")
|
|
if family, ok := bank.families[versionKey(key, version)]; ok {
|
|
return family, nil
|
|
}
|
|
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
|
}
|
|
|
|
func (bank *fakeBank) GetLatestFamily(_ context.Context, key domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
|
var latest domain.AssessmentFamily
|
|
for _, family := range bank.families {
|
|
if family.Key() == key && (latest.IsZero() || family.Version() > latest.Version()) {
|
|
latest = family
|
|
}
|
|
}
|
|
if latest.IsZero() {
|
|
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
|
}
|
|
return latest, nil
|
|
}
|
|
|
|
func (bank *fakeBank) DatabaseTime(context.Context) (time.Time, error) { return time.Now(), nil }
|
|
|
|
func (bank *fakeBank) CreateFamily(context.Context, domain.AssessmentFamilyDraft) (domain.AssessmentFamily, error) {
|
|
bank.calls = append(bank.calls, "create")
|
|
if bank.onCreate != nil {
|
|
bank.onCreate()
|
|
}
|
|
return domain.AssessmentFamily{}, bank.createErr
|
|
}
|
|
|
|
func (bank *fakeBank) LockCategory(context.Context, domain.AssessmentCategory) error {
|
|
bank.calls = append(bank.calls, "lock")
|
|
return nil
|
|
}
|
|
|
|
func (bank *fakeBank) GetPublishedFamily(context.Context, domain.AssessmentFamilyKey) (domain.AssessmentFamily, error) {
|
|
if bank.publishedFam == nil {
|
|
return domain.AssessmentFamily{}, outbound.ErrAssessmentFamilyNotFound
|
|
}
|
|
return *bank.publishedFam, nil
|
|
}
|
|
|
|
func (bank *fakeBank) MarkPublished(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
|
bank.calls = append(bank.calls, "publish:"+id.String())
|
|
return domain.AssessmentFamily{}, bank.markPubErr
|
|
}
|
|
|
|
func (bank *fakeBank) MarkRetired(_ context.Context, id domain.AssessmentFamilyID, _ domain.AssessmentOperator) (domain.AssessmentFamily, error) {
|
|
bank.calls = append(bank.calls, "retire:"+id.String())
|
|
return domain.AssessmentFamily{}, bank.markRetErr
|
|
}
|
|
|
|
func (bank *fakeBank) CountPublishedFamilies(context.Context, domain.AssessmentCategory) (int32, error) {
|
|
bank.calls = append(bank.calls, "count")
|
|
return bank.published, nil
|
|
}
|
|
|
|
func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error) {
|
|
bank.calls = append(bank.calls, "open")
|
|
return domain.AssessmentCategoryOpening{}, bank.openErr
|
|
}
|
|
|
|
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
|
if bank.opening == nil {
|
|
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
|
|
}
|
|
return *bank.opening, nil
|
|
}
|
|
|
|
type fakePolicies struct {
|
|
outbound.PolicyRepository
|
|
|
|
stored map[domain.PolicyVersionID]domain.PolicyVersion
|
|
effective domain.PolicyVersion
|
|
}
|
|
|
|
func (policies fakePolicies) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
|
if version, ok := policies.stored[id]; ok {
|
|
return version, nil
|
|
}
|
|
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
|
}
|
|
|
|
func (policies fakePolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
|
|
if policies.effective.IsZero() {
|
|
return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound
|
|
}
|
|
return policies.effective, nil
|
|
}
|
|
|
|
type fakeUnit struct {
|
|
outbound.UnitOfWork
|
|
|
|
bank *fakeBank
|
|
policies fakePolicies
|
|
}
|
|
|
|
func (unit *fakeUnit) AssessmentBank() outbound.AssessmentBankRepository { return unit.bank }
|
|
|
|
func (unit *fakeUnit) Policies() outbound.PolicyRepository { return unit.policies }
|
|
|
|
type fakeTransactor struct{ unit *fakeUnit }
|
|
|
|
func (transactor fakeTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
|
return fn(ctx, transactor.unit)
|
|
}
|
|
|
|
func newTestBank(t *testing.T) (*Bank, *fakeUnit) {
|
|
t.Helper()
|
|
unit := &fakeUnit{bank: &fakeBank{families: map[string]domain.AssessmentFamily{}}, policies: fakePolicies{stored: map[domain.PolicyVersionID]domain.PolicyVersion{}}}
|
|
return NewBank(fakeTransactor{unit: unit}), unit
|
|
}
|
|
|
|
// testPolicyVersion builds a stored policy version in force.
|
|
func testPolicyVersion(t *testing.T, number int32) domain.PolicyVersion {
|
|
t.Helper()
|
|
values := domain.DemoProductPolicyV1()
|
|
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: values,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
|
}
|
|
numbered, err := draft.WithVersion(number)
|
|
if err != nil {
|
|
t.Fatalf("WithVersion() error = %v", err)
|
|
}
|
|
hash, at := numbered.DocumentHash(), time.Now().Add(-time.Hour)
|
|
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
|
ID: numbered.ID(), Key: string(numbered.Key()), Version: number, Kind: string(numbered.Kind()), Author: string(numbered.Author()),
|
|
EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:],
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
|
}
|
|
return version
|
|
}
|
|
|
|
// storedFamily builds a stored version of the first demo family with the
|
|
// given number and lifecycle, approved by a reviewer unless pending.
|
|
func storedFamily(t *testing.T, bundle Bundle, version int32, approved bool, lifecycle domain.AssessmentLifecycle) domain.AssessmentFamily {
|
|
t.Helper()
|
|
bundle.Families = bundle.Families[:1]
|
|
bundle.Families[0].Version = version
|
|
if approved {
|
|
bundle.Author = "operator:unit-author"
|
|
bundle.Review = BundleReview{Status: "approved", Reviewer: "operator:unit-reviewer"}
|
|
}
|
|
drafts, err := bundle.Drafts()
|
|
if err != nil {
|
|
t.Fatalf("Drafts() error = %v", err)
|
|
}
|
|
draft := drafts[0]
|
|
core, hash := draft.Core(), draft.ContentHash()
|
|
generator, _ := draft.SeedGeneratorJSON()
|
|
key, _ := draft.AnswerKeyJSON()
|
|
rubric, _ := draft.RubricJSON()
|
|
stored := domain.StoredAssessmentFamily{
|
|
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
|
|
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName), Author: string(core.Author),
|
|
Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus), SeedGenerator: generator, AnswerKey: key, Rubric: rubric,
|
|
ContentHash: hash[:], HashScheme: draft.HashScheme(), Lifecycle: string(lifecycle), CreatedAt: time.Now(),
|
|
}
|
|
if lifecycle != domain.AssessmentLifecycleDraft {
|
|
stored.PublishedAt, stored.PublishedBy = time.Now(), string(testOperator)
|
|
}
|
|
if lifecycle == domain.AssessmentLifecycleRetired {
|
|
stored.RetiredAt, stored.RetiredBy = time.Now(), string(testOperator)
|
|
}
|
|
family, err := domain.RestoreAssessmentFamily(stored)
|
|
if err != nil {
|
|
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
|
|
}
|
|
return family
|
|
}
|
|
|
|
func assertRefusal(t *testing.T, operation string, err error, want domain.AssessmentRefusalReason) {
|
|
t.Helper()
|
|
var refusal *domain.AssessmentRefusalError
|
|
if !errors.As(err, &refusal) || refusal.Reason != want || !errors.Is(err, domain.ErrAssessmentRefused) {
|
|
t.Fatalf("%s error = %v, want a refusal with reason %s", operation, err, want)
|
|
}
|
|
}
|
|
|
|
func TestImportAcceptsAConcurrentIdenticalImport(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
bundle := loadDemoBundle(t)
|
|
bundle.Families = bundle.Families[:1]
|
|
drafts, err := bundle.Drafts()
|
|
if err != nil {
|
|
t.Fatalf("Drafts() error = %v", err)
|
|
}
|
|
winner := storedFamily(t, bundle, 1, false, domain.AssessmentLifecycleDraft)
|
|
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
|
unit.bank.onCreate = func() { unit.bank.families[versionKey(drafts[0].Core().Key, 1)] = winner }
|
|
|
|
result, err := bank.ImportBundle(t.Context(), bundle)
|
|
if err != nil || len(result.Created) != 0 || len(result.Unchanged) != 1 {
|
|
t.Fatalf("ImportBundle(concurrent identical import) = %+v, %v, want one unchanged version", result, err)
|
|
}
|
|
}
|
|
|
|
func TestImportRefusesAConcurrentImportWithOtherContent(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
bundle := loadDemoBundle(t)
|
|
bundle.Families = bundle.Families[:1]
|
|
other := bundle
|
|
other.Families = append([]BundleFamily(nil), bundle.Families...)
|
|
other.Families[0].AnswerKey.ReferenceSolution = "A different approach."
|
|
winner := storedFamily(t, other, 1, false, domain.AssessmentLifecycleDraft)
|
|
unit.bank.createErr = outbound.ErrAssessmentFamilyConflict
|
|
unit.bank.onCreate = func() { unit.bank.families[versionKey(winner.Key(), 1)] = winner }
|
|
|
|
_, err := bank.ImportBundle(t.Context(), bundle)
|
|
assertRefusal(t, "ImportBundle(concurrent import with other content)", err, domain.RefusalVersionConflict)
|
|
}
|
|
|
|
func TestDatabaseRacesBecomeRefusalsWithTheMatchingReason(t *testing.T) {
|
|
bundle := loadDemoBundle(t)
|
|
draft := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
|
published := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
|
|
|
t.Run("publication lost to a state change", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
|
unit.bank.markPubErr = outbound.ErrAssessmentFamilyLifecycle
|
|
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
|
assertRefusal(t, "PublishFamily(lifecycle race)", err, domain.RefusalNotDraft)
|
|
if !errors.Is(err, outbound.ErrAssessmentFamilyLifecycle) {
|
|
t.Fatalf("PublishFamily() error = %v, want the storage sentinel kept", err)
|
|
}
|
|
})
|
|
t.Run("publication refused by the review constraint", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(draft.Key(), 1)] = draft
|
|
unit.bank.markPubErr = outbound.ErrAssessmentFamilyNotPublishable
|
|
_, err := bank.PublishFamily(t.Context(), draft.Key(), 1, testOperator)
|
|
assertRefusal(t, "PublishFamily(review constraint)", err, domain.RefusalReviewNotApproved)
|
|
})
|
|
t.Run("retirement lost to a state change", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(published.Key(), 1)] = published
|
|
unit.bank.markRetErr = outbound.ErrAssessmentFamilyLifecycle
|
|
_, err := bank.RetireFamily(t.Context(), published.Key(), 1, testOperator)
|
|
assertRefusal(t, "RetireFamily(lifecycle race)", err, domain.RefusalNotPublished)
|
|
})
|
|
t.Run("opening refused by the coverage constraint", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
version := testPolicyVersion(t, 1)
|
|
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
|
required, err := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
|
if err != nil {
|
|
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
|
}
|
|
unit.bank.published = required
|
|
unit.bank.openErr = outbound.ErrAssessmentCoverageInsufficient
|
|
_, err = bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
|
assertRefusal(t, "OpenCategory(coverage race)", err, domain.RefusalCoverageInsufficient)
|
|
})
|
|
t.Run("opening refused for an unusable policy", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
version := testPolicyVersion(t, 1)
|
|
unit.policies.stored[version.ID()], unit.policies.effective = version, version
|
|
required, _ := domain.RequiredPublishedAssessmentFamilies(version.Policy())
|
|
unit.bank.published = required
|
|
unit.bank.openErr = outbound.ErrAssessmentGradingPolicyNotFound
|
|
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: version.ID(), OpenedBy: "operator:opener"})
|
|
assertRefusal(t, "OpenCategory(policy race)", err, domain.RefusalGradingPolicyMissing)
|
|
})
|
|
}
|
|
|
|
func TestPublishRetiresTheOlderVersionAndRefusesWhenANewerOneIsPublished(t *testing.T) {
|
|
bundle := loadDemoBundle(t)
|
|
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecyclePublished)
|
|
next := storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft)
|
|
newer := storedFamily(t, bundle, 3, true, domain.AssessmentLifecyclePublished)
|
|
|
|
t.Run("older published version", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(next.Key(), 2)] = next
|
|
unit.bank.publishedFam = &older
|
|
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator); err != nil {
|
|
t.Fatalf("PublishFamily() error = %v", err)
|
|
}
|
|
want := []string{"get", "lock", "get", "retire:" + older.ID().String(), "publish:" + next.ID().String()}
|
|
if !slices.Equal(unit.bank.calls, want) {
|
|
t.Fatalf("calls = %v, want %v: lock first, retire the older version, then publish", unit.bank.calls, want)
|
|
}
|
|
})
|
|
t.Run("newer published version", func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(next.Key(), 2)] = next
|
|
unit.bank.families[versionKey(newer.Key(), 3)] = newer
|
|
unit.bank.publishedFam = &newer
|
|
_, err := bank.PublishFamily(t.Context(), next.Key(), 2, testOperator)
|
|
assertRefusal(t, "PublishFamily(newer is published)", err, domain.RefusalNewerVersionPublished)
|
|
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return len(call) > 6 && call[:6] == "retire" }) {
|
|
t.Fatalf("calls = %v, want nothing retired after a refusal", unit.bank.calls)
|
|
}
|
|
})
|
|
t.Run("an operator that is not an operator", func(t *testing.T) {
|
|
bank, _ := newTestBank(t)
|
|
if _, err := bank.PublishFamily(t.Context(), next.Key(), 2, "ai:draft"); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
|
|
t.Fatalf("PublishFamily(ai operator) error = %v, want ErrInvalidAssessmentFamily", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestOpenCategoryRequiresThePolicyInForce(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
first, second := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
|
unit.policies.stored[first.ID()], unit.policies.stored[second.ID()] = first, second
|
|
unit.policies.effective = second
|
|
required, _ := domain.RequiredPublishedAssessmentFamilies(second.Policy())
|
|
unit.bank.published = required
|
|
|
|
_, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: first.ID(), OpenedBy: "operator:opener"})
|
|
assertRefusal(t, "OpenCategory(superseded policy)", err, domain.RefusalGradingPolicyNotCurrent)
|
|
if _, err := bank.OpenCategory(t.Context(), OpenCategoryInput{Category: testCategory, GradingPolicyID: second.ID(), OpenedBy: "operator:opener"}); err != nil {
|
|
t.Fatalf("OpenCategory(policy in force) error = %v", err)
|
|
}
|
|
if unit.bank.calls[0] != "lock" {
|
|
t.Fatalf("calls = %v, want the category lock first", unit.bank.calls)
|
|
}
|
|
}
|
|
|
|
func TestCategoryAvailabilityIsLive(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
if _, err := bank.CategoryAvailability(t.Context(), testCategory); !errors.Is(err, outbound.ErrAssessmentCategoryNotOpen) {
|
|
t.Fatalf("CategoryAvailability(no opening) error = %v, want ErrAssessmentCategoryNotOpen", err)
|
|
}
|
|
inForce := testPolicyVersion(t, 1)
|
|
unit.policies.stored[inForce.ID()], unit.policies.effective = inForce, inForce
|
|
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: inForce.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
|
unit.bank.published = 5
|
|
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
|
t.Fatalf("CategoryAvailability(enough coverage) error = %v", err)
|
|
}
|
|
unit.bank.published = 4
|
|
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
|
assertRefusal(t, "CategoryAvailability(coverage fell)", err, domain.RefusalCoverageInsufficient)
|
|
}
|
|
|
|
func TestPublishRefusesAnOlderVersionWhileANewerOneExistsInAnyState(t *testing.T) {
|
|
bundle := loadDemoBundle(t)
|
|
older := storedFamily(t, bundle, 1, true, domain.AssessmentLifecycleDraft)
|
|
for name, newer := range map[string]domain.AssessmentFamily{
|
|
"draft": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleDraft),
|
|
"published": storedFamily(t, bundle, 2, true, domain.AssessmentLifecyclePublished),
|
|
"retired": storedFamily(t, bundle, 2, true, domain.AssessmentLifecycleRetired),
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
unit.bank.families[versionKey(older.Key(), 1)] = older
|
|
unit.bank.families[versionKey(newer.Key(), 2)] = newer
|
|
_, err := bank.PublishFamily(t.Context(), older.Key(), 1, testOperator)
|
|
assertRefusal(t, "PublishFamily(older than an existing version)", err, domain.RefusalNewerVersionPublished)
|
|
if slices.ContainsFunc(unit.bank.calls, func(call string) bool { return strings.HasPrefix(call, "publish") || strings.HasPrefix(call, "retire") }) {
|
|
t.Fatalf("calls = %v, want nothing published or retired after a refusal", unit.bank.calls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAvailabilityRequiresTheOpeningPolicyToStayInForce(t *testing.T) {
|
|
bank, unit := newTestBank(t)
|
|
opened, replacement := testPolicyVersion(t, 1), testPolicyVersion(t, 2)
|
|
unit.policies.stored[opened.ID()], unit.policies.stored[replacement.ID()] = opened, replacement
|
|
unit.policies.effective = opened
|
|
unit.bank.opening = &domain.AssessmentCategoryOpening{Category: testCategory, PolicyVersionID: opened.ID(), RequiredFamilies: 5, PublishedFamilies: 5}
|
|
unit.bank.published = 5
|
|
if _, err := bank.CategoryAvailability(t.Context(), testCategory); err != nil {
|
|
t.Fatalf("CategoryAvailability(policy in force) error = %v", err)
|
|
}
|
|
// A new policy version takes force: the opening no longer applies.
|
|
unit.policies.effective = replacement
|
|
_, err := bank.CategoryAvailability(t.Context(), testCategory)
|
|
assertRefusal(t, "CategoryAvailability(policy superseded)", err, domain.RefusalGradingPolicyNotCurrent)
|
|
}
|