testutil

package
v0.0.0-...-dacee18 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package testutil provides shared test utilities for Melange integration tests.

Package testutil provides shared test utilities for Melange integration tests.

Package testutil provides shared test utilities for Melange integration tests.

Index

Constants

This section is empty.

Variables

View Source
var KitchenSinkScaleSmall = KitchenSinkScale{
	Name: "small", Users: 40, ServiceAccounts: 6, Groups: 12, GroupChainLen: 4,
	Orgs: 4, MembersPerOrg: 12, TeamsPerOrg: 2, ProjectsPerOrg: 3,
	FolderDepth: 4, FoldersPerLevel: 2, DocsPerFolder: 3, PlatformAdmins: 2,
}

KitchenSinkScaleSmall is sized for the differential correctness test: small enough to enumerate every (subject, object) pair against check_permission, large enough that every relation has both granted and denied results.

View Source
var KitchenSinkScales = []KitchenSinkScale{
	{Name: "1K", Users: 200, ServiceAccounts: 20, Groups: 40, GroupChainLen: 4, Orgs: 5, MembersPerOrg: 20, TeamsPerOrg: 3, ProjectsPerOrg: 5, FolderDepth: 4, FoldersPerLevel: 3, DocsPerFolder: 4, PlatformAdmins: 3},
	{Name: "10K", Users: 1000, ServiceAccounts: 80, Groups: 120, GroupChainLen: 5, Orgs: 15, MembersPerOrg: 40, TeamsPerOrg: 4, ProjectsPerOrg: 10, FolderDepth: 5, FoldersPerLevel: 4, DocsPerFolder: 6, PlatformAdmins: 5},
	{Name: "100K", Users: 5000, ServiceAccounts: 300, Groups: 400, GroupChainLen: 6, Orgs: 40, MembersPerOrg: 80, TeamsPerOrg: 6, ProjectsPerOrg: 20, FolderDepth: 6, FoldersPerLevel: 5, DocsPerFolder: 10, PlatformAdmins: 10},
	{Name: "1M", Users: 25000, ServiceAccounts: 1500, Groups: 2000, GroupChainLen: 6, Orgs: 100, MembersPerOrg: 200, TeamsPerOrg: 8, ProjectsPerOrg: 40, FolderDepth: 7, FoldersPerLevel: 6, DocsPerFolder: 16, PlatformAdmins: 25},
}

KitchenSinkScales are the benchmark sizes.

View Source
var SaaSScaleSmall = SaaSScale{
	Name: "small", Orgs: 16, Partners: 3, ClientsPerPartner: 3, UsersPerOrg: 5, Staff: 2,
	Contacts: 600, ContactOrgs: 6, DealsPerOrg: 6, QueuesPerOrg: 3, TicketsPerOrg: 8,
	InvoicesPerOrg: 5, EmployeesPerOrg: 5, TeamsPerOrg: 3, FoldersPerOrg: 7, DocsPerOrg: 10,
}

SaaSScaleSmall is sized for the differential correctness test.

View Source
var SaaSScales = []SaaSScale{
	{
		Name: "100K", Orgs: 80, Partners: 8, ClientsPerPartner: 5, UsersPerOrg: 6, Staff: 6,
		Contacts: 75_000, ContactOrgs: 20, DealsPerOrg: 60, QueuesPerOrg: 4, TicketsPerOrg: 80,
		InvoicesPerOrg: 40, EmployeesPerOrg: 30, TeamsPerOrg: 3, FoldersPerOrg: 13, DocsPerOrg: 60,
	},
	{
		Name: "1M", Orgs: 190, Partners: 24, ClientsPerPartner: 5, UsersPerOrg: 6, Staff: 24,
		Contacts: 900_000, ContactOrgs: 62, DealsPerOrg: 150, QueuesPerOrg: 4, TicketsPerOrg: 200,
		InvoicesPerOrg: 80, EmployeesPerOrg: 60, TeamsPerOrg: 3, FoldersPerOrg: 40, DocsPerOrg: 150,
	},
	{
		Name: "5M", Orgs: 190, Partners: 24, ClientsPerPartner: 5, UsersPerOrg: 6, Staff: 24,
		Contacts: 4_600_000, ContactOrgs: 62, DealsPerOrg: 150, QueuesPerOrg: 4, TicketsPerOrg: 200,
		InvoicesPerOrg: 80, EmployeesPerOrg: 60, TeamsPerOrg: 3, FoldersPerOrg: 40, DocsPerOrg: 150,
	},
}

