goraphql_mock_server

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2024 License: Apache-2.0 Imports: 8 Imported by: 0

README

G(o)raphQL Mock Server

GraphQL Mock server, highly based in github.com/getoutreach/goql/graphql_test.

Quickguide

  1. Start a new server:
	s := goraphql_mock_server.New()
	defer s.Close()
  1. Register the desired operations:
	s.RegisterQuery("ListFoos", goraphql_mock_server.SimpleMockedRequest{
		StringResponse: goraphql_mock_server.StringResponse(`{
			"ListFoos": {
				"foo": 123
			}
		}`),
		KeyOnlyVariables: goraphql_mock_server.KeyOnlyVariables{"foo", "num"},
	})
  1. Send requests with your preferred GraphQL client to s.URL().

Customizing responses

A request must implement the interface goraphql_mock_server.MockedRequest. In most cases, simply embedding one of the partial implementations (for example, goraphql_mock_server.StringResponse and goraphql_mock_server.KeyOnlyVariables) should be enough in most cases.

To match variables exactly (e.g., to mock pagination), goraphql_mock_server.ExactVariables may be used, however using a custom type for Variables that implementations goraphql_mock_server.VariableDecoder is highly advised! Otherwise, variables may unexpectedly get mismatched depending on how Go decodes values (and, for example, a number in a map would end up getting decoded as a float64).

Changes from graphql_test

  • Currently, only query is supported
  • Variables may be matched identically
  • The response may be specified as a string

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ExactVariables

type ExactVariables struct {
	// An object that should match the request's variables.
	// If this object implements VariableDecoder,
	// then Variable() is called on the request's variables
	// to convert it to the same type as this object before comparing them.
	Variables any
}

ExactVariables implements a CompareVariables() that checks if the variable's matches exactly whatever was provided, including the type of each variable.

func (ExactVariables) CompareVariables

func (ev ExactVariables) CompareVariables(reqVar map[string]any) bool

CompareVariables partially implements MockedRequest for ExactVariables.

type KeyOnlyVariables

type KeyOnlyVariables []string

KeyOnlyVariables implements a CompareVariables() that checks if the variable's keys exactly matches this object.

func (KeyOnlyVariables) CompareVariables

func (kv KeyOnlyVariables) CompareVariables(got map[string]any) bool

CompareVariables partially implements MockedRequest for KeyOnlyVariables.

type MockedRequest

type MockedRequest interface {
	// CompareVariables validates if the variables provided by the GraphQL client
	// matches this mocked request.
	CompareVariables(v map[string]any) bool

	// Response returns the object that should be sent as the response to this request.
	Response() any
}

MockedRequest manages validating whether a mocked request should be returned and generating its response.

type NoVariable

type NoVariable struct{}

KeyOnlyVariables implements a CompareVariables() that checks that there are no variables in the payload.

func (NoVariable) CompareVariables

func (nv NoVariable) CompareVariables(got map[string]any) bool

CompareVariables partially implements MockedRequest for NoVariable.

type RawResponse

type RawResponse struct {
	Payload any
}

RawResponse implements a Response() that returns exactly whatever was provided to it.

func (RawResponse) Response

func (r RawResponse) Response() any

Response partially implements MockedRequest for RawResponse.

type Request

type Request struct {
	Query     string         `json:"query"`
	Variables map[string]any `json:"variables"`
}

Request maps the received GraphQL request into a go structure.

type Response

type Response struct {
	Data   any             `json:"data"`
	Errors []ResponseError `json:"errors,omitempty"`
}

ResponseError maps a successful response into a go structure.

type ResponseError

type ResponseError struct {
	Message    string   `json:"message"`
	Path       []string `json:"path"`
	Extensions any      `json:"extensions"`
}

ResponseError maps an error response into a go structure.

type Server

type Server interface {
	// Close closes the underlying http server.
	Close()

	// URL returns the address that a client may use to communicate with the mock server.
	URL() string

	// Client returns an initialized HTTP client configured to accept the server's certificates
	// if running with TLS enabled.
	Client() *http.Client

	// RegisterQuery registers a new query with a specific response.
	//
	// identifier is matched with a simple strings.Contains.
	// So, considering the query:
	//
	// 	query {
	// 		ListObjects(page: $page) {
	// 			data {
	// 				id
	// 			}
	// 		}
	// 	}
	//
	// "ListObjects" would be a valid identifier, as well as "ListObjects(page: $page)".
	// Just be sure to match as much as needed to uniquely identify the request.
	//
	// This may be called multiple types with the same identifier,
	// though note that mocked requests are checked in the same order they were registered.
	// So, the most generic mocked request (e.g., one that embeds a KeyOnlyVariables
	// and that matches the query only on the operation)
	// should be registered last.
	RegisterQuery(identifier string, mock MockedRequest)
}

Server manages a mock GraphQL server.

func New

func New(opts ...ServerOptions) Server

New starts a new mocked GraphQL server.

To communicate with it, either use the pre-initialized client (retrieved by calling Client()) or just use the address returned by URL(). Mocked requests must be registered by calling RegisterQuery().

Be sure to call Close() when done with the server!

type ServerOptions

type ServerOptions func(s *server)

ServerOptions defines a function used to configure the server.

func WithAddress

func WithAddress(ip string, port uint16, ipv6 bool) ServerOptions

WithAddress defines a specific address which the mock server should listen on.

func WithTLS

func WithTLS() ServerOptions

WithTLS causes the mock server to start with TLS enabled.

type SimpleMockedRequest

type SimpleMockedRequest struct {
	StringResponse
	KeyOnlyVariables
}

SimpleMockedRequest implements MockedRequest using a hard-coded payload and comparing the key of the provided variables.

type StringResponse

type StringResponse string

StringResponse implements a Response() that returns this string encoded as an object.

func (StringResponse) Response

func (s StringResponse) Response() any

Response partially implements MockedRequest for StringResponse.

type VariableDecoder

type VariableDecoder interface {
	// Variable tries to convert v, the generic map of variables,
	// into the decoder's type.
	Variable(v map[string]any) (any, bool)
}

VariableDecoder converts a generic map of variables to the decoder's type, so the expected variables for a mocked request may be more easily compared.

Jump to

Keyboard shortcuts

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