microcks

package module
v0.3.2 Latest Latest
Warning

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

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

README

Microcks Testcontainers Go

Go library for Testcontainers that enables embedding Microcks into your Go unit tests with lightweight, throwaway instance thanks to containers

Want to see this extension in action? Check out our sample application. 🚀

GitHub Workflow Status License Project Chat Go version GitHub release Artifact HUB CNCF Landscape

Build Status

Latest released version is v0.3.2.

Current development version is v0.3.3.

Fossa license and security scans

FOSSA Status FOSSA Status FOSSA Status

OpenSSF best practices on Microcks core

CII Best Practices OpenSSF Scorecard

Community

To get involved with our community, please make sure you are familiar with the project's Code of Conduct.

How to use it?

Include it into your project dependencies

To get the latest version, use go1.23+ and fetch using the go get command. For example:

go get microcks.io/testcontainers-go@latest

To get a specific version, use go1.23+ and fetch the desired version using the go get command. For example:

go get microcks.io/testcontainers-go@v0.3.2
Startup the container

You just have to specify the container image you'd like to use. This library requires a Microcks uber distribution (with no MongoDB dependency).

import (
    microcks "microcks.io/testcontainers-go"
)

microcksContainer, err := microcks.Run(ctx, "quay.io/microcks/microcks-uber:nightly")
Import content in Microcks

To use Microcks mocks or contract-testing features, you first need to import OpenAPI, Postman Collection, GraphQL or gRPC artifacts. Artifacts can be imported as main/Primary ones or as secondary ones. See Multi-artifacts support for details.

You can do it before starting the container using simple paths:

import (
    microcks "microcks.io/testcontainers-go"
)

microcksContainer, err := microcks.Run(ctx, 
    "quay.io/microcks/microcks-uber:nightly",
    microcks.WithMainArtifact("testdata/apipastries-openapi.yaml"),
    microcks.WithSecondaryArtifact("testdata/apipastries-postman-collection.json"),
)

or once the container started using ImportAsMainArtifact and ImportAsSecondaryArtifact functions:

status, err := microcksContainer.ImportAsMainArtifact(context.Background(), "testdata/apipastries-openapi.yaml")
if err != nil {
    log.Fatal(err)
}

status, err = microcksContainer.ImportAsSecondaryArtifact(context.Background(), "testdata/apipastries-postman-collection.json")
if err != nil {
    log.Fatal(err)
}

status if the status of the Http response from the microcks container and should be equal to 201 in case of success.

Please refer to our microcks_test for comprehensive example on how to use it.

Using mock endpoints for your dependencies

During your test setup, you'd probably need to retrieve mock endpoints provided by Microcks containers to setup your base API url calls. You can do it like this:

baseApiUrl := microcksContainer.RestMockEndpoint(ctx, "API Pastries", "0.0.1")

The container provides methods for different supported API styles/protocols (Soap, GraphQL, gRPC,...).

The container also provides HttpEndpoint() for raw access to those API endpoints.

Verifying mock endpoint has been invoked

Once the mock endpoint has been invoked, you'd probably need to ensure that the mock have been really invoked.

You can do it like this :

called, err := microcksContainer.Verify(ctx, "API Pastries", "0.0.1")
require.NoError(t, err)
require.True(t, called)

Or like this after 2 subsequent call to the same mock endpoint:

callCount, err := microcksContainer.ServiceInvocationsCount(ctx, "API Pastries", "0.0.1")
require.NoError(t, err)
require.Equal(t, 2, callCount)
Launching new contract-tests

If you want to ensure that your application under test is conformant to an OpenAPI contract (or many contracts), you can launch a Microcks contract/conformance test using the local server port you're actually running:

import (
    client "microcks.io/go-client"
    microcks "microcks.io/testcontainers-go"
)

// Build a new TestRequest.
testRequest := client.TestRequest{
    ServiceId:    "API Pastries:0.0.1",
    RunnerType:   client.TestRunnerTypeOPENAPISCHEMA,
    TestEndpoint: "http://bad-impl:3001",
    Timeout:      2000,
}

