test

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (

	//nolint:revive // represents the default certificate's names.
	PrivateKey       = "private-key.pem"
	PublicKey        = "public-key.pem"
	CACertificateKey = "ca-certificate.pem"
)
View Source
const DockerNamesPrefix = "sc_test"

DockerNamesPrefix is the prefix for test-containers name.

Variables

View Source
var (
	// InsecureTLSConfig defines an empty tls config.
	InsecureTLSConfig connection.TLSConfig

	// OrgRootCA is the path to organization 0's TLS client credentials in the crypto materials directory.
	OrgRootCA = filepath.Join(cryptogen.PeerOrganizationsDir, "peer-org-0.com",
		cryptogen.MSPDir, cryptogen.TLSCaCertsDir, "tlspeer-org-0-CA-cert.pem")

	// OrdererRootCATLSPath is the path to organization 0's orderer TLS credentials in the crypto materials directory.
	OrdererRootCATLSPath = filepath.Join(cryptogen.OrdererOrganizationsDir,
		"orderer-org-0.com", cryptogen.MSPDir, cryptogen.TLSCaCertsDir, "tlsorderer-org-0-CA-cert.pem")
)

ServerModes is a list of server-side TLS modes used for testing.

Functions

func CheckMetrics

func CheckMetrics(t *testing.T, url string, tlsConfig *tls.Config, expectedMetrics ...string)

CheckMetrics checks the metrics endpoint for the expected metrics.

func CheckServerStopped

func CheckServerStopped(t *testing.T, addr string) bool

CheckServerStopped returns true if the grpc server listening on a given address has been stopped.

func CreateClientWithTLS added in v0.1.7

func CreateClientWithTLS[T any](
	t *testing.T,
	endpoint *connection.Endpoint,
	tlsCfg connection.TLSConfig,
	protoClient func(grpc.ClientConnInterface) T,
) T

CreateClientWithTLS creates and returns a typed gRPC client using the provided TLS configuration. It establishes a secure connection to the given endpoint and returns the generated client using the provided client creation proto function.

func CreateDockerNetwork added in v0.1.7

func CreateDockerNetwork(t *testing.T, name string) *docker.Network

CreateDockerNetwork creates a network if it doesn't exist.

func CreateServerAndClientTLSConfig added in v0.1.7

func CreateServerAndClientTLSConfig(t *testing.T, tlsMode string) (
	serverTLSConfig, clientTLSConfig connection.TLSConfig,
)

CreateServerAndClientTLSConfig creates server and client TLS configurations given a TLS mode.

func EventuallyIntMetric

func EventuallyIntMetric(
	t *testing.T, expected int, m prometheus.Metric, waitFor, tick time.Duration, msgAndArgs ...any,
)

EventuallyIntMetric fail the test if the integer metric is not equal to the expected value after the given duration.

func GetCounterOrGaugeValueFromURL added in v1.0.5

func GetCounterOrGaugeValueFromURL(t TestingT, params GetMetricValueParameters) int

GetCounterOrGaugeValueFromURL reads the metrics endpoint and returns the scalar value of the counter/gauge/untyped series named params.MetricName carrying params.Labels, rounded to the nearest integer. It returns 0 for an absent family and for a labeled series not exported yet (a "...Vec" series is absent until its first observation, so a pre-traffic baseline read returns 0). Reading a histogram/summary this way also returns 0 -- use GetHistogramCountAndSumValueFromURL.

func GetDockerClient added in v0.1.7

func GetDockerClient(t *testing.T) *docker.Client

GetDockerClient instantiate a new docker client.

func GetHistogramCountAndSumValueFromURL added in v1.0.5

func GetHistogramCountAndSumValueFromURL(t TestingT, params GetMetricValueParameters) (count uint64, sum float64)

GetHistogramCountAndSumValueFromURL reads the metrics endpoint and returns the observation count and the sum of the histogram named params.MetricName carrying params.Labels. Pass the histogram's base name, not its "_count" child. Absent-family and not-yet-observed reads return 0; a non-histogram family also reads as 0.

