test

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: Apache-2.0 Imports: 40 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 GetDockerClient added in v0.1.7

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

GetDockerClient instantiate a new docker client.

func GetIntMetricValue

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

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

func GetMetricValue

func GetMetricValue(t *testing.T, m prometheus.Metric) float64

GetMetricValue returns the value of a prometheus metric.

func GetMetricValueFromURL

func GetMetricValueFromURL(t *testing.T, url, metricName string, tlsConfig *tls.Config) int

GetMetricValueFromURL reads the metrics endpoint and fetch the value of a specific 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(t *testing.T, endpoint connection.WithAddress) *grpc.ClientConn

NewInsecureConnection creates the default connection with insecure credentials.

func NewInsecureConnectionWithRetry added in v0.1.7

func NewInsecureConnectionWithRetry(
	t *testing.T, 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 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 require.TestingT, expected, actual []T, msgAndArgs ...any,
)

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

func RequireProtoEqual

func RequireProtoEqual(t require.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,
	t *testing.T,
	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.

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 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 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.

Jump to

Keyboard shortcuts

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