testenv

package
v0.0.0-...-50c4096 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2025 License: Apache-2.0 Imports: 59 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//go:embed testdata/config.json
	ConfigJSONTemplate string
	//go:embed testdata/configWithEdfs.json
	ConfigWithEdfsJSONTemplate string
	//go:embed testdata/configWithEdfsKafka.json
	ConfigWithEdfsKafkaJSONTemplate string
	//go:embed testdata/configWithEdfsNats.json
	ConfigWithEdfsNatsJSONTemplate string
)
View Source
var ErrEnvironmentClosed = errors.New("test environment closed")

Functions

func Bench

func Bench(b *testing.B, cfg *Config, f func(b *testing.B, xEnv *Environment))

func FailsOnStartup

func FailsOnStartup(t *testing.T, cfg *Config, f func(t *testing.T, err error))

FailsOnStartup runs the test and ensures that the router fails during bootstrapping

func GenerateVersionedJwtToken

func GenerateVersionedJwtToken() (string, error)

func GetPubSubNameFn

func GetPubSubNameFn(prefix string) func(name string) string

func RandString

func RandString(n int) string

func Run

func Run(t *testing.T, cfg *Config, f func(t *testing.T, xEnv *Environment))

Run runs the test and fails the test if an error occurs

func RunRouterBinary

func RunRouterBinary(t *testing.T, cfg *Config, f func(t *testing.T, xEnv *Environment))

RunRouterBinary starts the router binary, sets up the test environment, and runs the provided test function.

func RunWithError

func RunWithError(t *testing.T, cfg *Config, f func(t *testing.T, xEnv *Environment)) error

RunWithError runs the test but returns an error instead of failing the test Useful when you want to assert errors during router bootstrapping

func SetupCDNServer

func SetupCDNServer(t testing.TB, port int) *httptest.Server

func WSReadJSON

func WSReadJSON(t testing.TB, conn *websocket.Conn, v interface{}) (err error)

func WSReadMessage

func WSReadMessage(t testing.TB, conn *websocket.Conn) (messageType int, p []byte, err error)

func WSWriteJSON

func WSWriteJSON(t testing.TB, conn *websocket.Conn, v interface{}) (err error)

func WSWriteMessage

func WSWriteMessage(t testing.TB, conn *websocket.Conn, messageType int, data []byte) (err error)

Types

type CacheMetricsAssertion

type CacheMetricsAssertion struct {
	QueryNormalizationMisses          int64
	QueryNormalizationHits            int64
	PersistedQueryNormalizationMisses int64
	PersistedQueryNormalizationHits   int64
	ValidationMisses                  int64
	ValidationHits                    int64
	PlanMisses                        int64
	PlanHits                          int64
	QueryHashMisses                   int64
	QueryHashHits                     int64
}

type CacheMetricsAssertions

type CacheMetricsAssertions struct {
	BaseGraphAssertions   CacheMetricsAssertion
	FeatureFlagAssertions map[string]CacheMetricsAssertion
}

type Config

type Config struct {
	Subgraphs                          SubgraphsConfig
	RouterConfig                       *RouterConfig
	RouterOptions                      []core.Option
	OverrideGraphQLPath                string
	OverrideAbsinthePath               string
	RouterConfigJSONTemplate           string
	ModifyRouterConfig                 func(routerConfig *nodev1.RouterConfig)
	ModifyEngineExecutionConfiguration func(engineExecutionConfiguration *config.EngineExecutionConfiguration)
	ModifySecurityConfiguration        func(securityConfiguration *config.SecurityConfiguration)
	ModifySubgraphErrorPropagation     func(subgraphErrorPropagation *config.SubgraphErrorPropagationConfiguration)
	ModifyWebsocketConfiguration       func(websocketConfiguration *config.WebSocketConfiguration)
	ModifyCDNConfig                    func(cdnConfig *config.CDNConfiguration)
	KafkaSeeds                         []string
	DisableWebSockets                  bool
	DisableParentBasedSampler          bool
	TLSConfig                          *core.TlsConfig
	TraceExporter                      trace.SpanExporter
	CustomMetricAttributes             []config.CustomAttribute
	CustomTelemetryAttributes          []config.CustomAttribute
	CustomResourceAttributes           []config.CustomStaticAttribute
	MetricReader                       metric.Reader
	PrometheusRegistry                 *prometheus.Registry
	PrometheusPort                     int
	ShutdownDelay                      time.Duration
	NoRetryClient                      bool
	PropagationConfig                  config.PropagationConfig
	CacheControlPolicy                 config.CacheControlPolicy
	ApqConfig                          config.AutomaticPersistedQueriesConfig
	LogObservation                     LogObservationConfig
	ClientHeader                       config.ClientHeader
	ResponseTraceHeader                config.ResponseTraceHeader
	Logger                             *zap.Logger
	AccessLogger                       *zap.Logger
	AccessLogFields                    []config.CustomAttribute
	MetricOptions                      MetricOptions
	ModifyEventsConfiguration          func(cfg *config.EventsConfiguration)
	EnableRuntimeMetrics               bool
	EnableNats                         bool
	EnableKafka                        bool
	SubgraphAccessLogsEnabled          bool
	SubgraphAccessLogFields            []config.CustomAttribute
	AssertCacheMetrics                 *CacheMetricsAssertions
	DisableSimulateCloudExporter       bool
	CdnSever                           *httptest.Server
	UseVersionedGraph                  bool
}

