Automatically generate Go test boilerplate from your source code.

Overview

gotests License godoc Build Status Coverage Status codebeat badge Go Report Card

gotests makes writing Go tests easy. It's a Golang commandline tool that generates table driven tests based on its target source files' function and method signatures. Any new dependencies in the test files are automatically imported.

Demo

The following shows gotests in action using the official Sublime Text 3 plugin. Plugins also exist for Emacs, also Emacs, Vim, Atom Editor, Visual Studio Code, and IntelliJ Goland.

demo

Installation

Minimum Go version: Go 1.6

Use go get to install and update:

$ go get -u github.com/cweill/gotests/...

Usage

From the commandline, gotests can generate Go tests for specific source files or an entire directory. By default, it prints its output to stdout.

$ gotests [options] PATH ...

Available options:

  -all                  generate tests for all functions and methods

  -excl                 regexp. generate tests for functions and methods that don't
                         match. Takes precedence over -only, -exported, and -all

  -exported             generate tests for exported functions and methods. Takes
                         precedence over -only and -all

  -i                    print test inputs in error messages

  -only                 regexp. generate tests for functions and methods that match only.
                         Takes precedence over -all

  -nosubtests           disable subtest generation when >= Go 1.7

  -parallel             enable parallel subtest generation when >= Go 1.7.

  -w                    write output to (test) files instead of stdout

  -template_dir         Path to a directory containing custom test code templates. Takes
                         precedence over -template. This can also be set via environment
                         variable GOTESTS_TEMPLATE_DIR

  -template             Specify custom test code templates, e.g. testify. This can also
                         be set via environment variable GOTESTS_TEMPLATE

  -template_params_file read external parameters to template by json with file

  -template_params      read external parameters to template by json with stdin

Contributions

Contributing guidelines are in CONTRIBUTING.md.

License

gotests is released under the Apache 2.0 License.

