A clipboard-based mocking framework for Go that gets out of your way.

Overview

logo

Build Status Coverage Status Go Report Card Latest version Go Documentation License

A clipboard-based mocking framework for Go that gets out of your way.

This tool has been built with inspiration lovingly taken from Moq, and fuelled by the frustration of using gomock.

Key ideas:

  • Invisible: No need to introduce dependencies or //go:generate directives in your codebase.
  • Integration friendly: Easy to integrate in your workflow, regardless of editor.
  • File/package agnostic: mokku doesn't care where exactly your code lives on your system or even whether it compiles yet.

Installation

$ go get github.com/kinbiko/mokku/cmd/mokku

Usage

# Copy the interface
$ mokku
# Paste the mock

That's it. Below is an example of how to use mokku within vim.

demo

Using the generated code

If you have been writing your own mocks or if you're familiar with Moq then the usage will look very familiar to you:

func TestRegisterUser(t *testing.T) {
	var (
		got = ""
		exp = "kinbiko"
	)

	mock := &UserRepositoryMock{
		CreateFunc: func(userName string) error {
			got = userName
			return nil
		},
	}

	RegisterUser(exp, mock)

	if got != exp {
		t.Errorf("expected user name '%s' but got '%s'", exp, got)
	}
}

func RegisterUser(userName string, repo UserRepository) {
	// ... Code that includes a call to 'repo.Create(userName)'
}

Defining Custom Templates

You can also define your own custom template to use for your mocks, by defining MOKKU_TEMPLATE_PATH that is the path to a file containing a Go text template, that uses the same variables found in the default template:

const defaultTemplate = `
type {{.TypeName}}Mock struct { {{ range .Methods }}
	{{.Name}}Func func{{.Signature}}{{ end }}
}
{{if .Methods }}{{$typeName := .TypeName}}
{{range $val := .Methods}}func (m *{{$typeName}}Mock) {{$val.Name}}{{$val.Signature}} {
	if m.{{$val.Name}}Func == nil {
		panic("unexpected call to {{$val.Name}}")
	}
	{{if $val.HasReturn}}return {{ end }}m.{{$val.Name}}Func{{$val.OrderedParams}}
}
{{ end }}{{ end }}`

See the GoDocs for a more detailed explanation of the template variables.

Contributing

Please raise an issue to discuss any changes you'd like to make to this project. If you wish to contribute, but need some ideas, please check out the GitHub project for this repository.

Gratitude

This project is has been made possible thanks to my employer who let me work on this project during Mercari Hack Week.