func GetIntMetricValue

func GetIntMetricValue(t TestingT, m prometheus.Metric) int

GetIntMetricValue returns the value of a prometheus metric, rounded to the nearest integer.

func GetMetricValue

func GetMetricValue(t TestingT, m prometheus.Metric) float64

GetMetricValue returns the value of a prometheus metric.

func GrpcServiceToConnectionServerConfigs added in v1.0.0

func GrpcServiceToConnectionServerConfigs(servers ...*serve.Config) []*serve.ServerConfig

GrpcServiceToConnectionServerConfigs extracts gRPC server endpoints from serve configs.

func LogStruct added in v0.1.6

func LogStruct(t *testing.T, name string, v any)

LogStruct logs a struct in a flat representation.

func Make added in v0.1.9

func Make(rules ...string) error

Make runs a make command with the specified rules.

func MustGetTLSConfig added in v0.1.9

func MustGetTLSConfig(t *testing.T, tlsConfig *connection.TLSConfig) *tls.Config

MustGetTLSConfig creates a tls.Config from a connection.TLSConfig while ensuring no error return from that process.

func NewEndpoint added in v0.2.0

func NewEndpoint(t *testing.T, host, port string) *connection.Endpoint

NewEndpoint creates an endpoint from give host and port (as string).

func NewInsecureClientConfig added in v0.1.7

func NewInsecureClientConfig(ep *connection.Endpoint) *connection.ClientConfig

NewInsecureClientConfig creates a client configuration for test purposes given an endpoint.

func NewInsecureConnection added in v0.1.7

func NewInsecureConnection(tb testing.TB, endpoint connection.WithAddress) *grpc.ClientConn

NewInsecureConnection creates the default connection with insecure credentials.

func NewInsecureConnectionWithRetry added in v0.1.7

func NewInsecureConnectionWithRetry(
	tb testing.TB, endpoint connection.WithAddress, retryProfile retry.Profile,
) *grpc.ClientConn

NewInsecureConnectionWithRetry creates the default dial config with insecure credentials.

func NewInsecureLoadBalancedConnection added in v0.1.7

func NewInsecureLoadBalancedConnection(t *testing.T, endpoints []*connection.Endpoint) *grpc.ClientConn

NewInsecureLoadBalancedConnection creates the default connection with insecure credentials.

func NewLocalHostServer added in v0.2.0

func NewLocalHostServer(creds connection.TLSConfig) *serve.ServerConfig

NewLocalHostServer returns a default server config with endpoint "localhost:0" given server credentials.

func NewLocalHostServiceConfig added in v1.0.0

func NewLocalHostServiceConfig(creds connection.TLSConfig) *serve.Config

NewLocalHostServiceConfig returns a grpcservice.ServerConfig with both gRPC and monitoring endpoints. Both endpoints use "localhost:0" (auto-assigned ports) with the given TLS credentials.

func NewPreAllocatedLocalHostServerConfig added in v1.0.0

func NewPreAllocatedLocalHostServerConfig(t *testing.T, tlsConfig connection.TLSConfig) *serve.Config

NewPreAllocatedLocalHostServerConfig create a localhost server config with a pre allocated listener and port.

func NewSecuredConnection added in v0.1.7

func NewSecuredConnection(
	t *testing.T,
	endpoint connection.WithAddress,
	tlsConfig connection.TLSConfig,
) *grpc.ClientConn

NewSecuredConnection creates the default connection with given transport credentials.

func NewSecuredConnectionWithRetry added in v0.1.7

func NewSecuredConnectionWithRetry(
	t *testing.T,
	endpoint connection.WithAddress,
	tlsConfig connection.TLSConfig,
	retryProfile retry.Profile,
) *grpc.ClientConn

NewSecuredConnectionWithRetry creates the default connection with given transport credentials.

func NewServiceTLSConfig added in v0.2.0

func NewServiceTLSConfig(artifactsPath, serviceName, mode string) connection.TLSConfig