type EngineStatOptions

type EngineStatOptions struct {
	EnableSubscription bool
}

type EngineStatisticAssertion

type EngineStatisticAssertion struct {
	Subscriptions int64
	Connections   int64
	MessagesSent  int64
	Triggers      int64
}

type Environment

type Environment struct {
	Context context.Context

	Router                *core.Router
	RouterURL             string
	RouterClient          *http.Client
	Servers               []*httptest.Server
	CDN                   *httptest.Server
	NatsData              *NatsData
	NatsConnectionDefault *nats.Conn
	NatsConnectionMyNats  *nats.Conn
	SubgraphRequestCount  *SubgraphRequestCount
	KafkaAdminClient      *kadm.Client
	KafkaClient           *kgo.Client
	// contains filtered or unexported fields
}

func (*Environment) AbsintheSubscriptionURL

func (e *Environment) AbsintheSubscriptionURL() string

func (*Environment) AbsintheWebsocketDialWithRetry

func (e *Environment) AbsintheWebsocketDialWithRetry(header http.Header) (*websocket.Conn, *http.Response, error)

func (*Environment) AssertEngineStatistics

func (e *Environment) AssertEngineStatistics(t testing.TB, metricReader metric.Reader, assertions EngineStatisticAssertion)

func (*Environment) GetPubSubName

func (e *Environment) GetPubSubName(name string) string

GetPubSubName returns the name of a PubSub entity (subject, topic, subscription, etc.) unique for this test environment. Using this method avoid conflicts between tests running in parallel.

func (*Environment) GraphQLRequestURL

func (e *Environment) GraphQLRequestURL() string

func (*Environment) GraphQLServeSentEventsURL

func (e *Environment) GraphQLServeSentEventsURL() string

func (*Environment) GraphQLSubscriptionOverSSE

func (e *Environment) GraphQLSubscriptionOverSSE(ctx context.Context, request GraphQLRequest, handler func(data string))

func (*Environment) GraphQLSubscriptionOverSSEWithQueryParam

func (e *Environment) GraphQLSubscriptionOverSSEWithQueryParam(ctx context.Context, request GraphQLRequest, handler func(data string))

func (*Environment) GraphQLWebSocketSubscriptionURL

func (e *Environment) GraphQLWebSocketSubscriptionURL() string

func (*Environment) GraphQLWebsocketDialWithRetry

func (e *Environment) GraphQLWebsocketDialWithRetry(header http.Header, query url.Values) (*websocket.Conn, *http.Response, error)

func (*Environment) InitAbsintheWebSocketConnection

func (e *Environment) InitAbsintheWebSocketConnection(header http.Header, initialPayload json.RawMessage) *websocket.Conn

func (*Environment) InitGraphQLWebSocketConnection

func (e *Environment) InitGraphQLWebSocketConnection(header http.Header, query url.Values, initialPayload json.RawMessage) *websocket.Conn

func (*Environment) MakeGraphQLMultipartRequest

func (e *Environment) MakeGraphQLMultipartRequest(method string, body io.Reader) *http.Request

func (*Environment) MakeGraphQLRequest

func (e *Environment) MakeGraphQLRequest(request GraphQLRequest) (*TestResponse, error)

func (*Environment) MakeGraphQLRequestAsMultipartForm

func (e *Environment) MakeGraphQLRequestAsMultipartForm(request GraphQLRequest) (*TestResponse, error)

func (*Environment) MakeGraphQLRequestOK

func (e *Environment) MakeGraphQLRequestOK(request GraphQLRequest) *TestResponse

func (*Environment) MakeGraphQLRequestOverGET

func (e *Environment) MakeGraphQLRequestOverGET(request GraphQLRequest) (*TestResponse, error)

func (*Environment) MakeGraphQLRequestRaw

func (e *Environment) MakeGraphQLRequestRaw(request *http.Request) (*TestResponse, error)

func (*Environment) MakeGraphQLRequestWithContext

func (e *Environment) MakeGraphQLRequestWithContext(ctx context.Context, request GraphQLRequest) (*TestResponse, error)

func (*Environment) MakeGraphQLRequestWithHeaders

func (e *Environment) MakeGraphQLRequestWithHeaders(request GraphQLRequest, headers map[string]string) (*TestResponse, error)

func (*Environment) MakeRequest

func (e *Environment) MakeRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error)

func (*Environment) Observer

func (e *Environment) Observer() *observer.ObservedLogs

func (*Environment) ReadSSE

func (e *Environment) ReadSSE(ctx context.Context, body io.ReadCloser, handler func(data string))

func (*Environment) RouterConfigVersionMain

func (e *Environment) RouterConfigVersionMain() string

func (*Environment) RouterConfigVersionMyFF

func (e *Environment) RouterConfigVersionMyFF() string

