testhelpers

package
v0.310.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package testhelpers provides utilities for testing the Prometheus HTTP API. This file contains helper functions for creating test API instances and managing test lifecycles.

This file provides assertion helpers for validating API responses in tests.

This file provides test fixture data for API tests.

This file contains mock implementations of API dependencies for testing.

This file provides OpenAPI-specific test utilities for validating spec compliance.

This file provides HTTP request builders for testing API endpoints.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FixtureEmptyRuleGroups

func FixtureEmptyRuleGroups() []*rules.Group

FixtureEmptyRuleGroups returns an empty set of rule groups.

func FixtureHistogramSeries

func FixtureHistogramSeries() []storage.Series

FixtureHistogramSeries creates a series with native histogram data.

func FixtureMultipleSeries

func FixtureMultipleSeries() []storage.Series

FixtureMultipleSeries creates multiple series for testing.

func FixtureRuleGroups

func FixtureRuleGroups() []*rules.Group

FixtureRuleGroups creates a simple set of rule groups for testing.

func FixtureSeries

func FixtureSeries() []storage.Series

FixtureSeries creates a simple series with the "up" metric.

func FixtureSingleSeries

func FixtureSingleSeries(metricName string, value float64) []storage.Series

FixtureSingleSeries creates a single series for simple tests.

func NewEmptyExemplarQueryable

func NewEmptyExemplarQueryable() storage.ExemplarQueryable

NewEmptyExemplarQueryable returns an exemplar queryable with no exemplars.

func NewEmptyQueryable

func NewEmptyQueryable() storage.SampleAndChunkQueryable

NewEmptyQueryable returns a queryable with no series.

func NewQueryableWithSeries

func NewQueryableWithSeries(series []storage.Series) storage.SampleAndChunkQueryable

NewQueryableWithSeries returns a queryable with the given series.

func NewTSDBNotReadyQueryable

func NewTSDBNotReadyQueryable() storage.SampleAndChunkQueryable

NewTSDBNotReadyQueryable returns a queryable that always returns tsdb.ErrNotReady.

Types

type APIConfig

type APIConfig struct {
	// Core dependencies.
	QueryEngine       *LazyLoader[promql.QueryEngine]
	Queryable         *LazyLoader[storage.SampleAndChunkQueryable]
	ExemplarQueryable *LazyLoader[storage.ExemplarQueryable]

	// Retrievers.
	RulesRetriever        *LazyLoader[RulesRetriever]
	TargetRetriever       *LazyLoader[TargetRetriever]
	ScrapePoolsRetriever  *LazyLoader[ScrapePoolsRetriever]
	AlertmanagerRetriever *LazyLoader[AlertmanagerRetriever]

	// Admin.
	TSDBAdmin *LazyLoader[TSDBAdminStats]
	DBDir     string

	// Optional overrides.
	Config   func() config.Config
	FlagsMap map[string]string
	Now      func() time.Time
}

APIConfig holds configuration for creating a test API instance.

type APIWrapper

type APIWrapper struct {
	Handler http.Handler
}

APIWrapper wraps the API and provides a handler for testing.

type AlertmanagerRetriever

type AlertmanagerRetriever interface {
	Alertmanagers() []*url.URL
	DroppedAlertmanagers() []*url.URL
}

AlertmanagerRetriever provides a list of all/dropped AlertManager URLs.

type FakeAlertmanagerRetriever

type FakeAlertmanagerRetriever struct{}

FakeAlertmanagerRetriever implements v1.AlertmanagerRetriever.

func NewEmptyAlertmanagerRetriever

func NewEmptyAlertmanagerRetriever() *FakeAlertmanagerRetriever

NewEmptyAlertmanagerRetriever returns an alertmanager retriever with no alertmanagers.

func (*FakeAlertmanagerRetriever) Alertmanagers

func (*FakeAlertmanagerRetriever) Alertmanagers() []*url.URL

func (*FakeAlertmanagerRetriever) DroppedAlertmanagers

func (*FakeAlertmanagerRetriever) DroppedAlertmanagers() []*url.URL

type FakeChunkQuerier

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

FakeChunkQuerier implements storage.ChunkQuerier.

func (*FakeChunkQuerier) Close

func (*FakeChunkQuerier) Close() error

func (*FakeChunkQuerier) LabelNames

func (*FakeChunkQuerier) LabelValues