testResult, err := microcksContainer.TestEndpoint(context.Background(), &testRequest)
require.NoError(t, err)

require.False(t, testResult.Success)
require.Equal(t, "http://bad-impl:3001", testResult.TestedEndpoint)

The testResult gives you access to all details regarding success of failure on different test cases.

In addition, you can use the MessagesForTestCase() function to retrieve the messages exchanged during the test.

A comprehensive Go demo application illustrating both usages is available here: go-order-service.

Using authentication Secrets

It's a common need to authenticate to external systems like Http/Git repositories or external brokers. For that, the microcks package provides the WithSecret() method to register authentication secrets at startup:

microcksContainer, err := microcks.Run(ctx, 
    "quay.io/microcks/microcks-uber:nightly",
    microcks.WithMainArtifact("testdata/apipastries-openapi.yaml"),
    microcks.WithSecondaryArtifact("testdata/apipastries-postman-collection.json"),
    microcks.WithSecret(client.Secret{
        Name: "localstack secret",
        Username: "test",
        Password: "test",
    }),
)

You may reuse this secret using its name later on during a test like this:

testRequest := client.TestRequest{
    ServiceId:    "Pastry orders API:0.1.0",
    RunnerType:   client.TestRunnerTypeASYNCAPISCHEMA,
    TestEndpoint: "sqs://us-east-1/pastry-orders?overrideUrl=http://localstack:4566",
    SecretName:   "localstack secret",
    Timeout:      2000,
}
Advanced features with MicrocksContainersEnsemble

The MicrocksContainer referenced above supports essential features of Microcks provided by the main Microcks container. The list of supported features is the following:

  • Mocking of REST APIs using different kinds of artifacts,
  • Contract-testing of REST APIs using OPEN_API_SCHEMA runner/strategy,
  • Mocking and contract-testing of SOAP WebServices,
  • Mocking and contract-testing of GraphQL APIs,
  • Mocking and contract-testing of gRPC APIs.

To support features like Asynchronous API and POSTMAN contract-testing, we introduced MicrocksContainersEnsemble that allows managing additional Microcks services. MicrocksContainersEnsemble allow you to implement Different levels of API contract testing in the Inner Loop with Testcontainers!

A MicrocksContainersEnsemble conforms to Testcontainers lifecycle methods and presents roughly the same interface as a MicrocksContainer. You can create and build an ensemble that way:

import (
    ensemble "microcks.io/testcontainers-go/ensemble"
)

ensembleContainers, err := ensemble.RunContainers(ctx, 
    ensemble.WithMainArtifact("testdata/apipastries-openapi.yaml"),
    ensemble.WithSecondaryArtifact("testdata/apipastries-postman-collection.json"),
)

A MicrocksContainer is wrapped by an ensemble and is still available to import artifacts and execute test methods. You have to access it using:

microcks := ensemble.GetMicrocksContainer();
microcks.ImportAsMainArtifact(...);
microcks.Logs(...);

Please refer to our ensemble tests for comprehensive example on how to use it.

Postman contract-testing

On this ensemble you may want to enable additional features such as Postman contract-testing:

import (
    ensemble "microcks.io/testcontainers-go/ensemble"
)

ensembleContainers, err := ensemble.RunContainers(ctx,
    // Microcks container in ensemble
    ensemble.WithMainArtifact("testdata/apipastries-openapi.yaml"),
    ensemble.WithSecondaryArtifact("testdata/apipastries-postman-collection.json"),

    // Postman container in ensemble
    ensemble.WithPostman(true),
)

You can execute a POSTMAN test using an ensemble that way:

// Build a new TestRequest.
testRequest := client.TestRequest{
    ServiceId:    "API Pastries:0.0.1",
    RunnerType:   client.TestRunnerTypePOSTMAN,
    TestEndpoint: "http://good-impl:3003",
    Timeout:      2000,
}