func (*Environment) SetExtraURLQueryValues

func (e *Environment) SetExtraURLQueryValues(values url.Values)

func (*Environment) Shutdown

func (e *Environment) Shutdown()

Shutdown closes all resources associated with the test environment. Can be called multiple times but will only shut down resources once.

func (*Environment) WaitForConnectionCount

func (e *Environment) WaitForConnectionCount(desiredCount uint64, timeout time.Duration)

func (*Environment) WaitForMessagesSent

func (e *Environment) WaitForMessagesSent(desiredCount uint64, timeout time.Duration)

func (*Environment) WaitForMinMessagesSent

func (e *Environment) WaitForMinMessagesSent(minCount uint64, timeout time.Duration)

func (*Environment) WaitForServer

func (e *Environment) WaitForServer(ctx context.Context, url string, timeoutMs int, maxAttempts int) error

func (*Environment) WaitForSubscriptionCount

func (e *Environment) WaitForSubscriptionCount(desiredCount uint64, timeout time.Duration)

func (*Environment) WaitForTriggerCount

func (e *Environment) WaitForTriggerCount(desiredCount uint64, timeout time.Duration)

type FileUpload

type FileUpload struct {
	VariablesPath string
	FileContent   []byte
}

type GraphQLError

type GraphQLError struct {
	Message    string                 `json:"message"`
	Path       []any                  `json:"path,omitempty"`
	Extensions GraphQLErrorExtensions `json:"extensions,omitempty"`
}

type GraphQLErrorExtensions

type GraphQLErrorExtensions struct {
	Code        string         `json:"code"`
	StatusCode  int            `json:"statusCode"`
	ServiceName string         `json:"serviceName"`
	Errors      []GraphQLError `json:"errors"`
}

type GraphQLRequest

type GraphQLRequest struct {
	Query         string          `json:"query"`
	Variables     json.RawMessage `json:"variables,omitempty"`
	Extensions    json.RawMessage `json:"extensions,omitempty"`
	OperationName json.RawMessage `json:"operationName,omitempty"`
	Header        http.Header     `json:"-"`
	Files         []FileUpload    `json:"-"`
	Cookies       []*http.Cookie  `json:"-"`
}

type GraphQLResponse

type GraphQLResponse struct {
	Data   json.RawMessage `json:"data,omitempty"`
	Errors []GraphQLError  `json:"errors,omitempty"`
}

type KafkaData

type KafkaData struct {
	Client   *kgo.Client
	Brokers  []string
	Resource *dockertest.Resource
}

type LogObservationConfig

type LogObservationConfig struct {
	Enabled  bool
	LogLevel zapcore.Level
}

type MetricExclusions

type MetricExclusions struct {
	ExcludedPrometheusMetrics      []*regexp.Regexp
	ExcludedPrometheusMetricLabels []*regexp.Regexp
	ExcludedOTLPMetrics            []*regexp.Regexp
	ExcludedOTLPMetricLabels       []*regexp.Regexp
	ExcludeScopeInfo               bool
}

type MetricOptions

type MetricOptions struct {
	MetricExclusions             MetricExclusions
	EnableRuntimeMetrics         bool
	EnableOTLPRouterCache        bool
	EnablePrometheusRouterCache  bool
	OTLPEngineStatsOptions       EngineStatOptions
	PrometheusEngineStatsOptions EngineStatOptions
}

type NatsData

type NatsData struct {
	Connections []*nats.Conn
}

type RouterConfig

type RouterConfig struct {
	StaticConfig        *nodev1.RouterConfig
	ConfigPollerFactory func(config *nodev1.RouterConfig) configpoller.ConfigPoller
}

type Subgraph

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

func (*Subgraph) ServeHTTP

func (s *Subgraph) ServeHTTP(w http.ResponseWriter, r *http.Request)

type SubgraphConfig

type SubgraphConfig struct {
	Middleware   func(http.Handler) http.Handler
	Delay        time.Duration
	CloseOnStart bool
}

type SubgraphRequestCount

type SubgraphRequestCount struct {
	Global       *atomic.Int64
	Employees    *atomic.Int64
	Family       *atomic.Int64
	Hobbies      *atomic.Int64
	Products     *atomic.Int64
	ProductFg    *atomic.Int64
	Test1        *atomic.Int64
	Availability *atomic.Int64
	Mood         *atomic.Int64
	Countries    *atomic.Int64
}

type SubgraphsConfig

type SubgraphsConfig struct {
	GlobalMiddleware func(http.Handler) http.Handler
	GlobalDelay      time.Duration
	Employees        SubgraphConfig
	Family           SubgraphConfig
	Hobbies          SubgraphConfig
	Products         SubgraphConfig
	ProductsFg       SubgraphConfig
	Test1            SubgraphConfig
	Availability     SubgraphConfig
	Mood             SubgraphConfig
	Countries        SubgraphConfig
}

type TestResponse

type TestResponse struct {
	Body     string
	Response *http.Response
	Proto    string
}

type WebSocketMessage

type WebSocketMessage struct {
	ID      string          `json:"id,omitempty"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

Jump to

Keyboard shortcuts

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