func (*FakeChunkQuerier) Select

type FakeChunkSeries

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

FakeChunkSeries implements storage.ChunkSeries.

func (*FakeChunkSeries) Iterator

func (*FakeChunkSeries) Labels

func (f *FakeChunkSeries) Labels() labels.Labels

type FakeChunkSeriesIterator

type FakeChunkSeriesIterator struct{}

FakeChunkSeriesIterator implements chunks.Iterator.

func (*FakeChunkSeriesIterator) At

func (*FakeChunkSeriesIterator) Err

func (*FakeChunkSeriesIterator) Next

func (*FakeChunkSeriesIterator) Next() bool

type FakeChunkSeriesSet

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

FakeChunkSeriesSet implements storage.ChunkSeriesSet.

func (*FakeChunkSeriesSet) At

func (*FakeChunkSeriesSet) Err

func (*FakeChunkSeriesSet) Err() error

func (*FakeChunkSeriesSet) Next

func (f *FakeChunkSeriesSet) Next() bool

func (*FakeChunkSeriesSet) Warnings

type FakeExemplarQuerier

type FakeExemplarQuerier struct{}

FakeExemplarQuerier implements storage.ExemplarQuerier.

func (*FakeExemplarQuerier) Select

func (*FakeExemplarQuerier) Select(_, _ int64, _ ...[]*labels.Matcher) ([]exemplar.QueryResult, error)

type FakeExemplarQueryable

type FakeExemplarQueryable struct{}

FakeExemplarQueryable implements storage.ExemplarQueryable.

func (*FakeExemplarQueryable) ExemplarQuerier

type FakeHistogramSeries

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

FakeHistogramSeries implements storage.Series for histogram data.

func (*FakeHistogramSeries) Iterator

func (*FakeHistogramSeries) Labels

func (f *FakeHistogramSeries) Labels() labels.Labels

type FakeHistogramSeriesIterator

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

FakeHistogramSeriesIterator implements chunkenc.Iterator for histogram data.

func (*FakeHistogramSeriesIterator) At

func (*FakeHistogramSeriesIterator) AtFloatHistogram

func (*FakeHistogramSeriesIterator) AtHistogram

func (*FakeHistogramSeriesIterator) AtST

func (*FakeHistogramSeriesIterator) AtT

func (*FakeHistogramSeriesIterator) Err

func (*FakeHistogramSeriesIterator) Next

func (*FakeHistogramSeriesIterator) Seek

type FakeQuerier

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

FakeQuerier implements storage.Querier.

func (*FakeQuerier) Close

func (*FakeQuerier) Close() error

func (*FakeQuerier) LabelNames

func (*FakeQuerier) LabelValues

func (*FakeQuerier) Select

type FakeQueryable

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

FakeQueryable implements storage.SampleAndChunkQueryable with configurable behavior.

func (*FakeQueryable) ChunkQuerier

func (f *FakeQueryable) ChunkQuerier(_, _ int64) (storage.ChunkQuerier, error)

func (*FakeQueryable) Querier

func (f *FakeQueryable) Querier(_, _ int64) (storage.Querier, error)

type FakeRulesRetriever

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

FakeRulesRetriever implements v1.RulesRetriever.

func NewEmptyRulesRetriever

func NewEmptyRulesRetriever() *FakeRulesRetriever

NewEmptyRulesRetriever returns a rules retriever with no rules.

func NewRulesRetrieverWithGroups

func NewRulesRetrieverWithGroups(groups []*rules.Group) *FakeRulesRetriever

NewRulesRetrieverWithGroups returns a rules retriever with the given groups.

func (*FakeRulesRetriever) AlertingRules

func (f *FakeRulesRetriever) AlertingRules() []*rules.AlertingRule

func (*FakeRulesRetriever) RuleGroups

func (f *FakeRulesRetriever) RuleGroups() []*rules.Group

type FakeScrapePoolsRetriever

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

FakeScrapePoolsRetriever implements v1.ScrapePoolsRetriever.

func NewEmptyScrapePoolsRetriever

func NewEmptyScrapePoolsRetriever() *FakeScrapePoolsRetriever

NewEmptyScrapePoolsRetriever returns a scrape pools retriever with no pools.

func (*FakeScrapePoolsRetriever) ScrapePools

func (f *FakeScrapePoolsRetriever) ScrapePools() []string

