test

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CreatorCertificate denotes Creator field in protoblocktx.Identity to contain x509 certificate.
	CreatorCertificate = 0
	// CreatorID denotes Creator field in protoblocktx.Identity to contain the digest of x509 certificate.
	CreatorID = 1
)
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",
		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", 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 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) *connection.ServerConfig

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

func NewPreAllocatedLocalHostServer added in v0.2.0

func NewPreAllocatedLocalHostServer(t *testing.T, tlsConfig connection.TLSConfig) *connection.ServerConfig

NewPreAllocatedLocalHostServer 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 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 Run added in v0.1.9

func Run(cmd *exec.Cmd, name, startCheck string) ifrit.Process

Run executes the specified command and returns the corresponding process. It is important to note that the underlying invocation function (Invoke) returns only when either process.Ready or process.Wait has been read. Consequently, the caller only needs to read process.Wait to wait for the process to complete and capture any errors that may have occurred during execution.

func RunGrpcServerForTest

func RunGrpcServerForTest(
	ctx context.Context, tb testing.TB, serverConfig *connection.ServerConfig, register func(server *grpc.Server),
) *grpc.Server

RunGrpcServerForTest starts a GRPC server using a register method. It handles the cleanup of the GRPC server at the end of a test, and ensure the test is ended only when the GRPC server is 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 GRPC server did not end with failure.

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 RunServiceAndGrpcForTest

func RunServiceAndGrpcForTest(
	ctx context.Context,
	t *testing.T,
	service grpcservice.Service,
	serverConfig ...*connection.ServerConfig,
) *channel.Ready

RunServiceAndGrpcForTest 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 ServerToMultiClientConfig added in v0.1.7

func ServerToMultiClientConfig(
	clientTLS connection.TLSConfig, servers ...*connection.ServerConfig,
) *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 GrpcServers

type GrpcServers struct {
	Servers []*grpc.Server
	Configs []*connection.ServerConfig
}

GrpcServers holds the server instances and their respective configurations.

func StartGrpcServersForTest

func StartGrpcServersForTest(
	ctx context.Context,
	t *testing.T,
	p StartServerParameters,
	register func(*grpc.Server),
) *GrpcServers

StartGrpcServersForTest starts multiple GRPC servers with a default configuration.

func StartGrpcServersWithConfigForTest

func StartGrpcServersWithConfigForTest(
	ctx context.Context, t *testing.T, register func(*grpc.Server), sc ...*connection.ServerConfig,
) *GrpcServers

StartGrpcServersWithConfigForTest starts multiple GRPC servers with given configurations.

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