NewServiceTLSConfig creates a server TLS configuration with certificates loaded from the artifact path. This function constructs paths to TLS certificates for a given service within the peer organization structure.

func NewTLSClientConfig added in v0.1.7

func NewTLSClientConfig(tlsConfig connection.TLSConfig, ep *connection.Endpoint) *connection.ClientConfig

NewTLSClientConfig creates a client configuration for test purposes given a single endpoint and creds.

func NewTLSMultiClientConfig added in v0.1.7

func NewTLSMultiClientConfig(
	tlsConfig connection.TLSConfig,
	ep ...*connection.Endpoint,
) *connection.MultiClientConfig

NewTLSMultiClientConfig creates a multi client configuration for test purposes given number of endpoints and a TLS configuration.

func OrgClientTLSConfig added in v1.0.0

func OrgClientTLSConfig(artifactsPath string, orgIndex int, serverCACertPaths []string) connection.TLSConfig

OrgClientTLSConfig creates a mutual TLS client configuration using a specific peer organization's TLS client certificate. The serverCACertPaths are the CA certs needed to verify the server (typically from the CredentialsFactory).

func RemoveDockerNetwork added in v0.1.7

func RemoveDockerNetwork(t *testing.T, name string)

RemoveDockerNetwork removes a Docker network by name.

func ReportTxPerSecond added in v1.0.5

func ReportTxPerSecond(b *testing.B)

ReportTxPerSecond reports a tx/s custom metric on the benchmark, using b.N as the number of transactions processed. Benchmarks that batch work (e.g., into blocks) should still size b.N in transactions so that both ns/op and tx/s are reported per transaction.

func RequireConnectionMetrics added in v1.0.5

func RequireConnectionMetrics(
	t *testing.T,
	label string,
	connMetrics *monitoring.ConnectionMetrics,
	expected ExpectedConn,
)

RequireConnectionMetrics waits for a connection status and a specified number of failures.

func RequireIntMetricValue

func RequireIntMetricValue(t *testing.T, expected int, m prometheus.Metric)

RequireIntMetricValue fail the test if the integer metric is not equal to the expected value.

func RequireProtoElementsMatch

func RequireProtoElementsMatch[T proto.Message](
	t TestingT, expected, actual []T, msgAndArgs ...any,
)

RequireProtoElementsMatch verifies that two arrays of proto have the same elements.

func RequireProtoEqual

func RequireProtoEqual(t TestingT, expected, actual proto.Message)

RequireProtoEqual verifies that two proto are equal.

func RunSecureConnectionTest added in v0.1.7

func RunSecureConnectionTest(t *testing.T, starter ServerStarter)

RunSecureConnectionTest starts a gRPC server with mTLS enabled and tests client connections using various TLS configurations to verify that the server correctly accepts or rejects connections based on the client's setup. It runs a server instance of the service and returns a function that starts a client with the required TLS mode, attempts an RPC call, and returns the resulting error. Server Mode | Client with mTLS | Client with server-side TLS | Client with no TLS ------------|------------------|-----------------------------|-------------------- mTLS | connect | can't connect | can't connect TLS | connect | connect | can't connect None | can't connect | can't connect | connect.

func RunServiceAndServeForTest added in v1.0.0

func RunServiceAndServeForTest(
	ctx context.Context,
	tb testing.TB,
	service serve.Service,
	serverConfig ...*serve.Config,
) *channel.Ready

RunServiceAndServeForTest combines running a service and its GRPC server. It is intended for services that implements the Service API (i.e., command line services).

func RunServiceForTest

func RunServiceForTest(
	ctx context.Context,
	tb testing.TB,
	service func(ctx context.Context) error,
	waitFunc func(ctx context.Context) bool,
) *channel.Ready

RunServiceForTest runs a service using the given service method, and waits for it to be ready given the waitFunc method. It handles the cleanup of the service at the end of a test, and ensure the test is ended only when the service return. The method asserts that the service did not end with failure. Returns a ready flag that indicate that the service is done.

func ServeForTest added in v1.0.0

