testutil

package
v0.0.0-...-b90014c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Overview

ABOUTME: Test helper that repeats a delivery claim until the due deliveries have been attempted. ABOUTME: Keeps delivery tests independent of the order of database clock readings.

ABOUTME: Test helpers for serving golden fixture files and rewriting adapter URLs. ABOUTME: Used by feed adapter golden file tests to replay captured API responses offline.

ABOUTME: Mock OIDC Identity Provider for integration testing SSO flows. ABOUTME: Serves discovery, JWKS, and token endpoints; issues real RSA-signed ID tokens.

ABOUTME: Must-style test helpers that call t.Fatalf on error instead of returning errors. ABOUTME: Eliminates the widespread `x, _ := s.Create*(...)` anti-pattern in test setup code.

ABOUTME: Labels test containers with the test process that owns them, and removes ABOUTME: containers whose owner has exited, such as those left by a timed-out test binary.

ABOUTME: Test helper that gives each test its own migrated Postgres database. ABOUTME: One container per test binary holds a migrated template; NewTestDB clones it per test.

ABOUTME: Test helpers for seeding CVE rows and other global test fixtures. ABOUTME: Use SeedTestCVE on *TestDB to insert minimal CVE rows for integration tests.

ABOUTME: Test helper that seeds a test database with curated CVEs from golden fixtures. ABOUTME: Runs adapters against fixture files through the real merge pipeline for deterministic data.

ABOUTME: Test helper that starts an Inbucket SMTP testcontainer for email integration tests. ABOUTME: Use NewTestSMTP(t) to get an SMTP host and port for tests that send email.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GoldenPatch

func GoldenPatch(t *testing.T, feedName, cveID string) feed.CanonicalPatch

GoldenPatch returns the patch one adapter builds for one CVE from its golden fixtures, for tests that need a real record but not the whole corpus. Supported feeds are "nvd" and "mitre".

func NewGoldenServer

func NewGoldenServer(t *testing.T, fixtureDir string) *httptest.Server

NewGoldenServer creates an httptest.Server that serves files from the given directory. The server is automatically closed when the test completes. Fixture files are served at their filename path (e.g., /page-001.json).

func OwnerOption

OwnerOption is ownedContainer for callers without a testing.TB, such as the shared Postgres cluster. A failed sweep is reported on stderr, not returned: it must not stop the tests.

func Run

func Run(m *testing.M) int

Run runs the package's tests and then terminates the shared Postgres container, if any test started one. Every package that calls NewTestDB needs

func TestMain(m *testing.M) { os.Exit(testutil.Run(m)) }

Types

type MockOIDC

type MockOIDC struct {
	Server   *httptest.Server
	Sub      string // subject claim in issued ID tokens
	Email    string // email claim in issued ID tokens
	ClientID string // expected client_id in audience
	// contains filtered or unexported fields
}

MockOIDC is a configurable OIDC identity provider for tests.

func NewMockOIDC

func NewMockOIDC(t *testing.T) *MockOIDC

NewMockOIDC creates a mock OIDC server that serves:

  • GET /.well-known/openid-configuration
  • POST /token — exchanges code for tokens (returns RSA-signed ID token)
  • GET /keys — JWKS endpoint with the test RSA public key

func (*MockOIDC) SetNonce

func (m *MockOIDC) SetNonce(nonce string)

SetNonce configures the nonce claim for the next ID token issued by the mock.

type SeedCVEOpts

type SeedCVEOpts struct {
	Status                string
	DescriptionPrimary    string
	CvssV3Score           *float64
	EpssScore             *float64
	ExploitAvailable      bool
	InCisaKev             bool
	DateModifiedCanonical *time.Time
	MaterialHash          string
}

SeedCVEOpts provides optional overrides when seeding a test CVE row. All fields default to sensible test values when nil/zero.

type SeedStats

type SeedStats struct {
	TotalCVEs   int      // total unique CVEs ingested across all feeds
	FeedsSeeded int      // number of feeds that produced patches
	FeedNames   []string // names of feeds that were seeded
}

SeedStats reports what SeedCorpus populated.

func SeedCorpus