Comments
  • add customize template feature

    add customize template feature

    Background

    Sometimes I want to use mock with other format to follow existing code base.

    What

    • add templates package

    How to use customize template

    1. add a new file under templates package like default.go
    2. build
    3. run mokku with specifing template name in command line argument like ./mokku -t mytemplate
    opened by cloverrose 5
  • Pointer return values are missing the *

    Pointer return values are missing the *

    Given:

    type O11y interface {
    	Wrap(ctx context.Context, err error, args ...interface{}) *bugsnag.Error
    }
    

    Got:

    type O11yMock struct {
    	WrapFunc     func(ctx context.Context, err error, args ...interface{}) bugsnag.Error
    }
    
    func (m *O11yMock) Wrap(ctx context.Context, err error, args ...interface{}) bugsnag.Error {
    	if m.WrapFunc == nil {
    		panic("unexpected call to Wrap")
    	}
    	return m.WrapFunc(ctx, err, args...)
    }
    

    the * in *bugsnag.Error is missing.

    bug good first issue 
    opened by kinbiko 1
  • feature: support template load feature

    feature: support template load feature

    WHAT

    Currently, template is fixed and built in the mokku binary. However, people want to follow their rule of project, policy, preferable, and so on. This suggestion is to support loading the template from the given environment variable.

    I supposed to use with .envrc etc.

    opened by yanolab 1
  • trailing comma causes error

    trailing comma causes error

    This Add method has trailing comma in parameters part.

    type Calculator interface {
    	Add(a int,
    		b int,
    	) int
    }
    

    It causes error like this.

    10:30: expected statement, found ')' (and 1 more errors)
    Usage:
    1. Copy the interface you want to mock
    2. Run 'mokku'
    3. Paste the mocked implementation that has been written to your clipboard
    
    bug good first issue 
    opened by cloverrose 1
  • Document how to integrate with vim

    Document how to integrate with vim

    Document the key binding to put in your .vimrc that is required to put the mock representation of the interface under the cursor in the default register by hitting (for example) <leader>m.

    documentation good first issue 
    opened by kinbiko 1
  • fix: allow trailing comma in method signature

    fix: allow trailing comma in method signature

    Allow for trailing commas in interface method signatures.

    Until this change, this will fail as it adds an excessive ) character, which cannot be processed.

    Closes #25.

    Checklist

    • [x] I have done a self-review of the PR.
    opened by kinbiko 0
  • Repo cleanup and consistency

    Repo cleanup and consistency

    Setting up the repository

    This document serves as both a list of all the rules and steps to set up a very good open source Go project, and also the issue contents of the GitHub issue generated by github.com/kinbiko/go-template's astroturf.sh script that automates a bunch of these very steps.

    CI

    • [x] Builds against one of the 2 latest Go versions
    • [x] Has golangci-lint v1.45.2 passing
    • [x] Runs tests with the race detector
    • [x] Runs integration tests, if applicable
    • [x] Reports coverage to coveralls
    • [x] Code scanning with CodeQL

    Community Standards

    • [x] Description w/ tags
    • [x] README
    • [x] Code of conduct
    • [x] Contributing guideline
    • [x] License
    • [x] Issue template(s)
    • [x] Pull request template
    • [x] CODEOWNERS

    GitHub settings

    • [x] Wiki pages disabled
    • [x] Sponsorship enabled
    • [x] Projects disabled (my OSS work is managed in a central project board)
    • [x] GitHub archive program enabled
    • [x] Discussions disabled
    • [x] Merge commits disabled
    • [x] Squash merging enabled
    • [x] Rebase merging disabled
    • [x] Suggest updating branches enabled
    • [x] Auto-merge disabled
    • [x] Auto-delete head branches enabled
    • [x] Limit "approve" or "request changes" to users with explicit permissions
    • [x] Default branch is main, with the following branch protection rules enabled (everything else disabled):
      • [x] Require PRs before merging (no approvals required, don't dismiss PR approvals on new commits, don't require codeowner review)
      • [x] Linear history enabled (assumption: only enabling squash merges globally means linear history in default branch)
    • [x] Allow kinbiko and select non-kinbiko actions only:
      • [x] Allow actions created by GitHub enabled
      • [x] Allow actions by Marketplace verified creators enabled
      • [x] shogo82148/[email protected] added as allowed action
    • [x] Require approval before running actions for first-time contributors
    • [x] GitHub actions approving PRs disabled
    • [x] Dependabot alerts enabled for security vulns
    • [x] Dependabot updates enabled for security vulns
    • [x] Code scanning (CodeQL) enabled
    • [x] Consistent labels:
      • bug
      • dependencies
      • documentation
      • enhancement
      • good first issue
      • help wanted
      • question

    README

    • [x] Has tags:
      • [x] Build status
      • [x] Coverage percentage
      • [x] Go report link
      • [x] Latest version
      • [x] Godoc with link to pkg.go.dev
      • [x] License tag
    • [x] Explains the why and then the what.
    • [x] Usage information incl any installation guidelines
    • [x] Link to docs
    opened by kinbiko 0
  • GitHub templates

    GitHub templates

    ISSUE_TEMPLATE.md

    Should provide a template for how bug reports should be structured. Should be as small as possible but include the following:

    • Indication that the template is for bug reports only, and can be ignored for other types of issues (e.g. ideas, missing docs etc.).
    • H2 headers for 'What I did', 'What I expected', 'What happened', 'Suggestions'. Suggestions are optional.
    • Whether or not you're interested in addressing the bug yourself.
    • HTML comments containing instructions for adding labels.

    PULL_REQUEST_TEMPLATE.md

    Should include a reminder to create/show interest in an issue before raising a pull request, and add a link to the issue within the pull request description.

    Code changes

    Once the issue template has been set up then we should include a link to create a new issue in the error messages in the case of a failed mock generation.

    good first issue 
    opened by kinbiko 0
  • [feat] Update public signature to permit config

    [feat] Update public signature to permit config

    In the future mokku is likely to support different options (e.g. whether or not to include godocs on the generated type, make mocks safe for concurrent access, whether or not to store the arguments per call to a mocked method, etc.). In order to not having to break backwards compatibility (even before v1.x.x) this commit identifies the desired signature upfront.

    opened by kinbiko 0
  • Document how to integrate with Goland

    Document how to integrate with Goland

    Document (in the README) how to integrate mokku with goland. If there's an even more convenient method of shelling out and copying, e.g. binding shelling out to run 'mokku' to a key binding, then that's preferable.

    documentation good first issue 
    opened by kinbiko 0
  • Improve error messages

    Improve error messages

    Right now the error messages are directed to the developer and not the end user. The error messages should be re-written to be actionable by the user.

    enhancement good first issue 
    opened by kinbiko 0
  • Missing parameter names in interface methods

    Missing parameter names in interface methods

    Did

    Copied the following struct:

    type foobar interface {
        baz(context.Context, int)
    }
    

    and ran mokku, and pasted the result.

    Expected

    A mock struct that compiles.

    Got

    A compile error, because the resulting mocked method attempts to pass context as a parameter to the underlying Func.

    Suggestion

    In the case that parameters are not named, we should create a dummy variable name. a,b, etc is probably fine for unnamed parameters. If users have more than 26 variable names then, well... there are bigger design issues at hand.

    bug good first issue 
    opened by kinbiko 0
Releases(v0.2.0)
  • v0.2.0(Aug 7, 2020)

    🚀 New feature: Custom mock templates as defined by a template file identified with MOKKU_TEMPLATE_PATH. Now each project can define their own mock style instead of falling on the default style provided by mokku. Thanks to @cloverrose (#28) and @yanolab (#29) for proposing and providing implementations for this feature.

    Also includes a bugfix for pointer args an return values.

    Source code(tar.gz)
    Source code(zip)
Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕

testza ?? Testza is like pizza for Go - you could life without it, but why should you? Get The Module | Documentation | Contributing | Code of Conduct

Marvin Wendt 409 Dec 10, 2022
Go Interface Mocking Tool

Charlatan Percolate's Go Interface Mocking Tool. Please read our introductory blog post. Installation go get github.com/percolate/charlatan Usage c

Percolate 199 Nov 3, 2022
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

gock Versatile HTTP mocking made easy in Go that works with any net/http based stdlib implementation. Heavily inspired by nock. There is also its Pyth

Tom 1.8k Jan 4, 2023
HTTP mocking for Golang

httpmock Easy mocking of http responses from external resources. Install Currently supports Go 1.7 - 1.15. v1 branch has to be used instead of master.

Jared Morse 1.6k Jan 3, 2023
HTTP mocking to test API services for chaos scenarios

GAOS HTTP mocking to test API services for chaos scenarios Gaos, can create and provide custom mock restful services via using your fully-customizable

Trendyol Open Source 211 Nov 5, 2022
Lightweight HTTP mocking in Go (aka golang)

httpmock This library builds on Go's built-in httptest library, adding a more mockable interface that can be used easily with other mocking tools like

null 79 Dec 16, 2022
A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Americanas Go 6 Dec 19, 2021
Interface mocking tool for go generate

Interface mocking tool for go generate. What is Moq? Moq is a tool that generates a struct from any interface. The struct can be used in test code as

Mat Ryer 1.5k Jan 5, 2023
A faster, simpler way to drive browsers supporting the Chrome DevTools Protocol.

About chromedp Package chromedp is a faster, simpler way to drive browsers supporting the Chrome DevTools Protocol in Go without external dependencies

Chrome DevTools Protocol clients and tools for Go 8.5k Jan 4, 2023
Easier way to unit test terraform

Unit testing terraform (WIP) Disclaimer Currently, the only way to compare values is using JSON query path and all types are strings. want := terraf

Thiago Nache Carvalho 51 Aug 16, 2022
A faster, simpler way to drive browsers supporting the Chrome DevTools Protocol.

About chromedp Package chromedp is a faster, simpler way to drive browsers supporting the Chrome DevTools Protocol in Go without external dependencies

Chrome DevTools Protocol clients and tools for Go 8.5k Dec 28, 2022
CLI tool to mock TCP connections. You can use it with Detox, Cypress or any other framework to automatically mock your backend or database.

Falso It is a CLI that allows you to mock requests/responses between you and any server without any configuration or previous knowledge about how it w

Sorin 3 Sep 23, 2022
A bytecode-based virtual machine to implement scripting/filtering support in your golang project.

eval-filter Implementation Scripting Facilities Types Built-In Functions Conditionals Loops Functions Case/Switch Use Cases Security Denial of service

Steve Kemp 93 Jan 8, 2023
Check your internet speed right from your terminal. Built on GOlang using chromedp

adhocore/fast A GO lang command line tool to check internet speed right from the terminal. Uses fast.com through headless chrome. Prerequistie Chrome

Jitendra Adhikari 71 Dec 26, 2022
End to end functional test and automation framework

Declarative end to end functional testing (endly) This library is compatible with Go 1.12+ Please refer to CHANGELOG.md if you encounter breaking chan

Viant, Inc 231 Jan 6, 2023
Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Shunsuke Suzuki 17 Sep 27, 2022
API testing framework inspired by frisby-js

frisby REST API testing framework inspired by frisby-js, written in Go Proposals I'm starting to work on frisby again with the following ideas: Read s

_Hofstadter 274 Sep 27, 2022
http integration test framework

go-hit hit is an http integration test framework written in golang. It is designed to be flexible as possible, but to keep a simple to use interface f

Tobias Salzmann 157 Dec 29, 2022
Minimal and Beautiful Go testing framework

Goblin A Mocha like BDD testing framework written in Go that requires no additional dependencies. Requires no extensive documentation nor complicated

null 869 Dec 25, 2022