func ServeForTest(
	ctx context.Context, tb testing.TB, sc *serve.Config, registerer serve.Registerer,
) (stop context.CancelFunc)

ServeForTest starts a GRPC server and optionally a monitoring server using a register method. It handles the cleanup of the servers at the end of a test, and ensure the test is ended only when the servers are down. It also updates the server config endpoint port to the actual port if the configuration did not specify a port. The method asserts that the servers did not end with failure.

func ServerToMultiClientConfig added in v0.1.7

func ServerToMultiClientConfig(
	clientTLS connection.TLSConfig, servers ...*serve.Config,
) *connection.MultiClientConfig

ServerToMultiClientConfig is used to create a multi client configuration from existing server(s) given a client TLS configuration.

func WaitForConnections added in v1.0.5

func WaitForConnections(t *testing.T, p *monitoring.Provider, name string, requiredCount int)

WaitForConnections waits for a connection metric to have the required number of connected labels.

Types

type CredentialsFactory added in v0.1.7

type CredentialsFactory struct {
	CertificateAuthority tlsgen.CA
}

CredentialsFactory responsible for the creation of TLS certificates inside a TLSConfig for testing purposes by using the tls generation library of 'Hyperledger Fabric'.

func NewCredentialsFactory added in v0.1.7

func NewCredentialsFactory(t *testing.T) *CredentialsFactory

NewCredentialsFactory returns a CredentialsFactory with a new CA.

func (*CredentialsFactory) CreateClientCredentials added in v0.1.7

func (scm *CredentialsFactory) CreateClientCredentials(t *testing.T, tlsMode string) (connection.TLSConfig, string)

CreateClientCredentials creates a client key pair, Writing it to a temp testing folder and returns a connection.TLSConfig.

func (*CredentialsFactory) CreateServerCredentials added in v0.1.7

func (scm *CredentialsFactory) CreateServerCredentials(
	t *testing.T,
	tlsMode string,
	san ...string,
) (connection.TLSConfig, string)

CreateServerCredentials creates a server key pair given SAN(s) (Subject Alternative Name), Writing it to a temp testing folder and returns a connection.TLSConfig.

type ExpectedConn added in v1.0.5

type ExpectedConn struct {
	Status       int
	FailureTotal int
}

ExpectedConn is used to describe the expected connection state.

type GetMetricValueParameters added in v1.0.5

type GetMetricValueParameters struct {
	MetricsConnectionParameters
	MetricName string
	Labels     map[string]string
}

GetMetricValueParameters carries the parameters for the metric-value lookups (GetCounterOrGaugeValueFromURL, GetHistogramCountAndSumValueFromURL).

type HealthService added in v1.0.0

type HealthService struct {
	healthgrpc.HealthServer
}

HealthService is a test helper that implements grpcservice.Registerer and provides a default health check service for gRPC servers in tests.

func (*HealthService) RegisterService added in v1.0.0

func (h *HealthService) RegisterService(s serve.Servers)

RegisterService registers the health check service with the gRPC server. This implements the grpcservice.Registerer interface.

type MetricsConnectionParameters added in v1.0.5

type MetricsConnectionParameters struct {
	URL       string
	TLSConfig *tls.Config
}

MetricsConnectionParameters carries the scrape URL and client TLS config for a service's HTTP metrics endpoint.

func NewMetricsConnectionParameters added in v1.0.5

func NewMetricsConnectionParameters(
	t *testing.T, clientTLS connection.TLSConfig, httpEndpoint *connection.Endpoint,
) MetricsConnectionParameters

NewMetricsConnectionParameters builds a handle for scraping the given service's HTTP metrics endpoint.

type Process added in v1.0.0

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

Process represents a managed external process with lifecycle control. This is a simple, test-friendly wrapper around os/exec.Cmd.

func NewProcess added in v1.0.0

func NewProcess(cmd *exec.Cmd, name string) (*Process, error)

NewProcess creates and starts a new managed process. The process starts immediately and streams output to stdout with a name prefix.

