mockaroo

package module
v0.0.1-alpha Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2021 License: MIT Imports: 16 Imported by: 0

README

Mock-a-(roo)🦘

comprehensive HTTP/HTTPS interface mocking tool for all your development and testing needs!

  • supports complex request matching (path/query/headers/verb)
  • mock response can be fully templated; with request body/query/header params in template context
  • config language is hashicorp HCL, human readable with single line and multiline comments, perfect for documenting your interface
  • mock complex HTTP API and send the mockaroo file to client developer for testing; communicate intent clearly; document your API
  • run integration tests locally with ease
  • add delays to mock real world response times
  • full support for generating fake data using https://github.com/brianvoe/gofakeit
  • support for HTTPS in case you need it

Getting Started: Mock HTTP Server in under a minute

  • Step 1: download mockaroo binary
  • Step 2: add this content to a file mock.hcl
server {
    listen_addr = "localhost:5000"
    mock "hello_world" {
        request {
            path = "/hello/{userName}"
            verb = "GET"
        }
        response {
            body = <<EOF
            hello world {{.PathVariable "userName"}}
            EOF
        }
    }
}
  • Step 3: start the mockaroo server from your terminal
mockaroo -conf ./mock.hcl
  • Step 4: curl away
curl "http://localhost:5000/hello/buddy"

That's it; read the complete documentation for all the features available for complex mocking

Why ?

There are several reasons why I always felt the need for something like mockaroo in my local dev box, these are some of them

  • I am experimenting with a new API and want to send a live working version with use-cases to my teammates, simply publish a mock file
  • I am a UX developer who wants to get started on UI work and wants to communicate my API needs to the back end developer, with clear documentation
  • I wand to publish API documentation that is "ALIVE" simply download mock file and code to it
  • Publish integration test contract that can be run and verified locally in the dev box
  • Test my client code against exhaustive fake data that almost looks real
  • I want to test my service locally but the service I am using does not run locally
  • I can check-in my mock HCL file with code so that other developers can contribute to the use cases and enhance the tests

... and many more, if any of these reasons resonate with you then mockaroo might be a good fit for you

Show me the goods

Just to show that mockaroo is a great fit for mocking needs I have created a samples folder https://github.com/subranag/mockaroo/tree/master/sample which contains several detailed examples I will keep adding to the list in the future, please check it out

Acknowledgments

This project would have not been possible without these two awesome projects

Documentation

detailed documentation is available here, the sample folder contains som really cool examples from top service providers

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	ServerConfig *ServerConf `hcl:"server,block"`
	// contains filtered or unexported fields
}

Config is the root config object that holds entire mockaroo config

func LoadConfig

func LoadConfig(filePath *string) (*Config, error)

LoadConfig loads the given config file in path and returns a pointed to Config object if successful other wise returns a InvalidConfigFile error

func (*Config) String

func (c *Config) String() string

type Delay

type Delay struct {
	MaxMillis int64 `hcl:"max_millis"`
	MinMillis int64 `hcl:"min_millis"`
}

type InvalidConfigFile

type InvalidConfigFile struct {
	// contains filtered or unexported fields
}

InvalidConfigFile error is raised when given input hcl file fails validation

func (*InvalidConfigFile) Error

func (e *InvalidConfigFile) Error() string

type Mock

type Mock struct {
	Name     string    `hcl:"name,label"`
	Request  *Request  `hcl:"request,block"`
	Response *Response `hcl:"response,block"`
}

Mock matches a specific request and lays out how to generate a response to the request

type MockServer

type MockServer interface {
	//Start starts the mock server and if the server cannot be started
	//returns an error
	Start() error
}

MockServer encapsulates a full mockaroo server

func NewServer

func NewServer(conf *Config) MockServer

NewServer creates a mock server with the given configuration

type Request

type Request struct {
	Path           *string `hcl:"path"`
	NormalizedPath string
	PathPrefix     bool              // should this path be a prefix formulated from the Path
	Verb           *string           `hcl:"verb"`
	Headers        map[string]string `hcl:"headers,optional"` // request match headers
	Queries        map[string]string `hcl:"queries,optional"` // query match headers
}

Request encapsulates a mock request with all information to match a specific request

type RequestLog

type RequestLog struct {
	RequestUri    *string     `json:"uri"`
	Timestamp     *time.Time  `json:"request_time"`
	Headers       http.Header `json:"headers"`
	Method        *string     `json:"method"`
	ContentLength int64       `json:"content_length"`
	RemoteAddr    *string     `json:"remote_addr"`
	QueryValues   *url.Values `json:"query_params"`
}

type Response

type Response struct {
	Status       int               `hcl:"status,optional"`
	ResponseBody *string           `hcl:"body"`
	ResponseFile *string           `hcl:"file"`
	Headers      map[string]string `hcl:"headers,optional"`
	Delay        *Delay            `hcl:"delay,block"`
	Template     *template.Template
	Content      []byte
}

Response encapsulates a complete mock response to a mock Request

type ServerConf

type ServerConf struct {
	ListenAddr       *string `hcl:"listen_addr"`
	SnakeOilCertPath *string `hcl:"snake_oil_cert"`
	SnakeOilKeyPath  *string `hcl:"snake_oil_key"`
	RequestLogPath   *string `hcl:"request_log_path"`
	Mocks            []*Mock `hcl:"mock,block"`
	Mode             ServerMode
}

ServerConf mockaroo server configuration

type ServerMode

type ServerMode int
const (
	HTTP ServerMode = iota
	HTTPS
)

type TemplateContext

type TemplateContext struct {
	//Method is the HTTP method for the request (GET, POST, PUT, etc.)
	Method *string

	//Protocol HTTP 1.1/2
	Protocol *string

	//Host to which the request came
	Host *string

	//RemoteAddr from which the request came
	RemoteAddr *string

	//Headers are key value pairs from request headers
	Headers http.Header

	//Form is all the form data from the request including Query params
	Form url.Values

	//JsonBody will be non nil if the request body can be parsed as JSON
	JsonBody map[string]interface{}

	//PathVars is the path variables captured as a part of the path
	PathVars map[string]string

	//Fake contains the context to fake data from "github.com/brianvoe/gofakeit"
	Fake *fakeit.Faker
	// contains filtered or unexported fields
}

func NewTemplateContext

func NewTemplateContext(req *http.Request) *TemplateContext

NewTemplateContext returns a pointer to TemplateContext

func (*TemplateContext) NewUUID

func (tc *TemplateContext) NewUUID() string

NewUUID generates a new pseudo random UUID seeded by the same constance value

func (*TemplateContext) PathVariable

func (tc *TemplateContext) PathVariable(key string) string

func (*TemplateContext) RandomFloat

func (tc *TemplateContext) RandomFloat(min, max float32) float32

RandomFloat generates a new pseudo random float32 between min and max seeded by the same constance value

func (*TemplateContext) RandomInt

func (tc *TemplateContext) RandomInt(min, max int) int

RandomInt generates a new pseudo random int between min and max seeded by the same constance value

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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