func SeedCorpus(t *testing.T, db *TestDB) SeedStats

SeedCorpus runs all feed adapters against their golden fixtures through the real merge pipeline, producing a deterministic CVE corpus in the test DB. EPSS scores are applied last (requires CVE rows to exist).

type TestDB

type TestDB struct {
	*store.Store // superuser store — bypasses RLS (for data setup)
	// AppStore connects as cvert_ops_app (NOBYPASSRLS) — use for RLS isolation tests.
	AppStore *store.Store
	// URL is the superuser connection string for this test's database.
	URL string
	// AppURL connects to the same database as cvert_ops_app.
	AppURL string
}

TestDB wraps a Store with helpers for RLS integration tests. It embeds *store.Store so all store methods are directly callable, keeping all existing tests working without modification.

func NewTestDB

func NewTestDB(t *testing.T) *TestDB

NewTestDB returns a TestDB backed by a new database cloned from the test binary's migrated template. The first call in a binary starts the shared container and migrates the template. The database and pools are cleaned up via t.Cleanup; the container is terminated by Run.

func (*TestDB) ClaimUntilDeliveriesAttempted

func (tdb *TestDB) ClaimUntilDeliveriesAttempted(t *testing.T, ctx context.Context, claim func())

ClaimUntilDeliveriesAttempted calls claim until no delivery written to be sent now remains unattempted. send_after and the claim's now() are read in separate transactions from a wall clock that can step backward between them, so a single claim can find a delivery not yet due.

func (*TestDB) MustCreateGroup

func (tdb *TestDB) MustCreateGroup(t *testing.T, ctx context.Context, orgID uuid.UUID, name, description string) *generated.Group

MustCreateGroup creates a group or fatals the test.

func (*TestDB) MustCreateOrg

func (tdb *TestDB) MustCreateOrg(t *testing.T, ctx context.Context, name string) *generated.Organization

MustCreateOrg creates an org or fatals the test.

func (*TestDB) MustCreateUser

func (tdb *TestDB) MustCreateUser(t *testing.T, ctx context.Context, email, displayName, passwordHash string, hashVersion int) *generated.User

MustCreateUser creates a user or fatals the test.

func (*TestDB) MustGetCVE

func (tdb *TestDB) MustGetCVE(t *testing.T, ctx context.Context, cveID string) *generated.CVE

MustGetCVE gets a CVE by ID or fatals the test.

func (*TestDB) SeedTestCVE

func (tdb *TestDB) SeedTestCVE(t *testing.T, cveID, severity string, opts *SeedCVEOpts)

SeedTestCVE inserts a minimal CVE row via the superuser connection. The cves table is global (no org_id, no RLS), so no bypass transaction is needed. Pass nil for opts to use defaults.

type TestSMTP

type TestSMTP struct {
	Host   string
	Port   int
	WebURL string
}

TestSMTP holds connection details for an Inbucket SMTP test server.

func NewTestSMTP

func NewTestSMTP(t *testing.T) *TestSMTP

NewTestSMTP starts an Inbucket container and returns the SMTP connection details. The container is cleaned up via t.Cleanup.

type URLRewriteTransport

type URLRewriteTransport struct {
	// OriginalBase is the prefix to match and replace (e.g., "https://services.nvd.nist.gov").
	OriginalBase string
	// RewriteBase is the replacement prefix (e.g., "http://127.0.0.1:12345").
	RewriteBase string
	// Inner is the underlying transport to use after rewriting.
	Inner http.RoundTripper
}

URLRewriteTransport intercepts HTTP requests targeting a specific base URL and rewrites them to point at a test server instead. The path and query string are preserved. This lets adapter golden file tests use the adapter's real Fetch method with hardcoded URLs, redirecting traffic to a local httptest server serving fixture files.

func NewURLRewriteTransport

func NewURLRewriteTransport(originalBase, rewriteBase string, inner http.RoundTripper) *URLRewriteTransport

NewURLRewriteTransport creates a URLRewriteTransport.

func (*URLRewriteTransport) RoundTrip

func (t *URLRewriteTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip rewrites matching request URLs and delegates to the inner transport.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL