feat(deploy): add an isolated demo stand with synthetic seed and guarded reset
This commit is contained in:
1 parent
bd23c839fd
commit
e1df4ff77c
26 files changed
+3292
-2
No files matched your search
@@ -0,0 +1,329 @@
|
||||
// Package demoseed implements the local operator command of the isolated
|
||||
// demonstration stand: it seeds the synthetic demo world, checks whether the
|
||||
// stand's database may be discarded by a reset, and prints an inventory of
|
||||
// counts. Every subcommand requires DEMO_MODE=isolated, and the command never
|
||||
// deletes anything; the reset itself is a deploy target that discards the
|
||||
// dedicated demo Compose project after this check.
|
||||
package demoseed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
seedusecase "lincodex/backend/internal/usecase/demoseed"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/profile"
|
||||
"lincodex/backend/internal/usecase/questionnaire"
|
||||
)
|
||||
|
||||
const (
|
||||
usage = "usage: demo-seed seed --actor operator:<handle> | demo-seed check-reset | demo-seed inventory"
|
||||
|
||||
// DemoModeName and IsolatedDemoMode are the explicit guard of the command.
|
||||
DemoModeName = "DEMO_MODE"
|
||||
IsolatedDemoMode = "isolated"
|
||||
// PasswordName holds the shared password of the synthetic accounts. It
|
||||
// comes from the demo env file and is never printed.
|
||||
PasswordName = "DEMO_ACCOUNT_PASSWORD" //nolint:gosec // The name of an environment variable, not a credential.
|
||||
|
||||
// poolSize covers the seed's sequential transactions and the nested
|
||||
// reads of the services it drives.
|
||||
poolSize = 4
|
||||
// hashConcurrency is one Argon2id derivation at a time; the seed creates a
|
||||
// handful of accounts once.
|
||||
hashConcurrency = 1
|
||||
// ephemeralKeyBytes is the size of the per-run idempotency secret. The
|
||||
// seed is idempotent by the state it reads, so its idempotency records
|
||||
// need no key shared with the backend.
|
||||
ephemeralKeyBytes = 48
|
||||
)
|
||||
|
||||
const syntheticWarning = "warning: synthetic demonstration data for an isolated demo stand only; never on a stand with real people\n"
|
||||
|
||||
// Subcommand names one action.
|
||||
type Subcommand string
|
||||
|
||||
const (
|
||||
SubcommandSeed Subcommand = "seed"
|
||||
SubcommandCheckReset Subcommand = "check-reset"
|
||||
SubcommandInventory Subcommand = "inventory"
|
||||
)
|
||||
|
||||
// Command is a parsed, validated request.
|
||||
type Command struct {
|
||||
Subcommand Subcommand
|
||||
Actor domain.AssessmentOperator
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
switch Subcommand(args[0]) {
|
||||
case SubcommandCheckReset, SubcommandInventory:
|
||||
if len(args) != 1 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
return Command{Subcommand: Subcommand(args[0])}, nil
|
||||
case SubcommandSeed:
|
||||
default:
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("demo-seed seed", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
operator, err := domain.ParseAssessmentOperator(strings.TrimSpace(*actor))
|
||||
if err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return Command{Subcommand: SubcommandSeed, Actor: operator}, nil
|
||||
}
|
||||
|
||||
// settings are the validated environment values of one run.
|
||||
type settings struct {
|
||||
databaseURL string
|
||||
password domain.Password
|
||||
}
|
||||
|
||||
// readSettings checks the demo mode guard, DATABASE_URL, and, for the seed,
|
||||
// the account password, all before any connection. It loads no dotenv file.
|
||||
func readSettings(command Command, lookup config.LookupEnv) (settings, error) {
|
||||
mode, _ := lookup(DemoModeName)
|
||||
if strings.TrimSpace(mode) != IsolatedDemoMode {
|
||||
return settings{}, errors.New("DEMO_MODE=isolated is required; the demo seed runs only on an isolated demo stand")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return settings{}, errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
result := settings{databaseURL: databaseURL}
|
||||
if command.Subcommand != SubcommandSeed {
|
||||
return result, nil
|
||||
}
|
||||
raw, _ := lookup(PasswordName)
|
||||
password, err := domain.NewPassword(raw)
|
||||
if err != nil {
|
||||
return settings{}, fmt.Errorf("%s must be a password of at least %d characters", PasswordName, domain.MinNewPasswordCodePoints)
|
||||
}
|
||||
result.password = password
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Run parses the command, validates the environment, connects, and executes.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil || clock == nil {
|
||||
return errors.New("demo seed command dependencies are required")
|
||||
}
|
||||
values, err := readSettings(command, lookup)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(output, syntheticWarning); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, values.databaseURL, poolSize)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
store := postgres.NewDemoSeedStore(pool)
|
||||
inspector, err := seedusecase.NewInspector(store)
|
||||
if err != nil {
|
||||
return errors.New("demo seed is unavailable")
|
||||
}
|
||||
switch command.Subcommand {
|
||||
case SubcommandCheckReset:
|
||||
return ExecuteCheckReset(ctx, inspector, output)
|
||||
case SubcommandInventory:
|
||||
return ExecuteInventory(ctx, inspector, output)
|
||||
case SubcommandSeed:
|
||||
seeder, err := newSeeder(pool, store, clock)
|
||||
if err != nil {
|
||||
return errors.New("demo seed is unavailable")
|
||||
}
|
||||
return ExecuteSeed(ctx, seeder, seedusecase.Input{Actor: command.Actor, Password: values.password}, output)
|
||||
}
|
||||
return errors.New(usage)
|
||||
}
|
||||
|
||||
// newSeeder wires the product services the seed drives. Synthetic category
|
||||
// assignment is on because the command runs only with DEMO_MODE=isolated.
|
||||
func newSeeder(pool *pgxpool.Pool, store outbound.DemoSeedStore, clock func() time.Time) (*seedusecase.Seeder, error) {
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
hasher, err := argon2id.NewHasher(hashConcurrency)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - create hasher: %w", err)
|
||||
}
|
||||
secret := make([]byte, ephemeralKeyBytes)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - draw idempotency secret: %w", err)
|
||||
}
|
||||
keyring, err := identity.NewKeyring(secret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - create keyring: %w", err)
|
||||
}
|
||||
attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock,
|
||||
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - create attempt service: %w", err)
|
||||
}
|
||||
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - create privacy service: %w", err)
|
||||
}
|
||||
attestor, err := assessment.NewCategoryAttestor(transactor)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("demoseed.newSeeder - create attestor: %w", err)
|
||||
}
|
||||
return seedusecase.NewSeeder(seedusecase.Dependencies{
|
||||
Transactor: transactor, Store: store, Hasher: hasher,
|
||||
Consents: consent.NewService(transactor, clock),
|
||||
Profiles: profile.NewService(transactor, clock),
|
||||
Questionnaires: questionnaire.NewService(transactor, clock),
|
||||
Privacy: privacy, Attempts: attempts,
|
||||
Bank: assessment.NewBank(transactor), Attestor: attestor, Clock: clock,
|
||||
})
|
||||
}
|
||||
|
||||
// Seeder runs the seed.
|
||||
type Seeder interface {
|
||||
Seed(ctx context.Context, input seedusecase.Input) (seedusecase.Report, error)
|
||||
}
|
||||
|
||||
// ExecuteSeed seeds and prints what was created, the logins, and the
|
||||
// prepared attempts. It prints synthetic addresses and identifiers only; the
|
||||
// password stays in the demo env file.
|
||||
func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, output io.Writer) error {
|
||||
if seeder == nil || output == nil {
|
||||
return errors.New("demo seed command dependencies are required")
|
||||
}
|
||||
report, err := seeder.Seed(ctx, input)
|
||||
if err != nil {
|
||||
return safeSeedError(err)
|
||||
}
|
||||
var text strings.Builder
|
||||
fmt.Fprintf(&text, "seeded: product policy version %d; created %d records, found %d already present\n",
|
||||
report.PolicyVersion, len(report.Created), len(report.Present))
|
||||
for _, item := range report.Created {
|
||||
fmt.Fprintf(&text, "created: %s\n", item)
|
||||
}
|
||||
for _, login := range report.Logins {
|
||||
fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role)
|
||||
}
|
||||
text.WriteString("password: the " + PasswordName + " value of the demo env file; it is not printed\n")
|
||||
for _, prepared := range report.PreparedAttempts {
|
||||
fmt.Fprintf(&text, "prepared full attempt: %s of %s\n", prepared.AttemptID, prepared.Email)
|
||||
}
|
||||
text.WriteString("note: the prepared attempts were answered by the seed through the ordinary attempt operations; " +
|
||||
"they are synthetic and no person took them. The express mode has its own policy section and bank and never assigns a category.\n")
|
||||
if _, err := io.WriteString(output, text.String()); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeSeedError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, seedusecase.ErrStandNotFresh):
|
||||
return errors.New("the stand holds ordinary accounts and was never seeded; seed only a fresh isolated demo stand")
|
||||
case errors.Is(err, seedusecase.ErrForeignPolicy):
|
||||
return errors.New("the product policy is neither the initial demo version nor the seeded one; seed only a fresh isolated demo stand")
|
||||
case errors.Is(err, seedusecase.ErrAccountConflict):
|
||||
return errors.New("a demo address belongs to an account the seed did not create; reset the isolated demo stand")
|
||||
case errors.Is(err, seedusecase.ErrPreparedAttemptFailed):
|
||||
return errors.New("a prepared attempt did not assign its demonstration category; reset the isolated demo stand")
|
||||
case errors.Is(err, outbound.ErrPolicyVersionNotFound):
|
||||
return errors.New("the product policy has no version yet; start the backend once so that it seeds the demo policy")
|
||||
default:
|
||||
return errors.New("demo seed failed")
|
||||
}
|
||||
}
|
||||
|
||||
// Inspector reads the census and the inventory.
|
||||
type Inspector interface {
|
||||
CheckReset(ctx context.Context) (seedusecase.ResetCheck, error)
|
||||
Inventory(ctx context.Context) (outbound.DemoInventory, error)
|
||||
}
|
||||
|
||||
// ExecuteCheckReset prints the verdict and fails when the database holds an
|
||||
// account outside the synthetic domain, so the reset target stops before it
|
||||
// discards anything.
|
||||
func ExecuteCheckReset(ctx context.Context, inspector Inspector, output io.Writer) error {
|
||||
if inspector == nil || output == nil {
|
||||
return errors.New("demo seed command dependencies are required")
|
||||
}
|
||||
check, err := inspector.CheckReset(ctx)
|
||||
if err != nil {
|
||||
return errors.New("reset check failed")
|
||||
}
|
||||
if !check.Verdict.Allowed() {
|
||||
return fmt.Errorf("reset refused: the stand holds %d accounts outside @%s; the reset never deletes ordinary data",
|
||||
check.Census.Ordinary(), seedusecase.SyntheticDomain)
|
||||
}
|
||||
if _, err := fmt.Fprintf(output, "reset allowed (%s): %d accounts, all on @%s\n",
|
||||
check.Verdict, check.Census.Total, seedusecase.SyntheticDomain); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExecuteInventory prints stable key=value counts, so two runs can be
|
||||
// compared line by line.
|
||||
func ExecuteInventory(ctx context.Context, inspector Inspector, output io.Writer) error {
|
||||
if inspector == nil || output == nil {
|
||||
return errors.New("demo seed command dependencies are required")
|
||||
}
|
||||
inventory, err := inspector.Inventory(ctx)
|
||||
if err != nil {
|
||||
return errors.New("inventory failed")
|
||||
}
|
||||
lines := []struct {
|
||||
name string
|
||||
value int64
|
||||
}{
|
||||
{"synthetic_accounts", inventory.SyntheticAccounts}, {"verified_synthetic_accounts", inventory.VerifiedSynthetic},
|
||||
{"ordinary_accounts", inventory.OrdinaryAccounts}, {"organizations", inventory.Organizations},
|
||||
{"memberships", inventory.Memberships}, {"consent_records", inventory.ConsentRecords},
|
||||
{"candidate_profiles", inventory.CandidateProfiles}, {"questionnaires", inventory.Questionnaires},
|
||||
{"attempts", inventory.Attempts}, {"attempt_results", inventory.AttemptResults},
|
||||
{"current_categories", inventory.CurrentCategories}, {"evidence_facts", inventory.EvidenceFacts},
|
||||
{"published_cards", inventory.PublishedCards}, {"product_policy_versions", inventory.ProductPolicyVersions},
|
||||
{"published_families", inventory.PublishedFamilies}, {"category_openings", inventory.CategoryOpenings},
|
||||
{"category_attestations", inventory.CategoryAttestations}, {"training_bindings", inventory.TrainingBindings},
|
||||
}
|
||||
var text strings.Builder
|
||||
for _, line := range lines {
|
||||
fmt.Fprintf(&text, "%s=%d\n", line.name, line.value)
|
||||
}
|
||||
if _, err := io.WriteString(output, text.String()); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package demoseed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
seedusecase "lincodex/backend/internal/usecase/demoseed"
|
||||
)
|
||||
|
||||
func TestParseAcceptsOnlyTheThreeSubcommands(t *testing.T) {
|
||||
command, err := Parse([]string{"seed", "--actor", "operator:night"})
|
||||
if err != nil || command.Subcommand != SubcommandSeed || command.Actor != "operator:night" {
|
||||
t.Fatalf("Parse(seed) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{{"check-reset"}, {"inventory"}} {
|
||||
if command, err := Parse(args); err != nil || string(command.Subcommand) != args[0] {
|
||||
t.Errorf("Parse(%v) = %+v, %v", args, command, err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil, {"reset"}, {"seed"}, {"seed", "--actor", "alice"}, {"seed", "--actor", "system:demo-seed"},
|
||||
{"seed", "--actor", "operator:night", "extra"}, {"check-reset", "--force"}, {"inventory", "all"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lookupOf(values map[string]string) func(string) (string, bool) {
|
||||
return func(key string) (string, bool) {
|
||||
value, ok := values[key]
|
||||
return value, ok
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRefusesWithoutTheIsolatedModeBeforeReadingAnythingElse(t *testing.T) {
|
||||
for _, mode := range []string{"", "production", "ISOLATED", "isolated-ish"} {
|
||||
values := map[string]string{"DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "a long synthetic password"}
|
||||
if mode != "" {
|
||||
values[DemoModeName] = mode
|
||||
}
|
||||
var output bytes.Buffer
|
||||
err := Run(context.Background(), []string{"check-reset"}, lookupOf(values), &output, time.Now)
|
||||
if err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") || output.Len() != 0 {
|
||||
t.Errorf("Run with DEMO_MODE=%q = %v, output %q; want a refusal before any output", mode, err, output.String())
|
||||
}
|
||||
}
|
||||
err := Run(context.Background(), []string{"seed", "--actor", "operator:night"},
|
||||
lookupOf(map[string]string{DemoModeName: IsolatedDemoMode, "DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "short"}),
|
||||
&bytes.Buffer{}, time.Now)
|
||||
if err == nil || !strings.Contains(err.Error(), PasswordName) || strings.Contains(err.Error(), "short") {
|
||||
t.Fatalf("Run(seed, short password) = %v, want a refusal that does not echo the value", err)
|
||||
}
|
||||
err = Run(context.Background(), []string{"inventory"}, lookupOf(map[string]string{DemoModeName: IsolatedDemoMode}), &bytes.Buffer{}, time.Now)
|
||||
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(inventory) without a database = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type seederFake struct {
|
||||
report seedusecase.Report
|
||||
err error
|
||||
}
|
||||
|
||||
func (fake seederFake) Seed(context.Context, seedusecase.Input) (seedusecase.Report, error) {
|
||||
return fake.report, fake.err
|
||||
}
|
||||
|
||||
func TestExecuteSeedPrintsLoginsAndAttemptsButNeverThePassword(t *testing.T) {
|
||||
attemptID, err := domain.NewAssessmentAttemptID()
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttemptID() error = %v", err)
|
||||
}
|
||||
report := seedusecase.Report{
|
||||
PolicyVersion: 2, Created: []string{"account candidate@demo.lincodex.test"},
|
||||
Logins: []seedusecase.Login{{Email: "candidate@demo.lincodex.test", Role: "candidate"}},
|
||||
PreparedAttempts: []seedusecase.PreparedAttempt{{Email: "prepared-1@demo.lincodex.test", AttemptID: attemptID}},
|
||||
}
|
||||
var output bytes.Buffer
|
||||
password, err := domain.NewPassword("a long synthetic password")
|
||||
if err != nil {
|
||||
t.Fatalf("NewPassword() error = %v", err)
|
||||
}
|
||||
if err := ExecuteSeed(context.Background(), seederFake{report: report}, seedusecase.Input{Password: password}, &output); err != nil {
|
||||
t.Fatalf("ExecuteSeed() error = %v", err)
|
||||
}
|
||||
text := output.String()
|
||||
for _, want := range []string{
|
||||
"created 1 records, found 0", "login: candidate@demo.lincodex.test", "prepared full attempt: " + attemptID.String(),
|
||||
"no person took them", "never assigns a category",
|
||||
} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, text)
|
||||
}
|
||||
}
|
||||
if strings.Contains(text, "a long synthetic password") {
|
||||
t.Fatal("the output contains the password")
|
||||
}
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{seedusecase.ErrStandNotFresh, "never seeded"},
|
||||
{seedusecase.ErrForeignPolicy, "neither the initial demo version"},
|
||||
{seedusecase.ErrAccountConflict, "did not create"},
|
||||
{seedusecase.ErrPreparedAttemptFailed, "did not assign"},
|
||||
{outbound.ErrPolicyVersionNotFound, "no version yet"},
|
||||
{errors.New("pq: password authentication failed for user x"), "demo seed failed"},
|
||||
} {
|
||||
err := ExecuteSeed(context.Background(), seederFake{err: test.err}, seedusecase.Input{}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "authentication") {
|
||||
t.Errorf("ExecuteSeed(%v) = %v, want a safe message containing %q", test.err, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type inspectorFake struct {
|
||||
census outbound.DemoAccountCensus
|
||||
err error
|
||||
}
|
||||
|
||||
func (fake inspectorFake) CheckReset(context.Context) (seedusecase.ResetCheck, error) {
|
||||
return seedusecase.ResetCheck{Verdict: seedusecase.DecideReset(fake.census), Census: fake.census}, fake.err
|
||||
}
|
||||
|
||||
func (fake inspectorFake) Inventory(context.Context) (outbound.DemoInventory, error) {
|
||||
return outbound.DemoInventory{SyntheticAccounts: fake.census.Synthetic, OrdinaryAccounts: fake.census.Ordinary()}, fake.err
|
||||
}
|
||||
|
||||
func TestExecuteCheckResetFailsOnOrdinaryAccounts(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
census outbound.DemoAccountCensus
|
||||
want string
|
||||
fails bool
|
||||
}{
|
||||
{outbound.DemoAccountCensus{}, "reset allowed (empty)", false},
|
||||
{outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, "reset allowed (synthetic): 9 accounts", false},
|
||||
{outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, "holds 1 accounts outside", true},
|
||||
{outbound.DemoAccountCensus{Total: 1}, "holds 1 accounts outside", true},
|
||||
} {
|
||||
var output bytes.Buffer
|
||||
err := ExecuteCheckReset(context.Background(), inspectorFake{census: test.census}, &output)
|
||||
if test.fails != (err != nil) {
|
||||
t.Fatalf("ExecuteCheckReset(%+v) = %v, want failure %v", test.census, err, test.fails)
|
||||
}
|
||||
text := output.String()
|
||||
if err != nil {
|
||||
text = err.Error()
|
||||
}
|
||||
if !strings.Contains(text, test.want) {
|
||||
t.Errorf("ExecuteCheckReset(%+v) said %q, want %q", test.census, text, test.want)
|
||||
}
|
||||
}
|
||||
if err := ExecuteCheckReset(context.Background(), inspectorFake{err: errors.New("connection reset")}, &bytes.Buffer{}); err == nil ||
|
||||
err.Error() != "reset check failed" {
|
||||
t.Fatalf("ExecuteCheckReset(store failure) = %v, want a refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteInventoryPrintsStableCounts(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
if err := ExecuteInventory(context.Background(), inspectorFake{census: outbound.DemoAccountCensus{Total: 10, Synthetic: 9}}, &output); err != nil {
|
||||
t.Fatalf("ExecuteInventory() error = %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(output.String(), "synthetic_accounts=9\nverified_synthetic_accounts=0\nordinary_accounts=1\n") {
|
||||
t.Fatalf("inventory = %q", output.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user