testResult := ensemble.
    GetMicrocksContainer().
    TestEndpoint(context.Background(), testRequest);
Asynchronous API support

Asynchronous API feature need to be explicitly enabled as well. In the case you want to use it for mocking purposes, you'll have to specify additional connection details to the broker of your choice. See an example below with connection to a Kafka broker:

ensembleContainers, err := ensemble.RunContainers(ctx,
	// ...
	ensemble.WithAsyncFeature(),
	ensemble.WithKafkaConnection(kafka.Connection{
		BootstrapServers: "kafka:9092",
	}),
)
Using mock endpoints for your dependencies

Once started, the ensembleContainers.GetAsyncMinionContainer() provides methods for retrieving mock endpoint names for the different supported protocols (WebSocket, Kafka, SQS and SNS).

kafkaTopic := ensembleContainers.
	GetAsyncMinionContainer().
	KafkaMockTopic("Pastry orders API", "0.1.0", "SUBSCRIBE pastry/orders")
Launching new contract-tests

Using contract-testing techniques on Asynchronous endpoints may require a different style of interacting with the Microcks container. For example, you may need to:

  • Start the test making Microcks listen to the target async endpoint,
  • Activate your System Under Tests so that it produces an event,
  • Finalize the Microcks tests and actually ensure you received one or many well-formed events.

For that the MicrocksContainer now provides a TestEndpointAsync(ctx context.Context, testRequest *client.TestRequest, testResult chan *client.TestResult) method that actually uses a channel. Once invoked, you may trigger your application events and then wait to receive the future result to assert like this:

// Start the test, making Microcks listen the endpoint provided in testRequest
testResultChan := make(chan *client.TestResult)
go ensembleContainers.GetMicrocksContainer().TestEndpointAsync(ctx, &testRequest, testResultChan)

// Here below: activate your app to make it produce events on this endpoint.
// myapp.invokeBusinessMethodThatTriggerEvents();

// Now retrieve the final test result and assert.
testResult := <-testResultChan
require.NoError(t, err)
require.True(t, testResult.Success)

In addition, you can use the EventMessagesForTestCase() function to retrieve the messages exchanged during the test.

Documentation

Overview

* Copyright The Microcks Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.

Index

Constants

View Source
const (
	DefaultImage = "quay.io/microcks/microcks-uber:latest"

	// DefaultHttpPort represents the default Microcks HTTP port.
	DefaultHttpPort = "8080/tcp"

	// DefaultGrpcPort represents the default Microcks GRPC port.
	DefaultGrpcPort = "9090/tcp"

	// DefaultNetworkAlias represents the default network alias of the the MicrocksContainer.
	DefaultNetworkAlias = "microcks"
)

Variables

This section is empty.

Functions

func WithArtifact added in v0.2.0

func WithArtifact(artifactFilePath string, main bool) testcontainers.CustomizeRequestOption

WithArtifact provides paths to artifacts that will be imported within the Microcks container. Once it will be started and healthy.

func WithEnv added in v0.2.0

func WithEnv(key, value string) testcontainers.CustomizeRequestOption

WithEnv allows to add an environment variable.

func WithHostAccessPorts added in v0.2.0

func WithHostAccessPorts(hostAccessPorts []int) testcontainers.CustomizeRequestOption

WithHostAccessPorts allows to set the host access ports.

func WithMainArtifact added in v0.2.0

func WithMainArtifact(artifactFilePath string) testcontainers.CustomizeRequestOption

WithMainArtifact provides paths to artifacts that will be imported as main or main ones within the Microcks container. Once it will be started and healthy.

func WithNetwork added in v0.2.0

func WithNetwork(networkName string) testcontainers.CustomizeRequestOption

WithNetwork allows to add a custom network. Deprecated: Use network.WithNetwork from testcontainers instead.

func WithNetworkAlias added in v0.2.0

func WithNetworkAlias(networkName, networkAlias string) testcontainers.CustomizeRequestOption