Issues
  • Add subtests support to template.

    Add subtests support to template.

    Used an if block and duplicated because of wanting to keep the tabbing consistent. There might be some way to make it so you don't need to duplicate?

    enhancement 
    opened by itsjamie 26
  • Support some comments before 'package'

    Support some comments before 'package'

    Support some comments before 'package', such as License comment.

    I don't know whether the correct way, but can leave the license comment and support the empty line before the 'package' token.Pos. It may be ugly implementation. Please point out if there is a mistake.

    Fixes https://github.com/cweill/gotests/issues/37

    opened by zchee 15
  • Remove .IsNaked check in function template.

    Remove .IsNaked check in function template.

    If the .IsNaked check is in place, the generated code will not compile when the tests are generated for files containing functions which neither accept arguments nor return values (e.g., main()). See Issue 32.

    opened by adamdrake 13
  • Add ability to set a custom template path

    Add ability to set a custom template path

    I have added the ability to use custom templates for generating tests. The templates should just be a modified copy of the ones provided in the library. This is useful for us as we would only like to make a few minor modifications for our specific use. There was also demand for it in issues like #5

    -template accepts a path to a template folder that is used to generate the test. Allowing people to use their own templates when generating tests

    Any tips and feedback welcome!

    enhancement 
    opened by meyskens 12
  • Go 1.7 install failed

    Go 1.7 install failed

    go get -u -v github.com/cweill/gotests/... github.com/cweill/gotests (download)

    cd /Users/Project/go/src/github.com/cweill/gotests; git pull --ff-only

    There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details.

    git pull <remote> <branch>
    

    If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> master
    

    package github.com/cweill/gotests/...: exit status 1

    opened by rh1nox 11
  • failing tests with Go 1.10

    failing tests with Go 1.10

    As the linked travis build demonstrates, the test TestGenerateTests fails with Go 1.10 due to changes to go fmt.

    Here's a breakdown of the issue:

    • gotests generates a test
    • the generated test is then formatted (using Go 1.10 fmt)
    • the formatted generated output is compared against the golden files which were formatted using an older version of Go
    • They don't match.

    The exact formatting problem lies in this block:

    screen shot 2018-03-19 at 18 24 21

    I'm still thinking about how to go about this in a clean way.

    testing 
    opened by jawher 11
  • add support for generating tests for functions defined in test files

    add support for generating tests for functions defined in test files

    It can be useful if you write some wrapper function in test file to simplify testing. For example I wrote function that is not pure. And for test it I wrote some wrapper that mock this function environment and call that function multiple times on series of input data. When I was try to generate table test for this wrapper function gotests wan't help me :smile: So I use dirty hack to do it - move wrapper function from test file and back. And now I want better solution like in this PR.

    enhancement 
    opened by s-kostyaev 11
  • Add version command

    Add version command

    Adding version command to show current version of gotests installed.

    NOTE Had issue with tests failing intermittently locally (even on develop). Not sure what the issue, please let me know if this is a known issue or something I should make another ticket for. This only appears to be happening for the 1.16.x build.

    #133

    cla: yes 
    opened by teddylear 10
  • generate tests failing after upgraded to go1.7

    generate tests failing after upgraded to go1.7

    Hi, I'm getting the below error while generating tests after upgraded to go1.7. If anything is missing, please help..

    panic: inconsistent import: func errors.New(text string) error previously imported as: func errors.New(text string) error [recovered] panic: inconsistent import: func errors.New(text string) error previously imported as: func errors.New(text string) error

    goroutine 34 [running]: panic(0x28f460, 0xc4204c94c0) /usr/local/go/src/runtime/panic.go:500 +0x1a1 go/types.(_Checker).handleBailout(0xc4202861c0, 0xc4202f5a18) /usr/local/go/src/go/types/check.go:213 +0xae panic(0x28f460, 0xc4204c94c0) /usr/local/go/src/runtime/panic.go:458 +0x243 go/internal/gcimporter.(_importer).declare(0xc42036f380, 0x49aba0, 0xc4204fdf90) /usr/local/go/src/go/internal/gcimporter/bimport.go:175 +0x17c go/internal/gcimporter.(_importer).obj(0xc42036f380, 0xfffffffffffffffb) /usr/local/go/src/go/internal/gcimporter/bimport.go:203 +0x4a2 go/internal/gcimporter.BImportData(0xc420268690, 0xc4204a9000, 0xb51, 0xe00, 0xc4202ec999, 0x6, 0x0, 0x6, 0xc42005c820, 0xc42005c8f0) /usr/local/go/src/go/internal/gcimporter/bimport.go:88 +0x390 go/internal/gcimporter.Import(0xc420268690, 0xc4202ec999, 0x6, 0xc420288180, 0x3f, 0xc420146a00, 0x0, 0x0) /usr/local/go/src/go/internal/gcimporter/gcimporter.go:166 +0x551 go/importer.gcimports.ImportFrom(0xc420268690, 0xc4202ec999, 0x6, 0xc420288180, 0x3f, 0x0, 0x1, 0x2, 0x0) /usr/local/go/src/go/importer/importer.go:70 +0x67 go/types.(_Checker).collectObjects(0xc4202861c0) /usr/local/go/src/go/types/resolver.go:191 +0x826 go/types.(_Checker).checkFiles(0xc4202861c0, 0xc4204b6300, 0x16, 0x20, 0x0, 0x0) /usr/local/go/src/go/types/check.go:225 +0xaa go/types.(_Checker).Files(0xc4202861c0, 0xc4204b6300, 0x16, 0x20, 0xc4204d0b70, 0xc4202f5a90) /usr/local/go/src/go/types/check.go:218 +0x49 go/types.(_Config).Check(0xc4204cdac0, 0x0, 0x0, 0xc42007f040, 0xc4204b6300, 0x16, 0x20, 0xc4204d4320, 0x0, 0x3, ...) /usr/local/go/src/go/types/api.go:344 +0x1a3 github.com/cweill/gotests/internal/goparser.(_Parser).parseTypes(0xc4202f5eb8, 0xc42007f040, 0xc4204b6300, 0x16, 0x20, 0xc4204a1e00, 0x8) /Users/cfs426/workspace/src/github.com/cweill/gotests/internal/goparser/goparser.go:119 +0x18c github.com/cweill/gotests/internal/goparser.(_Parser).parseFunctions(0xc4202f5eb8, 0xc42007f040, 0xc4200b1080, 0xc4204b6300, 0x16, 0x20, 0x1e98, 0x16, 0x20) /Users/cfs426/workspace/src/github.com/cweill/gotests/internal/goparser/goparser.go:96 +0x74 github.com/cweill/gotests/internal/goparser.(_Parser).Parse(0xc4202f5eb8, 0xc4202880c0, 0x5b, 0xc42025a600, 0x16, 0x20, 0xc420070d80, 0x20, 0x18) /Users/cfs426/workspace/src/github.com/cweill/gotests/internal/goparser/goparser.go:56 +0x2b9 github.com/cweill/gotests.generateTest(0xc4202880c0, 0x5b, 0xc42025a600, 0x16, 0x20, 0xc420230880, 0x0, 0x0, 0x0) /Users/cfs426/workspace/src/github.com/cweill/gotests/gotests.go:100 +0xc3 github.com/cweill/gotests.parallelize.func1(0xc42022a730, 0xc42025a600, 0x16, 0x20, 0xc420230880, 0xc4202896e0, 0xc4202880c0, 0x5b) /Users/cfs426/workspace/src/github.com/cweill/gotests/gotests.go:72 +0xd0 created by github.com/cweill/gotests.parallelize /Users/cfs426/workspace/src/github.com/cweill/gotests/gotests.go:74 +0x140

    bug 
    opened by sudheernayudu 9
  • Having tests as map vs slice

    Having tests as map vs slice

    I wonder if having maps instead of the slice is desired feature for gotests users. I made a simple implementation based on default and testify templates.

    Can be checked with next parameters:

    gotests -nosubtests -asmap -i   -only ^Func$  /path/demo.go
    gotests -asmap  -only  ^Func$  /path/demo.go
    gotests -parallel -only  ^Func$  /path/demo.go
    gotests -only ^Func$  /path/demo.go
    

    Benefits:

    • it wouldn't break current implementation if not provided (arg -asmap).
    • it makes tests random (as go maps iterated in random order)

    Cons:

    • asmap isn't the best name for argument, any ideas of better name?
    • tests, I need to write a lot of tests before creating PR, but that's OK, I can spend some time.
    enhancement 
    opened by butuzov 8
  • Rename test036.go to test036.go22

    Rename test036.go to test036.go22

    null

    cla: no 
    opened by sjfxy 1
  • Ability to exclude generated files

    Ability to exclude generated files

    Hello

    Would it possible to avoid generating tests for generated files ?

    The simplest ways for me would be to look for the regex ^// Code generated .* DO NOT EDIT.$
    documented here : https://pkg.go.dev/cmd/go/internal/generate.

    If you have recommendation of the best way to do it, I can try to propose a PR if you like.

    opened by marema31 0
  • Cannot see any mock sample data when generating tests

    Cannot see any mock sample data when generating tests

    Everytime i generate test cases ,it gives me same skeleton code like below wihtout adding any actual testing values in the code. May be I am missing something. Can somebody please advise.A bit urgent All test cases have comments " TODO: Add test cases." Does this package not support it ?

    Sample test code generated with this package

    func TestBit_Value(t *testing.T) { tests := []struct { name string b Bit want driver.Value wantErr bool }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.b.Value() if (err != nil) != tt.wantErr { t.Errorf("Bit.Value() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Bit.Value() = %v, want %v", got, tt.want) } }) } }

    opened by dev2021-ctrl 1
  • Use go-cmp instead of reflect.DeepEqual

    Use go-cmp instead of reflect.DeepEqual

    As discussed in https://github.com/cweill/gotests/pull/99, the branch had to be cleared from merge conflicts before go-cmp support could be integrated. That's what I did in this PR.

    cla: yes 
    opened by hslatman 12
  • template_params argument

    template_params argument

    What does template_params do and how to use it? I tried to understand, but it looks that it's just redundant in terms of the main package.

    Or is there some hidden magic I miss?

    question 
    opened by butuzov 4
  • Support for mocks in tests

    Support for mocks in tests

    Majority of the functions involve calls to functions from external packages which need to be mocked. Adding support for mocks can take gotests to the next level I believe.

    e.g. An example function and its generated test can look something like this (pseudocode)

    CODE

    package A
    
    import B
    
    func fA(in) out{
    	...
        resp := B.fB(p1, p2)
        ...
    }
    

    TEST

    package A
    
    import bmock
    
    func TestfA(t *testing.T) {
    	type mockB struct {
    		resp   // mock resp of B.fB
    		times  // number of times B.fB will be called
    	}
    	
    	testCases := []struct {
    		name
    		args
    		mockB 
    		want
    	} { // add testcases }
    
    	for _, tc := range testCases {
    		t.Run(tc.name, func(t *testing.T) {
    			gmc := gomock.NewController(t)
    			defer gmc.Finish()
    
    			bStub := bmock.NewMockService(t) // just an example, this is debatable
    			bstub.Expect().fB(gomock.Any(), gomock.Any()). // 2 params so 2 gomock.Any()
    					Times(tc.mockB.times).
    					Return(tc.mockB.resp)
    
    			...... // existing logic follows
    		})
    	}
    }
    

    I would first like to ask whether you have already thought about the feasibility of this idea. If you feel this is possible, I would love to work on this enhancement.

    enhancement 
    opened by chatrasen 2
  • No tests generated for my path

    No tests generated for my path

    I'm running the following expecting it to generate a test file as oppose to getting stdout /home/rob/go/bin/gotests -all -w /home/rob/Projects/Go/testme

    The first time it said Generated Test_main But it didn't create a test file. I ran the same command again but then it said No tests generated for /home/rob/Projects/Go/testme Subsequent commands give me No tests generated.

    There doesn't appear to be a file generated in any of the paths that i could find. Nor could it repeat the first Generated Test_

    I'm not using any of the plugins, i wish to use the command line to test this out but i'm not getting what i expect.

    Edited to add I found the tests in the folder (eg main_test) but they were not named as the cli output suggests, leaving the user confused as to what happened. Maybe make the cli output match what was created? If i already have a file main_test then the command will not create a file.

    opened by robtrooper 0
  • Add a -version flag to differentiate two gotests binaries

    Add a -version flag to differentiate two gotests binaries

    I have two setups, in one the -parallel option works just fine in vscode - it generates parallel test cases as it should. In the other it doesn't do anything (not reporting errors in custom flags is a problem in the vscode go plugin, which is not the issue here).

    Both were installed with go get -u github.com/cweill/gotests/... when in the $HOME directory within 15 minutes of each other.

    One installation looks like this (go version go1.14.3 darwin/amd64) - no -parallel option

    Usage of gotests:
      -all
        	generate tests for all functions and methods
      -excl string
        	regexp. generate tests for functions and methods that don't match. Takes precedence over -only, -exported, and -all
      -exported
        	generate tests for exported functions and methods. Takes precedence over -only and -all
      -i	print test inputs in error messages
      -nosubtests
        	disable generating tests using the Go 1.7 subtests feature
      -only string
        	regexp. generate tests for functions and methods that match only. Takes precedence over -all
      -template string
        	optional. Specify custom test code templates, e.g. testify
      -template_dir string
        	optional. Path to a directory containing custom test code templates. Takes precedence over -template
      -template_params string
        	read external parameters to template by json with stdin
      -template_params_file string
        	read external parameters to template by json with file
      -w	write output to (test) files instead of stdout
    

    The other like this (go version go1.13.8 linux/amd64) - -parallel found and works perfectly

    Usage of ./gotests:
      -all
        	generate tests for all functions and methods
      -excl string
        	regexp. generate tests for functions and methods that don't match. Takes precedence over -only, -exported, and -all
      -exported
        	generate tests for exported functions and methods. Takes precedence over -only and -all
      -i	print test inputs in error messages
      -nosubtests
        	disable generating tests using the Go 1.7 subtests feature
      -only string
        	regexp. generate tests for functions and methods that match only. Takes precedence over -all
      -parallel
        	enable generating parallel subtests
      -template string
        	optional. Specify custom test code templates, e.g. testify. This can also be set via environment variable GOTESTS_TEMPLATE
      -template_dir string
        	optional. Path to a directory containing custom test code templates. Takes precedence over -template. This can also be set via environment variable GOTESTS_TEMPLATE_DIR
      -template_params string
        	read external parameters to template by json with stdin
      -template_params_file string
        	read external parameters to template by json with file
      -w	write output to (test) files instead of stdout
    

    Took me a LONG while to figure out why vscode was generating parallel tests on one and not on the other... There is no way to differentiate the two installs except by manually comparing the help texts - which themselves only appear when giving a faulty flag. Just running gotests by itself gives the exact same defaults on both installations.

    It would be really useful to have a -version flag in gotests to debug these issues and maybe make it possible for plugins like the Go vscode plugin to determine if some options are available or not.

    Bonus question: why did both platforms and go versions get a completely different version of gotests?

    help wanted good first issue 
    opened by lepinkainen 6
  •  Support to automatically generate mock code

    Support to automatically generate mock code

    Since most of the time when we write cases we are writing mock data, I want to know if there are plans to integrate mock tools under gotests, such as gomonkey, convey, etc. When we use gotests to generate cases, we also generate mock sample code together. I am also doing secondary development based on your gotests tool to achieve this function.

    opened by ivanxwwu 1
  • Verify test package name when generating tests

    Verify test package name when generating tests

    I've noticed that when generating tests, they will generate as invalid if the *_test.go file uses the _test suffix in its package name (i.e.package *_test).

    bug 
    opened by SteelPhase 4
Releases(v1.6.0)
Owner
Charles Weill
Co-Author of google/nitroml, and tensorflow/adanet. AutoML Researcher @google.
Charles Weill
manage your mocks / run mockgen more quickly / mocks up-to-date checking

gomockhandler If you find any bugs or have feature requests, please feel free to create an issue. gomockhandler is handler of golang/mock, as the name

Kensei Nakada 39 Oct 20, 2021
A generic fuzzing and delta-debugging framework

Tavor Tavor (Sindarin for woodpecker) is a framework for easily implementing and using fuzzing and delta-debugging. Its EBNF-like notation allows you

Markus Zimmermann 233 Oct 1, 2021
Powerful mock generation tool for Go programming language

Summary Minimock generates mocks out of Go interface declarations. The main features of minimock are: It generates statically typed mocks and helpers.

Juno Inc. 431 Oct 18, 2021
Automatically generate Go test boilerplate from your source code.

gotests gotests makes writing Go tests easy. It's a Golang commandline tool that generates table driven tests based on its target source files' functi

Charles Weill 3.5k Oct 18, 2021
An implementation of failpoints for Golang.

failpoint An implementation of failpoints for Golang. Fail points are used to add code points where errors may be injected in a user controlled fashio

PingCAP 631 Oct 18, 2021
Testing framework for Go. Allows writing self-documenting tests/specifications, and executes them concurrently and safely isolated. [UNMAINTAINED]

GoSpec GoSpec is a BDD-style testing framework for the Go programming language. It allows writing self-documenting tests/specs, and executes them in p

Esko Luontola 114 Feb 11, 2021
Completely type-safe compile-time mock generator for Go

Mockc Mockc is a completely type-safe compile-time mock generator for Go. You can use it just by writing the mock generators with mockc.Implement() or

Geon Kim 29 May 23, 2021
Automatically update your Go tests

autogold - automatically update your Go tests autogold makes go test -update automatically update your Go tests (golden files and Go values in e.g. fo

Hexops 101 Oct 19, 2021
mockery - A mock code autogenerator for Golang

mockery - A mock code autogenerator for Golang

Vektra 3k Oct 21, 2021
go-test-trace is like go test but it also generates distributed traces.

go-test-trace go-test-trace is like go test but it also generates distributed traces. Generated traces are exported in OTLP to a OpenTelemetry collect

JBD 346 Oct 21, 2021
Random fake data generator written in go

Gofakeit Random data generator written in go Features 160+ Functions!!! Concurrent Global Rand Struct Generator Custom Functions Http Server Command L

Brian Voelker 2.1k Oct 15, 2021
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.

Fortio Fortio (Φορτίο) started as, and is, Istio's load testing tool and now graduated to be its own project. Fortio is also used by, among others, Me

Fortio (Φορτίο) 2.1k Oct 15, 2021
Mutation testing for Go source code

go-mutesting go-mutesting is a framework for performing mutation testing on Go source code. Its main purpose is to find source code, which is not cove

Markus Zimmermann 475 Oct 21, 2021
A toolkit with common assertions and mocks that plays nicely with the standard library

Testify - Thou Shalt Write Tests ℹ️ 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

Stretchr, Inc. 14.6k Oct 24, 2021
Ruby on Rails like test fixtures for Go. Write tests against a real database

testfixtures Warning: this package will wipe the database data before loading the fixtures! It is supposed to be used on a test database. Please, doub

null 707 Oct 11, 2021
Cucumber for golang

Godog The API is likely to change a few times before we reach 1.0.0 Please read the full README, you may find it very useful. And do not forget to pee

Cucumber 1.5k Oct 16, 2021
Cucumber for golang

Godog The API is likely to change a few times before we reach 1.0.0 Please read the full README, you may find it very useful. And do not forget to pee

Cucumber 1.5k Oct 20, 2021
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 198 Oct 20, 2021
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 282 Oct 18, 2021