func (*Process) Signal added in v1.0.0

func (p *Process) Signal(sig os.Signal)

Signal sends a signal to the process.

func (*Process) Wait added in v1.0.0

func (p *Process) Wait() <-chan error

Wait returns a channel that will receive an error when the process exits. If the process exits successfully, nil is sent. Otherwise, the error is sent.

type RPCAttempt added in v0.1.7

type RPCAttempt func(ctx context.Context, t *testing.T, cfg connection.TLSConfig) error

RPCAttempt is a function returned by ServerStarter that contains the information needed to start a client connection and attempt an RPC call.

type SafeBuffer added in v0.2.0

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

SafeBuffer is a thread-safe wrapper around bytes.Buffer. It protects concurrent access to the underlying buffer using a mutex, preventing race conditions when multiple goroutines read from or write to the same buffer simultaneously.

This is particularly useful in testing scenarios where command output is being written by one goroutine while another goroutine is reading or checking the buffer contents.

func (*SafeBuffer) Len added in v0.2.0

func (sb *SafeBuffer) Len() int

Len returns the number of bytes in the buffer in a thread-safe manner.

func (*SafeBuffer) Read added in v0.2.0

func (sb *SafeBuffer) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the buffer in a thread-safe manner. It implements the io.Reader interface. Returns the number of bytes read and any error encountered.

func (*SafeBuffer) Reset added in v0.2.0

func (sb *SafeBuffer) Reset()

Reset resets the buffer to be empty in a thread-safe manner. This is useful for reusing the same SafeBuffer across multiple test cases.

func (*SafeBuffer) String added in v0.2.0

func (sb *SafeBuffer) String() string

String returns the contents of the buffer as a string in a thread-safe manner. This is safe to call concurrently with Write operations.

func (*SafeBuffer) Write added in v0.2.0

func (sb *SafeBuffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer in a thread-safe manner. It implements the io.Writer interface. Returns the number of bytes written and any error encountered.

type ServerStarter added in v0.1.7

type ServerStarter func(t *testing.T, serverTLS, clientTLS connection.TLSConfig) RPCAttempt

ServerStarter is a function that starts the server, and returns a RPCAttempt function for initiating a client connection and attempting an RPC call. It receives the serverTLS config to configure the server, and the client TLS config to configure the service internal clients if needed.

type Servers added in v1.0.0

type Servers struct {
	Configs     []*serve.Config
	ServersStop []context.CancelFunc
}

Servers holds the server instances and their respective configurations.

func ServeManyForTest added in v1.0.0

func ServeManyForTest(
	ctx context.Context,
	t *testing.T,
	p StartServerParameters,
	r serve.Registerer,
) *Servers

ServeManyForTest starts multiple GRPC servers with a default configuration.

func ServeManyWithConfigForTest added in v1.0.0

func ServeManyWithConfigForTest(
	ctx context.Context, t *testing.T, r serve.Registerer, sc ...*serve.Config,
) *Servers

ServeManyWithConfigForTest starts multiple GRPC servers with given configurations.

type StartServerParameters added in v0.1.8

type StartServerParameters struct {
	TLSConfig  connection.TLSConfig
	NumService int
}

StartServerParameters defines the parameters for starting servers.

type TestingT added in v1.0.5

type TestingT interface {
	require.TestingT
	Helper()
}

TestingT is the assertion surface shared by testing.T and assert.CollectT: what require.TestingT carries, plus Helper. A helper that takes it can be called both from a test and from inside an require.Eventually condition — which runs on its own goroutine and may still be running after the test completed, where asserting on the test's own T panics the whole test binary rather than failing one test.

Prefer this over a bare require.TestingT, which cannot call Helper and so reports failures against the helper's own line instead of the caller's. testing.TB cannot serve either: it is sealed by an unexported method, so an assert.CollectT can never implement it. Use testing.TB only for a helper that needs the rest of it (Cleanup, TempDir, Context, ...) and is never called from a condition.

Jump to

Keyboard shortcuts

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