type FakeSeries

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

FakeSeries implements storage.Series.

func (*FakeSeries) Iterator

func (*FakeSeries) Labels

func (f *FakeSeries) Labels() labels.Labels

type FakeSeriesIterator

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

FakeSeriesIterator implements chunkenc.Iterator.

func (*FakeSeriesIterator) At

func (f *FakeSeriesIterator) At() (int64, float64)

func (*FakeSeriesIterator) AtFloatHistogram

func (*FakeSeriesIterator) AtHistogram

func (*FakeSeriesIterator) AtST

func (*FakeSeriesIterator) AtST() int64

func (*FakeSeriesIterator) AtT

func (f *FakeSeriesIterator) AtT() int64

func (*FakeSeriesIterator) Err

func (*FakeSeriesIterator) Err() error

func (*FakeSeriesIterator) Next

func (*FakeSeriesIterator) Seek

type FakeSeriesSet

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

FakeSeriesSet implements storage.SeriesSet.

func (*FakeSeriesSet) At

func (f *FakeSeriesSet) At() storage.Series

func (*FakeSeriesSet) Err

func (*FakeSeriesSet) Err() error

func (*FakeSeriesSet) Next

func (f *FakeSeriesSet) Next() bool

func (*FakeSeriesSet) Warnings

type FakeTSDBAdminStats

type FakeTSDBAdminStats struct{}

FakeTSDBAdminStats implements v1.TSDBAdminStats.

func NewEmptyTSDBAdminStats

func NewEmptyTSDBAdminStats() *FakeTSDBAdminStats

NewEmptyTSDBAdminStats returns a TSDB admin stats with no-op implementations.

func (*FakeTSDBAdminStats) BlockMetas

func (*FakeTSDBAdminStats) BlockMetas() ([]tsdb.BlockMeta, error)

func (*FakeTSDBAdminStats) CleanTombstones

func (*FakeTSDBAdminStats) CleanTombstones() error

func (*FakeTSDBAdminStats) Delete

func (*FakeTSDBAdminStats) Delete(_ context.Context, _, _ int64, _ ...*labels.Matcher) error

func (*FakeTSDBAdminStats) Snapshot

func (*FakeTSDBAdminStats) Snapshot(_ string, _ bool) error

func (*FakeTSDBAdminStats) Stats

func (*FakeTSDBAdminStats) Stats(_ string, _ int) (*tsdb.Stats, error)

func (*FakeTSDBAdminStats) WALReplayStatus

func (*FakeTSDBAdminStats) WALReplayStatus() (tsdb.WALReplayStatus, error)

type FakeTargetRetriever

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

FakeTargetRetriever implements v1.TargetRetriever.

func NewEmptyTargetRetriever

func NewEmptyTargetRetriever() *FakeTargetRetriever

NewEmptyTargetRetriever returns a target retriever with no targets.

func (*FakeTargetRetriever) ScrapePoolConfig

func (f *FakeTargetRetriever) ScrapePoolConfig(name string) (*config.ScrapeConfig, error)

func (*FakeTargetRetriever) TargetsActive

func (f *FakeTargetRetriever) TargetsActive() map[string][]*scrape.Target

func (*FakeTargetRetriever) TargetsDropped

func (f *FakeTargetRetriever) TargetsDropped() map[string][]*scrape.Target

func (*FakeTargetRetriever) TargetsDroppedCounts

func (f *FakeTargetRetriever) TargetsDroppedCounts() map[string]int

type LazyLoader

type LazyLoader[T any] struct {
	// contains filtered or unexported fields
}

LazyLoader allows lazy initialization of mocks per test.

func NewLazyLoader

func NewLazyLoader[T any](loader func() T) *LazyLoader[T]

NewLazyLoader creates a new LazyLoader with the given loader function.

func (*LazyLoader[T]) Get

func (l *LazyLoader[T]) Get() T

Get returns the loaded value, initializing it if necessary.

type NewAPIParams