WithNetworkAlias allows to add a custom network alias for a specific network. Deprecated: Use network.WithNetwork from testcontainers instead.

func WithSecondaryArtifact added in v0.2.0

func WithSecondaryArtifact(artifactFilePath string) testcontainers.CustomizeRequestOption

WithSecondaryArtifact provides paths to artifacts that will be imported as main or main ones within the Microcks container. Once it will be started and healthy.

func WithSecret added in v0.2.0

func WithSecret(s client.Secret) testcontainers.CustomizeRequestOption

WithSecret allows to add a new secret.

Types

type MicrocksContainer

type MicrocksContainer struct {
	testcontainers.Container
}

MicrocksContainer represents the Microcks container type used in the module.

func Run added in v0.2.0

func Run(ctx context.Context, image string, opts ...testcontainers.ContainerCustomizer) (*MicrocksContainer, error)

Run creates an instance of the MicrocksContainer type.

func RunContainer deprecated

func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*MicrocksContainer, error)

Deprecated: use Run instead RunContainer creates an instance of the MicrocksContainer type.

func (*MicrocksContainer) EventMessagesForTestCase added in v0.3.0

func (container *MicrocksContainer) EventMessagesForTestCase(ctx context.Context, testResult *client.TestResult, operationName string) (*[]client.UnidirectionalEvent, error)

EventMessagesForTestCase retrieves event messages received during a test on an endpoint.

func (*MicrocksContainer) GraphQLMockEndpoint added in v0.2.0

func (container *MicrocksContainer) GraphQLMockEndpoint(ctx context.Context, service string, version string) (string, error)

GraphQLMockEndpoint get the exposed mock endpoints for a GraphQL Service.

func (*MicrocksContainer) GraphQLMockEndpointPath added in v0.3.2

func (container *MicrocksContainer) GraphQLMockEndpointPath(ctx context.Context, service string, version string) string

GraphQLMockEndpointPath get the exposed mock endpoints path for a GraphQL Service.

func (*MicrocksContainer) GrpcMockEndpoint

func (container *MicrocksContainer) GrpcMockEndpoint(ctx context.Context) (string, error)

GrpcMockEndpoint get the exposed mock endpoint for a GRPC Service.

func (*MicrocksContainer) HttpEndpoint

func (container *MicrocksContainer) HttpEndpoint(ctx context.Context) (string, error)

