** We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify ** Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. testify contains the following packages: The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
Package sqlmock is a mock library implementing sql driver. Which has one and only purpose - to simulate any sql driver behavior in tests, without needing a real database connection. It helps to maintain correct **TDD** workflow. It does not require any modifications to your source code in order to test and mock database operations. Supports concurrency and multiple database mocking. The driver allows to mock any sql driver method behavior.
Package sqlmock is a mock library implementing sql driver. Which has one and only purpose - to simulate any sql driver behavior in tests, without needing a real database connection. It helps to maintain correct **TDD** workflow. It does not require any modifications to your source code in order to test and mock database operations. Supports concurrency and multiple database mocking. The driver allows to mock any sql driver method behavior.
Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. testify contains the following packages: The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. The http package contains tools to make it easier to test http activity using the Go testing system. The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. testify contains the following packages: The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. The http package contains tools to make it easier to test http activity using the Go testing system. The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
Package govpp provides the entry point to govpp functionality. It provides the API for connecting the govpp core to VPP either using the default VPP adapter, or using the adapter previously set by SetAdapter function (useful mostly just for unit/integration tests with mocked VPP adapter). To create a connection to VPP, use govpp.Connect function: Make sure you close the connection after using it. If the connection is not closed, it will leak resources. Please note that only one VPP connection is allowed for a single process. In case you need to mock the connection to VPP (e.g. for testing), use the govpp.SetAdapter function before calling govpp.Connect. Once connected to VPP, use the functions from the api package to communicate with it.
Package httpmock provides tools for mocking HTTP responses. Simple Example: Advanced Example:
Package demotools provides a set of tools that help you write code examples. **FileSystem** The filesystem is used to abstract the os module and allow for variations to be swapped out, such as mocks for testing. Package demotools provides a set of tools that help you write code examples. **Pausable** The pausable interface creates an easy to mock pausing object for testing. Package demotools provides a set of tools that help you write code examples. **Questioner** The questioner is used in interactive examples to ask for input from the user at a command prompt, validate the answer, and ask the question again, if needed. It is exposed through an interface so that it can be mocked for unit testing. A pre-written mock is provided in the testtools package.
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package micro is a pluggable framework for microservices
Package testtools provides a set of tools to help test code that calls AWS services. **AWS Middleware Stubber** The AWS Middleware Stubber is a unit testing tool that hooks into the AWS SDK for Go middleware (https://aws.github.io/aws-sdk-go-v2/docs/middleware/) to short-circuit calls to AWS services, verify inputs, and return predefined outputs. This improves unit testing because you don't have to define mocks or change the way your code calls AWS. Tests run without calling AWS, which means tests run faster and don't incur charges or risk impacting your resources. To use AwsmStubber, first create an instance of AwsmStubber. The stubber is configured to handle all calls to AWS before the Serialize middleware step. Use the stubber config to create a service client. Define and add all service actions that are called by your test. During your test run, the stubber verifies that each call is made in the order that stubs are added to the stubber. The stubber also checks actual input against expected input. If the call is verified, either the specified output is returned or, if an error is requested, the error is returned. Run your test and verify the results. Use testtools helper functions to verify errors and run exit code. By using sub tests, you can use the same test code to test both error and non-error paths. The testtools.ExitTest helper verifies that all expected stubs were called during the test, so if your test exits early and leaves uncalled stubs, the test fails. **Framework** The framework section of the package provides a set of helper functions that you can use in your tests to perform common tasks, such as verifying that errors returned from the code under test match up with the expected errors, and running exit checks to verify all stubs were called. **Scenarios** The scenarios section of the package provides a set of helper functions that you can use to run scenario tests. Scenarios typically string together several actions in a narrative format. The scenario test functions let you define the expected actions of your scenario as a list of stubs. Then, your test function is called first with no errors, and subsequently with each stub set to return an error. **Mocks** The mocks section of the package provides mocks of components that are used in the code examples, such as a mock of the IQuestioner interface that lets you specify a list of expected answers. The mock questioner returns these answers in sequence during a test to mock user input.
Package mocks provides mocks and helpers used in testing.
Pact Go enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project. Consumer side Pact testing is an isolated test that ensures a given component is able to collaborate with another (remote) component. Pact will automatically start a Mock server in the background that will act as the collaborators' test double. This implies that any interactions expected on the Mock server will be validated, meaning a test will fail if all interactions were not completed, or if unexpected interactions were found: A typical consumer-side test would look something like this: If this test completed successfully, a Pact file should have been written to ./pacts/my_consumer-my_provider.json containing all of the interactions expected to occur between the Consumer and Provider. In addition to verbatim value matching, you have 3 useful matching functions in the `dsl` package that can increase expressiveness and reduce brittle test cases. Here is a complex example that shows how all 3 terms can be used together: This example will result in a response body from the mock server that looks like: See the examples in the dsl package and the matcher tests (https://github.com/pact-foundation/pact-go/blob/master/dsl/matcher_test.go) for more matching examples. NOTE: You will need to use valid Ruby regular expressions (http://ruby-doc.org/core-2.1.5/Regexp.html) and double escape backslashes. Read more about flexible matching (https://github.com/pact-foundation/pact-ruby/wiki/Regular-expressions-and-type-matching-with-Pact. Provider side Pact testing, involves verifying that the contract - the Pact file - can be satisfied by the Provider. A typical Provider side test would like something like: The `VerifyProvider` will handle all verifications, treating them as subtests and giving you granular test reporting. If you don't like this behaviour, you may call `VerifyProviderRaw` directly and handle the errors manually. Note that `PactURLs` may be a list of local pact files or remote based urls (possibly from a Pact Broker - http://docs.pact.io/documentation/sharings_pacts.html). Pact reads the specified pact files (from remote or local sources) and replays the interactions against a running Provider. If all of the interactions are met we can say that both sides of the contract are satisfied and the test passes. When validating a Provider, you have 3 options to provide the Pact files: 1. Use "PactURLs" to specify the exact set of pacts to be replayed: Options 2 and 3 are particularly useful when you want to validate that your Provider is able to meet the contracts of what's in Production and also the latest in development. See this [article](http://rea.tech/enter-the-pact-matrix-or-how-to-decouple-the-release-cycles-of-your-microservices/) for more on this strategy. Each interaction in a pact should be verified in isolation, with no context maintained from the previous interactions. So how do you test a request that requires data to exist on the provider? Provider states are how you achieve this using Pact. Provider states also allow the consumer to make the same request with different expected responses (e.g. different response codes, or the same resource with a different subset of data). States are configured on the consumer side when you issue a dsl.Given() clause with a corresponding request/response pair. Configuring the provider is a little more involved, and (currently) requires running an API endpoint to configure any [provider states](http://docs.pact.io/documentation/provider_states.html) during the verification process. The option you must provide to the dsl.VerifyRequest is: An example route using the standard Go http package might look like this: See the examples or read more at http://docs.pact.io/documentation/provider_states.html. See the Pact Broker (http://docs.pact.io/documentation/sharings_pacts.html) documentation for more details on the Broker and this article (http://rea.tech/enter-the-pact-matrix-or-how-to-decouple-the-release-cycles-of-your-microservices/) on how to make it work for you. Publishing using Go code: Publishing from the CLI: Use a cURL request like the following to PUT the pact to the right location, specifying your consumer name, provider name and consumer version. The following flags are required to use basic authentication when publishing or retrieving Pact files to/from a Pact Broker: Pact Go uses a simple log utility (logutils - https://github.com/hashicorp/logutils) to filter log messages. The CLI already contains flags to manage this, should you want to control log level in your tests, you can set it like so:
HTTPmock provides tools for mocking HTTP responses. Simple Example: Advanced Example:
Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. testify contains the following packages: The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. The http package contains tools to make it easier to test http activity using the Go testing system. The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package grpcreplay supports the capture and replay of gRPC calls. Its main goal is to improve testing. Once you capture the calls of a test that runs against a real service, you have an "automatic mock" that can be replayed against the same test, yielding a unit test that is fast and flake-free. To record a sequence of gRPC calls to a file, create a Recorder and pass its DialOptions to grpc.Dial: It is essential to close the Recorder when the interaction is finished. There is also a NewRecorderWriter function for capturing to an arbitrary io.Writer. To replay a captured file, create a Replayer and ask it for a (fake) connection. We don't actually have to dial a server. (Since we're reading the file and not writing it, we don't have to be as careful about the error returned from Close). A test might use random or time-sensitive values, for instance to create unique resources for isolation from other tests. The test therefore has initial values, such as the current time, or a random seed, that differ from run to run. You must record this initial state and re-establish it on replay. To record the initial state, serialize it into a []byte and pass it as the second argument to NewRecorder: On replay, get the bytes from Replayer.Initial: Recorders and replayers have support for running callbacks before messages are written to or read from the replay file. A Recorder has a BeforeFunc that can modify a request or response before it is written to the replay file. The actual RPCs sent to the service during recording remain unaltered; only what is saved in the replay file can be changed. A Replayer has a BeforeFunc that can modify a request before it is sent for matching. Example uses for these callbacks include customized logging, or scrubbing data before RPCs are written to the replay file. If requests are modified by the callbacks during recording, it is important to perform the same modifications to the requests when replaying, or RPC matching on replay will fail. A common way to analyze and modify the various messages is to use a type switch. A nondeterministic program may invoke RPCs in a different order each time it is run. The order in which RPCs are called during recording may differ from the order during replay. The replayer matches incoming to recorded requests by method name and request contents, so nondeterminism is only a concern for identical requests that result in different responses. A nondeterministic program whose behavior differs depending on the order of such RPCs probably has a race condition: since both the recorded sequence of RPCs and the sequence during replay are valid orderings, the program should behave the same under both. The same is not true of streaming RPCs. The replayer matches streams only by method name, since it has no other information at the time the stream is opened. Two streams with the same method name that are started concurrently may replay in the wrong order. Besides the differences in replay mentioned above, other differences may cause issues for some programs. We list them here. The Replayer delivers a response to an RPC immediately, without waiting for other incoming RPCs. This can violate causality. For example, in a Pub/Sub program where one goroutine publishes and another subscribes, during replay the Subscribe call may finish before the Publish call begins. For streaming RPCs, the Replayer delivers the result of Send and Recv calls in the order they were recorded. No attempt is made to match message contents. At present, this package does not record or replay stream headers and trailers, or the result of the CloseSend method.
Package minimock is a command line tool that parses the input Go source file that contains an interface declaration and generates implementation of this interface that can be used as a mock. 1. It's integrated with the standard Go "testing" package 2. It supports variadic methods and embedded interfaces 3. It's very convenient to use generated mocks in table tests because it implements builder pattern to set up several mocks 4. It provides a useful Wait(time.Duration) helper to test concurrent code 5. It generates helpers to check if the mocked methods have been called and keeps your tests clean and up to date 6. It generates concurrent-safe mock execution counters that you can use in your mocks to implement sophisticated mocks behaviour Let's say we have the following interface declaration in github.com/gojuno/minimock/tests package: Here is how to generate the mock for this interface: The result file ./tests/formatter_mock_test.go will contain the following code: Setting up a mock using direct assignment: Setting up a mock using builder pattern and Return method: Setting up a mock using builder and Set method: Builder pattern is convenient when you have to mock more than one method of an interface. Let's say we have an io.ReadCloser interface which has two methods: Read and Close Then you can set up a mock using just one assignment: You can also use invocation counters in your mocks and tests: minimock.Controller When you have to mock multiple dependencies in your test it's recommended to use minimock.Controller and its Finish or Wait methods. All you have to do is instantiate the Controller and pass it as an argument to the mocks' constructors: Every mock is registered in the controller so by calling mc.Finish() you can verify that all the registered mocks have been called within your test. Sometimes we write tons of mocks for our tests but over time the tested code stops using mocked dependencies, however mocks are still present and being initialized in the test files. So while tested code can shrink, tests are only growing. To prevent this minimock provides Finish() method that verifies that all your mocks have been called at least once during the test run. Testing concurrent code is tough. Fortunately minimock provides you with the helper method that makes testing concurrent code easy. Here is how it works: Minimock comman line args:
Package redigomock is a mock for redigo library (redis client) Redigomock basically register the commands with the expected results in a internal global variable. When the command is executed via Conn interface, the mock will look to this global variable to retrieve the corresponding result. To start a mocked connection just do the following: Now you can inject it whenever your system needs a redigo.Conn because it satisfies all interface requirements. Before running your tests you need beyond of mocking the connection, registering the expected results. For that you can generate commands with the expected results. As the Expect method from Command receives anything (interface{}), another method was created to easy map the result to your structure. For that use ExpectMap: You should also test the error cases, and you can do it in the same way of a normal result. Sometimes you will want to register a command regardless the arguments, and you can do it with the method GenericCommand (mainly with the HMSET). All commands are registered in a global variable, so they will be there until all your test cases ends. So for good practice in test writing you should in the beginning of each test case clear the mock states. Let's see a full test example. Imagine a Person structure and a function that pick up this person in Redis using redigo library (file person.go): Now we need to test it, so let's create the corresponding test with redigomock (fileperson_test.go): When you use redis as a persistent list, then you might want to call the same redis command multiple times. For example: To test it, you can chain redis responses. Let's write a test case: In the first iteration of the loop redigomock would return "www.some.url.com", then "www.another.url.com" and finally redis.ErrNil. Sometimes providing expected arguments to redigomock at compile time could be too constraining. Let's imagine you use redis hash sets to store some data, along with the timestamp of the last data update. Let's expand our Person struct: And add a function updating personal data (phone number for example). Please notice that the update timestamp can't be determined at compile time: Unit test: As you can see at the position of current timestamp redigomock is told to match AnyInt struct created by NewAnyInt() method. AnyInt struct will match any integer passed to redigomock from the tested method. Please see fuzzyMatch.go file for more details.
Package mocks is a generated GoMock package.
Package wabbit provides an interface for AMQP client specification and a mock implementation of that interface.
Pact Go enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project. Consumer side Pact testing is an isolated test that ensures a given component is able to collaborate with another (remote) component. Pact will automatically start a Mock server in the background that will act as the collaborators' test double. This implies that any interactions expected on the Mock server will be validated, meaning a test will fail if all interactions were not completed, or if unexpected interactions were found: A typical consumer-side test would look something like this: If this test completed successfully, a Pact file should have been written to ./pacts/my_consumer-my_provider.json containing all of the interactions expected to occur between the Consumer and Provider. In addition to verbatim value matching, you have 3 useful matching functions in the `dsl` package that can increase expressiveness and reduce brittle test cases. Here is a complex example that shows how all 3 terms can be used together: This example will result in a response body from the mock server that looks like: See the examples in the dsl package and the matcher tests (https://github.com/pact-foundation/pact-go/v2/blob/master/dsl/matcher_test.go) for more matching examples. NOTE: You will need to use valid Ruby regular expressions (http://ruby-doc.org/core-2.1.5/Regexp.html) and double escape backslashes. Read more about flexible matching (https://github.com/pact-foundation/pact-ruby/wiki/Regular-expressions-and-type-matching-with-Pact. Provider side Pact testing, involves verifying that the contract - the Pact file - can be satisfied by the Provider. A typical Provider side test would like something like: The `VerifyProvider` will handle all verifications, treating them as subtests and giving you granular test reporting. If you don't like this behaviour, you may call `VerifyProviderRaw` directly and handle the errors manually. Note that `PactURLs` may be a list of local pact files or remote based urls (possibly from a Pact Broker - http://docs.pact.io/documentation/sharings_pacts.html). Pact reads the specified pact files (from remote or local sources) and replays the interactions against a running Provider. If all of the interactions are met we can say that both sides of the contract are satisfied and the test passes. When validating a Provider, you have 3 options to provide the Pact files: 1. Use "PactURLs" to specify the exact set of pacts to be replayed: Options 2 and 3 are particularly useful when you want to validate that your Provider is able to meet the contracts of what's in Production and also the latest in development. See this [article](http://rea.tech/enter-the-pact-matrix-or-how-to-decouple-the-release-cycles-of-your-microservices/) for more on this strategy. Each interaction in a pact should be verified in isolation, with no context maintained from the previous interactions. So how do you test a request that requires data to exist on the provider? Provider states are how you achieve this using Pact. Provider states also allow the consumer to make the same request with different expected responses (e.g. different response codes, or the same resource with a different subset of data). States are configured on the consumer side when you issue a dsl.Given() clause with a corresponding request/response pair. Configuring the provider is a little more involved, and (currently) requires running an API endpoint to configure any [provider states](http://docs.pact.io/documentation/provider_states.html) during the verification process. The option you must provide to the dsl.VerifyRequest is: An example route using the standard Go http package might look like this: See the examples or read more at http://docs.pact.io/documentation/provider_states.html. See the Pact Broker (http://docs.pact.io/documentation/sharings_pacts.html) documentation for more details on the Broker and this article (http://rea.tech/enter-the-pact-matrix-or-how-to-decouple-the-release-cycles-of-your-microservices/) on how to make it work for you. Publishing using Go code: Publishing from the CLI: Use a cURL request like the following to PUT the pact to the right location, specifying your consumer name, provider name and consumer version. The following flags are required to use basic authentication when publishing or retrieving Pact files to/from a Pact Broker: Pact Go uses a simple log utility (logutils - https://github.com/hashicorp/logutils) to filter log messages. The CLI already contains flags to manage this, should you want to control log level in your tests, you can set it like so:
These packages contain code that can help you test against the GCP Client Libraries for Go (https://github.com/GoogleCloudPlatform/google-cloud-go). We do not recommend using mocks for most testing. Please read https://testing.googleblog.com/2013/05/testing-on-toilet-dont-overuse-mocks.html. Note: These packages are in alpha. Some backwards-incompatible changes may occur. All interfaces in this package include an embedToIncludeNewMethods method. This is intentionally unexported so that any implementor of the interface must embed the interface in their implementation. Embedding the interface in an implementation has the effect that any future methods added to the interface will not cause compile-time errors (the implementation does not implement the newly-added method), since embedded interfaces provide a default method for unimplemented methods. See Example (RecordBuckets) for an example of how to implement interfaces (including embedding the interface).
Package minimock is a command line tool that parses the input Go source file that contains an interface declaration and generates implementation of this interface that can be used as a mock. 1. It's integrated with the standard Go "testing" package 2. It supports variadic methods and embedded interfaces 3. It's very convenient to use generated mocks in table tests because it implements builder pattern to set up several mocks 4. It provides a useful Wait(time.Duration) helper to test concurrent code 5. It generates helpers to check if the mocked methods have been called and keeps your tests clean and up to date 6. It generates concurrent-safe mock execution counters that you can use in your mocks to implement sophisticated mocks behaviour Let's say we have the following interface declaration in github.com/gojuno/minimock/tests package: Here is how to generate the mock for this interface: The result file ./tests/formatter_mock_test.go will contain the following code: Setting up a mock using direct assignment: Setting up a mock using builder pattern and Return method: Setting up a mock using builder and Set method: Builder pattern is convenient when you have to mock more than one method of an interface. Let's say we have an io.ReadCloser interface which has two methods: Read and Close Then you can set up a mock using just one assignment: You can also use invocation counters in your mocks and tests: minimock.Controller When you have to mock multiple dependencies in your test it's recommended to use minimock.Controller and its Finish or Wait methods. All you have to do is instantiate the Controller and pass it as an argument to the mocks' constructors: Every mock is registered in the controller so by calling mc.Finish() you can verify that all the registered mocks have been called within your test. Sometimes we write tons of mocks for our tests but over time the tested code stops using mocked dependencies, however mocks are still present and being initialized in the test files. So while tested code can shrink, tests are only growing. To prevent this minimock provides Finish() method that verifies that all your mocks have been called at least once during the test run. Testing concurrent code is tough. Fortunately minimock provides you with the helper method that makes testing concurrent code easy. Here is how it works: Minimock comman line args:
Package testza is a full-featured testing framework for Go. It integrates with the default test runner, so you can use it with the standard `go test` tool. Testza contains easy to use methods, like assertions, output capturing, mocking, and much more.