SaaSScales are the benchmark sizes, named by their approximate tuple count. The 1M and 5M scales have production's tenant count; 5M has its contact volume too and needs MELANGE_BENCH_LARGE_SCALE=1.

Functions

func AnalyzeKitchenSink

func AnalyzeKitchenSink() ([]compiler.RelationAnalysis, error)

AnalyzeKitchenSink runs the analysis pipeline over the kitchen-sink schema and returns the per-relation analyses (with ListStrategy and Features populated). DB-free; used by the generator-coverage test to assert every strategy and feature combination is exercised.

func BenchLoop

func BenchLoop(b *testing.B, db *sql.DB, op func())

BenchLoop runs op b.N times. When db is non-nil and has pg_stat_statements (see EnableServerStats), it also reports where the time went:

  • db-ns/op: server time (planning, if tracked, plus execution) of the statements op sent, from pg_stat_statements
  • net-ns/op: the rest of the wall time: network round trips plus client and driver work
  • stmts/op: statements op sent

db-ns/op and net-ns/op add up to the wall time of the loop, which matches ns/op apart from timer granularity. test/cmd/benchreport turns these into tables.

func DB

func DB(tb testing.TB) *sql.DB

DB returns a fully migrated database connection for testing. Each call creates a new isolated database copied from the template. The database is automatically cleaned up when the test completes. Works with both *testing.T and *testing.B.

If DATABASE_URL environment variable is set, connects to remote database instead.

func DBWithDatabaseSchema

func DBWithDatabaseSchema(tb testing.TB, databaseSchema string) *sql.DB

DBWithDatabaseSchema is like DB but seeds the isolated test database from the given database schema. An empty databaseSchema uses the default template.

func DSN

func DSN(tb testing.TB) string

DSN returns the connection string for an isolated test database. Unlike DB(), it returns the raw DSN so callers can open with any driver. The database is automatically cleaned up when the test completes.

func DSNWithDatabaseSchema

func DSNWithDatabaseSchema(tb testing.TB, databaseSchema string) string

DSNWithDatabaseSchema is like DSN but seeds the isolated test database from the given database schema. An empty databaseSchema uses the default template.

func DomainTablesSQL

func DomainTablesSQL() string

DomainTablesSQL returns the embedded SQL for creating domain tables. Domain tables always live in the public schema.

func EmptyDB

func EmptyDB(tb testing.TB) *sql.DB

EmptyDB returns an empty database connection for testing. Each call creates a new isolated empty database. The database is automatically cleaned up when the test completes. Works with both *testing.T and *testing.B.

func EmptyDBWithDSN

func EmptyDBWithDSN(tb testing.TB) (db *sql.DB, dsn string)

EmptyDBWithDSN is EmptyDB, also returning the database's DSN for opening further connections to it.

func EnableServerStats

func EnableServerStats(db *sql.DB)

EnableServerStats installs pg_stat_statements in db. It only works when the server preloads the library (Cloud SQL does; the default test container does not), and BenchLoop skips the breakdown when it is unavailable. A nil db is a no-op.

func KitchenSinkListSubjectsSQL

func KitchenSinkListSubjectsSQL() ([]string, error)

KitchenSinkListSubjectsSQL compiles the kitchen-sink schema and returns the generated list_subjects function bodies. DB-free; used for codegen-shape assertions over a realistic mix of wildcard and non-wildcard relations.

func LoadKitchenSinkTuples

func LoadKitchenSinkTuples(tb testing.TB, db *sql.DB, tuples []KitchenSinkTuple)