HttpEndpoint allows retrieving the Http endpoint where Microcks can be accessed. (you'd have to append '/api' to access APIs)

func (*MicrocksContainer) ImportAsMainArtifact

func (container *MicrocksContainer) ImportAsMainArtifact(ctx context.Context, artifactFilePath string) (int, error)

ImportAsMainArtifact imports an artifact as a primary or main one within the Microcks container.

func (*MicrocksContainer) ImportAsSecondaryArtifact

func (container *MicrocksContainer) ImportAsSecondaryArtifact(ctx context.Context, artifactFilePath string) (int, error)

ImportAsSecondaryArtifact imports an artifact as a secondary one within the Microcks container.

func (*MicrocksContainer) MessagesForTestCase added in v0.3.0

func (container *MicrocksContainer) MessagesForTestCase(ctx context.Context, testResult *client.TestResult, operationName string) (*[]client.RequestResponsePair, error)

MessagesForTestCase retrieves messages exchanged during a test on an endpoint.

func (*MicrocksContainer) RestMockEndpoint

func (container *MicrocksContainer) RestMockEndpoint(ctx context.Context, service string, version string) (string, error)

RestMockEndpoint get the exposed mock endpoint for a REST Service.

func (*MicrocksContainer) RestMockEndpointPath added in v0.3.2

func (container *MicrocksContainer) RestMockEndpointPath(ctx context.Context, service string, version string) string

RestMockEndpointPath get the exposed mock endpoint path for a REST Service.

func (*MicrocksContainer) ServiceInvocationsCount added in v0.3.0

func (container *MicrocksContainer) ServiceInvocationsCount(ctx context.Context, serviceName string, serviceVersion string) (int, error)

ServiceInvocationsCount gets the invocations' count for a given service, identified by its name and version, for the current date.

func (*MicrocksContainer) ServiceInvocationsCountAtDate added in v0.3.0

func (container *MicrocksContainer) ServiceInvocationsCountAtDate(ctx context.Context, serviceName string, serviceVersion string, date time.Time) (int, error)

ServiceInvocationsCountAtDate gets the invocations' count for a given service, identified by its name and version, for the given invocations' date.

func (*MicrocksContainer) SoapMockEndpoint

func (container *MicrocksContainer) SoapMockEndpoint(ctx context.Context, service string, version string) (string, error)

SoapMockEndpoint get the exposed mock endpoint for a SOAP Service.

func (*MicrocksContainer) SoapMockEndpointPath added in v0.3.2

func (container *MicrocksContainer) SoapMockEndpointPath(ctx context.Context, service string, version string) string

SoapMockEndpointPath get the exposed mock endpoint path for a SOAP Service.

func (*MicrocksContainer) TestEndpoint

func (container *MicrocksContainer) TestEndpoint(ctx context.Context, testRequest *client.TestRequest) (*client.TestResult, error)

TestEndpoint launches a conformance test on an endpoint.

func (*MicrocksContainer) TestEndpointAsync added in v0.2.0

func (container *MicrocksContainer) TestEndpointAsync(ctx context.Context, testRequest *client.TestRequest, testResult chan *client.TestResult) error

TestEndpointAsync launches a conformance test on an endpoint and will provide result via a channel.

func (*MicrocksContainer) ValidatingRestMockEndpoint added in v0.3.2

func (container *MicrocksContainer) ValidatingRestMockEndpoint(ctx context.Context, service string, version string) (string, error)

ValidatingRestMockEndpoint get the exposed mock endpoint - with request validation enabled - for a REST Service.

func (*MicrocksContainer) ValidatingRestMockEndpointPath added in v0.3.2

func (container *MicrocksContainer) ValidatingRestMockEndpointPath(ctx context.Context, service string, version string) string

ValidatingRestMockEndpointPath get the exposed mock endpoint path - with request validation enabled - for a REST Service.

func (*MicrocksContainer) ValidatingSoapMockEndpoint added in v0.3.2

func (container *MicrocksContainer) ValidatingSoapMockEndpoint(ctx context.Context, service string, version string) (string, error)

ValidatingSoapMockEndpoint get the exposed mock endpoint - with request validation enabled - for a SOAP Service.

func (*MicrocksContainer) ValidatingSoapMockEndpointPath added in v0.3.2

func (container *MicrocksContainer) ValidatingSoapMockEndpointPath(ctx context.Context, service string, version string) string

ValidatingSoapMockEndpointPath get the exposed mock endpoint path - with request validation enabled - for a SOAP Service.

func (*MicrocksContainer) Verify added in v0.3.0

func (container *MicrocksContainer) Verify(ctx context.Context, serviceName string, serviceVersion string) (bool, error)

Verify checks that given Service has been invoked at least one time, for the current invocations' date.

func (*MicrocksContainer) VerifyAtDate added in v0.3.0

func (container *MicrocksContainer) VerifyAtDate(ctx context.Context, serviceName string, serviceVersion string, date time.Time) (bool, error)

VerifyAtDate checks that given Service has been invoked at least one time, for the given invocations' date.

Directories

Path Synopsis
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
async
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
async/connection/amazonservice
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
async/connection/generic
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
async/connection/kafka
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
postman
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
internal
test
* Copyright The Microcks Authors.
* Copyright The Microcks Authors.
* This is local copy of testcontainers/testcontainers/go/modules/kafka/kafka.go with modified startup script for * the purpose of fully working demonstration.
* This is local copy of testcontainers/testcontainers/go/modules/kafka/kafka.go with modified startup script for * the purpose of fully working demonstration.

Jump to

Keyboard shortcuts

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