All Projects → steinfletcher → Apitest

steinfletcher / Apitest

Licence: mit
A simple and extensible behavioural testing library for Go. You can use api test to simplify REST API, HTTP handler and e2e tests.

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Apitest

Prism
Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.
Stars: ✭ 2,484 (+683.6%)
Mutual labels:  api-testing, mocking
Mockbin
Mock, Test & Track HTTP Requests and Response for Microservices
Stars: ✭ 1,782 (+462.15%)
Mutual labels:  api-testing, mocking
mock-inspect
Mocks network requests and allows you to make assertions about how these requests happened. Supports auto-mocking of graphQL requests given a valid schema.
Stars: ✭ 19 (-94.01%)
Mutual labels:  mocking
Mockqueryable
Moking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc
Stars: ✭ 281 (-11.36%)
Mutual labels:  mocking
automock
A library for testing classes with auto mocking capabilities using jest-mock-extended
Stars: ✭ 26 (-91.8%)
Mutual labels:  mocking
TestBox
TestBox is a next generation testing framework for ColdFusion (CFML) that is based on BDD (Behavior Driven Development) for providing a clean obvious syntax for writing tests. It also includes MockBox, our mocking and stubbing framework.
Stars: ✭ 54 (-82.97%)
Mutual labels:  mocking
test-graphql-java
Easy Graphql Testing in Java
Stars: ✭ 22 (-93.06%)
Mutual labels:  api-testing
node-muk
Mock object methods and dependencies.
Stars: ✭ 57 (-82.02%)
Mutual labels:  mocking
Unmock Plugin
Gradle plugin to be used in combination with the new unit testing feature of the Gradle Plugin / Android Studio to use real classes for e.g. SparseArray.
Stars: ✭ 304 (-4.1%)
Mutual labels:  mocking
api-test-helper
A collection of helper methods for testing and debugging API endpoints.
Stars: ✭ 50 (-84.23%)
Mutual labels:  api-testing
Aioresponses
Aioresponses is a helper for mock/fake web requests in python aiohttp package.
Stars: ✭ 278 (-12.3%)
Mutual labels:  mocking
super-powered-api-testing
Comparisons of powerful API testing tools
Stars: ✭ 25 (-92.11%)
Mutual labels:  api-testing
MockDataGenerator
Generate mock data for POCO
Stars: ✭ 12 (-96.21%)
Mutual labels:  mocking
Pook
HTTP traffic mocking and testing made simple in Python
Stars: ✭ 257 (-18.93%)
Mutual labels:  mocking
apitest
Apitest is declarative api testing tool with JSON-like DSL.
Stars: ✭ 88 (-72.24%)
Mutual labels:  api-testing
Stubby4j
An HTTP stub server for testing application interactions with web services (REST, etc) & external system stubbing for easy testing
Stars: ✭ 300 (-5.36%)
Mutual labels:  api-testing
dummyjdbc
dummyjdbc answers database requests with dummy data to be independent of an existing database.
Stars: ✭ 20 (-93.69%)
Mutual labels:  mocking
speakeasy
A tool for creating Go web servers which can be embedded in iOS and Android apps.
Stars: ✭ 27 (-91.48%)
Mutual labels:  mocking
Hippolyte
HTTP Stubbing in Swift
Stars: ✭ 109 (-65.62%)
Mutual labels:  mocking
Firebase Mock
Firebase mock library for writing unit tests
Stars: ✭ 319 (+0.63%)
Mutual labels:  mocking

Godoc Coverage Status Build Status Go Report Card Mentioned in Awesome Go

apitest

A simple and extensible behavioural testing library. Supports mocking external http calls and renders sequence diagrams on completion.

In behavioural tests the internal structure of the app is not known by the tests. Data is input to the system and the outputs are expected to meet certain conditions.

Join the conversation at #apitest on https://gophers.slack.com.

Logo by @egonelbre

Documentation

Please visit https://apitest.dev for the latest documentation.

Installation

go get -u github.com/steinfletcher/apitest

Examples

Framework and library integration examples

Example Comment
gin popular martini-like web framework
graphql using gqlgen.com to generate a graphql server
gorilla the gorilla web toolkit
iris iris web framework
echo High performance, extensible, minimalist Go web framework
fiber Express inspired web framework written in Go
httprouter High performance HTTP request router that scales well
mocks example mocking out external http calls
sequence diagrams generate sequence diagrams from tests. See the demo
Ginkgo Ginkgo BDD test framework

Companion libraries