type NewAPIParams struct {
	QueryEngine           promql.QueryEngine
	Queryable             storage.SampleAndChunkQueryable
	ExemplarQueryable     storage.ExemplarQueryable
	ScrapePoolsRetriever  func(context.Context) ScrapePoolsRetriever
	TargetRetriever       func(context.Context) TargetRetriever
	AlertmanagerRetriever func(context.Context) AlertmanagerRetriever
	ConfigFunc            func() config.Config
	FlagsMap              map[string]string
	ReadyFunc             func(http.HandlerFunc) http.HandlerFunc
	TSDBAdmin             TSDBAdminStats
	DBDir                 string
	Logger                *slog.Logger
	RulesRetriever        func(context.Context) RulesRetriever
	RuntimeInfoFunc       func() (RuntimeInfo, error)
	BuildInfo             *PrometheusVersion
	NotificationsGetter   func() []notifications.Notification
	NotificationsSub      func() (<-chan notifications.Notification, func(), bool)
	Gatherer              prometheus.Gatherer
	Registerer            prometheus.Registerer
}

NewAPIParams holds all the parameters needed to create a v1.API instance.

func PrepareAPI

func PrepareAPI(t *testing.T, cfg APIConfig) NewAPIParams

PrepareAPI creates a NewAPIParams with sensible defaults for testing.

type PrometheusVersion

type PrometheusVersion struct {
	Version   string `json:"version"`
	Revision  string `json:"revision"`
	Branch    string `json:"branch"`
	BuildUser string `json:"buildUser"`
	BuildDate string `json:"buildDate"`
	GoVersion string `json:"goVersion"`
}

PrometheusVersion contains build information about Prometheus.

type Response

type Response struct {
	StatusCode int
	Body       string
	JSON       map[string]any
	// contains filtered or unexported fields
}

Response wraps an HTTP response with parsed JSON data. It supports method chaining for assertions.

Example usage:

testhelpers.GET(t, api, "/api/v1/query", "query", "up").
	ValidateOpenAPI().
	RequireSuccess().
	RequireEquals("$.data.resultType", "vector").
	RequireLenAtLeast("$.data.result", 1)

testhelpers.POST(t, api, "/api/v1/query", "query", "up").
	ValidateOpenAPI().
	RequireSuccess().
	RequireArrayContains("$.data.result", expectedValue)

func GET

func GET(t *testing.T, api *APIWrapper, path string, queryParams ...string) *Response

GET sends a GET request to the API and returns a Response with parsed JSON. queryParams should be pairs of key-value strings.

func POST

func POST(t *testing.T, api *APIWrapper, path string, bodyParams ...string) *Response

POST sends a POST request to the API with the given body and returns a Response with parsed JSON. bodyParams should be pairs of key-value strings for form data.

func (*Response) DebugJSON

func (r *Response) DebugJSON() *Response

DebugJSON is a helper for debugging JSON responses in tests.

func (*Response) RequireArrayContains

func (r *Response) RequireArrayContains(path string, expected any) *Response

RequireArrayContains asserts that a JSON path contains an array with the expected element and returns the response for chaining.

func (*Response) RequireContainsSubstring

func (r *Response) RequireContainsSubstring(substring string) *Response

RequireContainsSubstring asserts that the response body contains the given substring.

func (*Response) RequireEquals

func (r *Response) RequireEquals(path string, expected any) *Response

RequireEquals asserts that a JSON path equals the expected value and returns the response for chaining.

func (*Response) RequireError

func (r *Response) RequireError() *Response

RequireError asserts that the response has status "error" and returns the response for chaining.

func (*Response) RequireField

func (r *Response) RequireField(path string) any

RequireField asserts that a field exists at the given path and returns its value. Note: This method cannot be chained further since it returns the field value, not the Response.

func (*Response) RequireFieldType

func (r *Response) RequireFieldType(path, expectedType string) *Response

RequireFieldType asserts that a field exists and has the expected type.

func (*Response) RequireJSONArray

func (r *Response) RequireJSONArray(path string) *Response

RequireJSONArray asserts that a JSON path contains an array and returns the response for chaining.

func (*Response) RequireJSONPathExists

func (r *Response) RequireJSONPathExists(path string) *Response

RequireJSONPathExists asserts that a JSON path exists and returns the response for chaining.

func (*Response) RequireJSONPathNotExists

func (r *Response) RequireJSONPathNotExists(path string) *Response

RequireJSONPathNotExists asserts that a JSON path does not exist and returns the response for chaining.

func (*Response) RequireLenAtLeast

func (r *Response) RequireLenAtLeast(path string, minLen int) *Response

RequireLenAtLeast asserts that a JSON path contains an array with at least minLen elements and returns the response for chaining.

func (*Response) RequireMatrixResult