LoadKitchenSinkTuples bulk-loads tuples via COPY (batched INSERT fallback).

func PostgresSchema

func PostgresSchema(schema string) string

PostgresSchema returns a literal with the schema name or "current_schema()" if empty.

func SetupKitchenSinkDB

func SetupKitchenSinkDB(tb testing.TB) *sql.DB

SetupKitchenSinkDB returns a fresh database with the kitchen-sink schema migrated and a melange_tuples view over an (empty) kitchen_sink_tuples base table. Call LoadKitchenSinkTuples to populate it.

func TuplesViewSQL

func TuplesViewSQL(databaseSchema string) string

TuplesViewSQL returns the embedded SQL for creating the tuples view.

Types

type BulkFixtures

type BulkFixtures struct {
	// contains filtered or unexported fields
}

BulkFixtures provides factory functions for creating test data using PostgreSQL COPY FROM. This is 10-100x faster than batch INSERTs for large datasets.

func NewBulkFixtures

func NewBulkFixtures(ctx context.Context, db *sql.DB) *BulkFixtures

NewBulkFixtures creates a new BulkFixtures instance for bulk data loading via COPY FROM.

func (*BulkFixtures) AddOrganizationMembers

func (bf *BulkFixtures) AddOrganizationMembers(orgID int64, userIDs []int64, role string) error

AddOrganizationMembers adds users to an organization with the specified role using COPY FROM.

func (*BulkFixtures) CreateOrganizations

func (bf *BulkFixtures) CreateOrganizations(n int) ([]int64, error)

CreateOrganizations creates n organizations using COPY FROM. Falls back to batch INSERT if COPY fails.

func (*BulkFixtures) CreatePullRequests

func (bf *BulkFixtures) CreatePullRequests(repoID int64, authorIDs []int64, n int) ([]int64, error)

CreatePullRequests creates pull requests in the given repository using COPY FROM. Cycles through authorIDs for each PR.

func (*BulkFixtures) CreateRepositories

func (bf *BulkFixtures) CreateRepositories(orgID int64, n int) ([]int64, error)

CreateRepositories creates n repositories under an organization using COPY FROM.

func (*BulkFixtures) CreateUsers

func (bf *BulkFixtures) CreateUsers(n int) ([]int64, error)

CreateUsers creates n users using COPY FROM for bulk loading. Falls back to batch INSERT if COPY fails.

func (*BulkFixtures) TupleCount

func (bf *BulkFixtures) TupleCount() (int, error)

TupleCount returns the current count of tuples in the melange_tuples view.

type DatabaseConfig

type DatabaseConfig struct {
	URL            string
	MaxConnections int
	EnablePooling  bool
}

DatabaseConfig holds configuration for connecting to a database.

func GetDatabaseConfig

func GetDatabaseConfig() DatabaseConfig

GetDatabaseConfig reads database configuration from environment variables. If DATABASE_URL is set, it returns configuration for a remote database. Otherwise, returns an empty config which signals to use testcontainers.

type Fixtures

type Fixtures struct {
	// contains filtered or unexported fields
}

Fixtures provides factory functions for creating test data in bulk. All functions use batch inserts for efficiency at scale.

func NewFixtures

func NewFixtures(ctx context.Context, db *sql.DB) *Fixtures

NewFixtures creates a new Fixtures instance for bulk data insertion.

func (*Fixtures) AddOrganizationMembers

func (f *Fixtures) AddOrganizationMembers(orgID int64, userIDs []int64, role string) error

AddOrganizationMembers adds users to an organization with the specified role. role must be one of: owner, admin, member, billing_manager

func (*Fixtures) CreateOrganizations

func (f *Fixtures) CreateOrganizations(n int) ([]int64, error)

CreateOrganizations creates n organizations and returns their IDs.

func (*Fixtures) CreatePullRequests

func (f *Fixtures) CreatePullRequests(repoID int64, authorIDs []int64, n int) ([]int64, error)