Library Comment
JSONPath JSONPath assertion addons
CSS Selectors CSS selector assertion addons
PlantUML Export sequence diagrams as plantUML
DynamoDB Add DynamoDB interactions to sequence diagrams

Credits

This library was influenced by the following software packages:

  • YatSpec for creating sequence diagrams from tests
  • MockMVC and superagent for the concept and behavioural testing approach
  • Gock for the approach to mocking HTTP services in Go
  • Baloo for API design

Code snippets

JSON body matcher

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/user/1234").
		Expect(t).
		Body(`{"id": "1234", "name": "Tate"}`).
		Status(http.StatusCreated).
		End()
}

JSONPath

For asserting on parts of the response body JSONPath may be used. A separate module must be installed which provides these assertions - go get -u github.com/steinfletcher/apitest-jsonpath. This is packaged separately to keep this library dependency free.

Given the response is {"a": 12345, "b": [{"key": "c", "value": "result"}]}

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Assert(jsonpath.Contains(`$.b[? @.key=="c"].value`, "result")).
		End()
}

and jsonpath.Equals checks for value equality

func TestApi(t *testing.T) {
	apitest.New(handler).
		Get("/hello").
		Expect(t).
		Assert(jsonpath.Equal(`$.a`, float64(12345))).
		End()
}

Custom assert functions

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Assert(func(res *http.Response, req *http.Request) error {
			assert.Equal(t, http.StatusOK, res.StatusCode)
			return nil
		}).
		End()
}

Assert cookies

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Patch("/hello").
		Expect(t).
		Status(http.StatusOK).
		Cookies(apitest.Cookie"ABC").Value("12345")).
		CookiePresent("Session-Token").
		CookieNotPresent("XXX").
		Cookies(
			apitest.Cookie("ABC").Value("12345"),
			apitest.Cookie("DEF").Value("67890"),
		).
		End()
}

Assert headers

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		Headers(map[string]string{"ABC": "12345"}).
		End()
}

Mocking external http calls

var getUser = apitest.NewMock().
	Get("/user/12345").
	RespondWith().
	Body(`{"name": "jon", "id": "1234"}`).
	Status(http.StatusOK).
	End()

var getPreferences = apitest.NewMock().
	Get("/preferences/12345").
	RespondWith().
	Body(`{"is_contactable": true}`).
	Status(http.StatusOK).
	End()

func TestApi(t *testing.T) {
	apitest.New().
		Mocks(getUser, getPreferences).
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		Body(`{"name": "jon", "id": "1234"}`).
		End()
}

Generating sequence diagrams from tests


func TestApi(t *testing.T) {
	apitest.New().
		Report(apitest.SequenceDiagram()).
		Mocks(getUser, getPreferences).
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		Body(`{"name": "jon", "id": "1234"}`).
		End()
}

It is possible to override the default storage location by passing the formatter instance Report(apitest.NewSequenceDiagramFormatter(".sequence-diagrams")). You can bring your own formatter too if you want to produce custom output. By default a sequence diagram is rendered on a html page. See the demo

Debugging http requests and responses generated by api test and any mocks

func TestApi(t *testing.T) {
	apitest.New().
		Debug().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Provide basic auth in the request

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		BasicAuth("username", "password").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Provide cookies in the request

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Cookies(apitest.Cookie("ABC").Value("12345")).
		Expect(t).
		Status(http.StatusOK).
		End()
}

Provide headers in the request

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Delete("/hello").
		Headers(map[string]string{"My-Header": "12345"}).
		Expect(t).
		Status(http.StatusOK).
		End()
}

Provide query parameters in the request

Query, QueryParams and QueryCollection can all be used in combination

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		QueryParams(map[string]string{"a": "1", "b": "2"}).
		Query("c", "d").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Providing {"a": {"b", "c", "d"} results in parameters encoded as a=b&a=c&a=d. QueryCollection can be used in combination with Query

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		QueryCollection(map[string][]string{"a": {"b", "c", "d"}}).
		Expect(t).
		Status(http.StatusOK).
		End()
}

Provide a url encoded form body in the request

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Post("/hello").
		FormData("a", "1").
		FormData("b", "2").
		FormData("b", "3").
		FormData("c", "4", "5", "6").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Capture the request and response data

func TestApi(t *testing.T) {
	apitest.New().
		Observe(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) {
			// do something with res and req
		}).
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Intercept the request

This is useful for mutating the request before it is sent to the system under test.

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Intercept(func(req *http.Request) {
			req.URL.RawQuery = "a[]=xxx&a[]=yyy"
		}).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Contributing

View the contributing guide.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].