func (r *Response) RequireMatrixResult() *Response

RequireMatrixResult is a convenience helper for checking matrix query results.

func (*Response) RequireRulesGroupNamed

func (r *Response) RequireRulesGroupNamed(name string) *Response

RequireRulesGroupNamed asserts that a rules response contains a group with the given name.

func (*Response) RequireScalarResult

func (r *Response) RequireScalarResult() *Response

RequireScalarResult is a convenience helper for checking scalar query results.

func (*Response) RequireSome

func (r *Response) RequireSome(path string, predicate func(any) bool) *Response

RequireSome asserts that at least one element in an array satisfies the predicate and returns the response for chaining.

func (*Response) RequireStatusCode

func (r *Response) RequireStatusCode(expectedCode int) *Response

RequireStatusCode asserts that the response has the given HTTP status code and returns the response for chaining.

func (*Response) RequireSuccess

func (r *Response) RequireSuccess() *Response

RequireSuccess asserts that the response has status "success" and returns the response for chaining.

func (*Response) RequireTargetCount

func (r *Response) RequireTargetCount(minCount int) *Response

RequireTargetCount asserts that a targets response contains at least n targets.

func (*Response) RequireVectorResult

func (r *Response) RequireVectorResult() *Response

RequireVectorResult is a convenience helper for checking vector query results.

func (*Response) ValidateOpenAPI

func (r *Response) ValidateOpenAPI() *Response

ValidateOpenAPI validates the request and response against both OpenAPI 3.1 and 3.2 specifications. This ensures API endpoints are compatible with both OpenAPI versions. Returns the response for chaining.

type RulesRetriever

type RulesRetriever interface {
	RuleGroups() []*rules.Group
	AlertingRules() []*rules.AlertingRule
}

RulesRetriever provides a list of active rules and alerts.

type RuntimeInfo

type RuntimeInfo struct {
	StartTime           time.Time `json:"startTime"`
	CWD                 string    `json:"CWD"`
	Hostname            string    `json:"hostname"`
	ServerTime          time.Time `json:"serverTime"`
	ReloadConfigSuccess bool      `json:"reloadConfigSuccess"`
	LastConfigTime      time.Time `json:"lastConfigTime"`
	CorruptionCount     int64     `json:"corruptionCount"`
	GoroutineCount      int       `json:"goroutineCount"`
	GOMAXPROCS          int       `json:"GOMAXPROCS"`
	GOMEMLIMIT          int64     `json:"GOMEMLIMIT"`
	GOGC                string    `json:"GOGC"`
	GODEBUG             string    `json:"GODEBUG"`
	StorageRetention    string    `json:"storageRetention"`
}

RuntimeInfo contains runtime information about Prometheus.

type ScrapePoolsRetriever

type ScrapePoolsRetriever interface {
	ScrapePools() []string
}

ScrapePoolsRetriever provide the list of all scrape pools.

type TSDBAdminStats

type TSDBAdminStats interface {
	CleanTombstones() error
	Delete(ctx context.Context, mint, maxt int64, ms ...*labels.Matcher) error
	Snapshot(dir string, withHead bool) error
	Stats(statsByLabelName string, limit int) (*tsdb.Stats, error)
	WALReplayStatus() (tsdb.WALReplayStatus, error)
	BlockMetas() ([]tsdb.BlockMeta, error)
}

TSDBAdminStats provides TSDB admin statistics.

type TSDBNotReadyQueryable

type TSDBNotReadyQueryable struct{}

TSDBNotReadyQueryable implements storage.SampleAndChunkQueryable that returns tsdb.ErrNotReady.

func (*TSDBNotReadyQueryable) ChunkQuerier

func (*TSDBNotReadyQueryable) ChunkQuerier(_, _ int64) (storage.ChunkQuerier, error)

func (*TSDBNotReadyQueryable) Querier

func (*TSDBNotReadyQueryable) Querier(_, _ int64) (storage.Querier, error)

type TargetRetriever

type TargetRetriever interface {
	TargetsActive() map[string][]*scrape.Target
	TargetsDropped() map[string][]*scrape.Target
	TargetsDroppedCounts() map[string]int
	ScrapePoolConfig(string) (*config.ScrapeConfig, error)
}

TargetRetriever provides the list of active/dropped targets to scrape or not.

Jump to

Keyboard shortcuts

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