CreatePullRequests creates pull requests in the given repository. Cycles through authorIDs for each PR.

func (*Fixtures) CreateRepositories

func (f *Fixtures) CreateRepositories(orgID int64, n int) ([]int64, error)

CreateRepositories creates n repositories under an organization and returns their IDs.

func (*Fixtures) CreateUsers

func (f *Fixtures) CreateUsers(n int) ([]int64, error)

CreateUsers creates n users and returns their IDs.

func (*Fixtures) TupleCount

func (f *Fixtures) TupleCount() (int, error)

TupleCount returns the current count of tuples in the melange_tuples view.

type KitchenSinkScale

type KitchenSinkScale struct {
	Name            string
	Users           int
	ServiceAccounts int
	Groups          int // total groups, arranged into self-referential nesting chains
	GroupChainLen   int // nesting depth per chain (exercises self-ref userset CTE)
	Orgs            int
	MembersPerOrg   int
	TeamsPerOrg     int
	ProjectsPerOrg  int
	FolderDepth     int // folder tree depth (self-referential recursive TTU)
	FoldersPerLevel int
	DocsPerFolder   int
	PlatformAdmins  int
}

KitchenSinkScale parameterises the deterministic kitchenSink-tuple generator. The same scale always produces the same tuples (no randomness), so results are reproducible across runs and machines.

type KitchenSinkTuple

type KitchenSinkTuple struct {
	SubjectType string
	SubjectID   string
	Relation    string
	ObjectType  string
	ObjectID    string
}

KitchenSinkTuple is one authorization tuple in the kitchen-sink dataset.

func GenerateKitchenSinkTuples

func GenerateKitchenSinkTuples(s KitchenSinkScale) []KitchenSinkTuple

GenerateKitchenSinkTuples deterministically produces the tuple set for the kitchenSink schema at the given scale. It seeds every direct/linking relation so that list and check have non-trivial, overlapping results across the whole feature matrix. It does not attempt to be "semantically correct" — check_permission is the oracle in the differential test; the generator only needs varied grants.

type SaaSData

type SaaSData struct {
	DB  *sql.DB
	DSN string // for opening fresh sessions

	Staff       string // support staff: reads every production org without membership
	BigMember   string // a member of the largest org with a 7-role bundle
	PartnerUser string // a partner org member with roles over its clients, the largest org among them
	SmallMember string // a member of one small org

	BigOrg   string // the org with the most contacts
	Contact  string // objects in BigOrg
	Incident string
	Deal     string
	Invoice  string
	Document string // in the deepest folder of BigOrg's tree
}

SaaSData is a loaded SaaS database and the subjects and objects the benchmarks use.

func SetupSaaSDB

func SetupSaaSDB(tb testing.TB, s SaaSScale) *SaaSData

SetupSaaSDB returns a fresh database with the SaaS schema migrated and the scale's data loaded and analyzed.

type SaaSScale

type SaaSScale struct {
	Name              string
	Orgs              int
	Partners          int // orgs 1..Partners are partner orgs with clients
	ClientsPerPartner int // average clients per partner; each client has one partner
	UsersPerOrg       int // members per org, about 7 of 17 roles each
	Staff             int // support staff, reading every production org (35%)
	Contacts          int
	ContactOrgs       int
	DealsPerOrg       int
	QueuesPerOrg      int
	TicketsPerOrg     int
	InvoicesPerOrg    int
	EmployeesPerOrg   int
	TeamsPerOrg       int
	FoldersPerOrg     int // a ternary folder tree per org
	DocsPerOrg        int
}

SaaSScale parameterises the deterministic SaaS data generator. Most tuples are contacts, spread over ContactOrgs orgs by a Zipf distribution, so one org holds about a quarter of them and the median org a fraction of a percent. Per-org counts of the other resources vary by up to 2.5x across orgs.

func (SaaSScale) Large

func (s SaaSScale) Large() bool

Large reports whether the scale needs MELANGE_BENCH_LARGE_SCALE=1.

Jump to

Keyboard shortcuts

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