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
  • 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
  • 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
  • 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
  • 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
  • Adds the test name to the errors

    Adds the test name to the errors

    Error messages omit the table element name (tt.name), making it difficult (impossible?) to identify which table entry failed. This patch adds the name to the error message.

    opened by ghost 8
  • fix: render template load reset

    fix: render template load reset

    This fixes reset for render's template load, bug appears only while running tests, when previous one is changing text one (if none of the template* params provided).

    Adds tests for output.Option checkers

    Also fixes two tests:

    1. Undefined Interface - solution fixed golden
    2. Entire Directory - solution provide template name (testify).
    cla: yes 
    opened by butuzov 7
  • [docs] update README to include git install instruction

    [docs] update README to include git install instruction

    Using go get -u github.com/cweill/gotests/... to install would give following error message.

    go get: installing executables with 'go get' in module mode is deprecated.
    	Use 'go install [email protected]' instead.
    	For more information, see https://golang.org/doc/go-get-install-deprecation
    	or run 'go help get' or 'go help install'.
    

    Instruction to use go install is added to README for Go version >= 1.17.

    opened by Xirui 2
  • return on wantErr bypass Subtests

    return on wantErr bypass Subtests

    Thanks for your contribution. When I am generating test if the function has error then we add a test for wantErr then adds Subtests. But there should be a return statement also and return if wantErr e.g

    t.Run(tt.name, func(t *testing.T) {
    	got, err := tt.p.Write(tt.args.record)
    	if (err != nil) != tt.wantErr {
    		t.Errorf("parquetWriter.Write() error = %v, wantErr %v", err, tt.wantErr)
    		return
    	}
            //////////////////// this return should be added//////////////////////////
    	if tt.wantErr {
    		return
    	}
            //////////////////// this return should be added//////////////////////////
            
           // There is no point checking Subtests if I want error it may create wrong test result
    	if got != tt.want {
    		t.Errorf("parquetWriter.Write() = %v, want %v", got, tt.want)
    	}
    })
    
    opened by arifmahmudrana 0
  • Support only 2 latest major go releases

    Support only 2 latest major go releases

    TL;DR

    Raised a PoC PR, and it passed all the checks. If it looks good to you, I can raise a PR in this repository. I will also update the README.md to indicate what's supported.

    Why

    From Go's release policy:

    Each major Go release is supported until there are two newer major releases.

    As a result, unless under some special circumstances, I feel that it does not make much sense to support versions that are not even supported by official Go team.

    Context

    As of now, tests are failing with the following error message:

    ../../../golang.org/x/tools/internal/typeparams/normalize.go:162:17: u.EmbeddedType undefined (type *types.Interface has no field or method EmbeddedType)

    That is because in Go1.10, type *types.Interface has no field or method EmbeddedType.

    I also noticed that we have golang.org/x/tools v0.0.0-20191109212701-97ad0ed33101 in our go.mod, and in that version, the whole typeparams directory does not even exist. From the line number in the error message above, the build job seems to use the latest version instead of the one specified in go.mod, and why is that?

    The Go version is 1.10 in the job, and modules was introduced in 1.11, and I suspect that the go get ./... simply downloads the latest version because it just does not understand go.mod.

    At this timepoint, I figured that maybe it makes more sense to support the latest releases (i.e., 1.17 and so on) instead of making effort to maintain releases that are too old.

    opened by davidhsingyuchen 0
  • Add a link to VS Code configuration

    Add a link to VS Code configuration

    PR changes the VS Code link to be the gotests-specific one just like all the other mentioned IDEs.

    Not opening an issue first because this PR is small. Signed the CLA. Waiting for approval.

    opened by davidhsingyuchen 1
  • Favor 'go install' over 'go get' for installation

    Favor 'go install' over 'go get' for installation

    go get is deprecated in terms of installing executables. $ is removed so that folks can just copy the whole block and run it.

    Not opening an issue first because this PR is small. Signed the CLA. Waiting for approval.

    opened by davidhsingyuchen 3
Releases(v1.6.0)
Owner
Charles Weill
Co-Author of google/nitroml, and tensorflow/adanet. AutoML Researcher @google.
Charles Weill
Generate a test coverage badge like this one for your go projects.

coverage-badge-go ?? Generate a test coverage badge like this one for your go projects. Usage on: pull_request: branches: -

tj-actions 12 May 10, 2022
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 366 Apr 21, 2022
Flugel Test Documentation for steps to run and test the automatio

Flugel Test Documentation Documentation for steps to run and test the automation #Test-01 1 - Local Test Using Terratest (End To End) 1- By runing " t

Suc0_Unix 0 Dec 30, 2021
Test-assignment - Test assignment with golang

test-assignment We have a two steam of data and we need to save it in the map: I

null 0 Jan 19, 2022
This repository includes consumer driven contract test for provider, unit test and counter api.

This repository includes consumer driven contract test for provider, unit test and counter api.

Ahmet Zümberoğlu 0 Feb 1, 2022
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 116 May 1, 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 Mar 15, 2022
go-carpet - show test coverage in terminal for Go source files

go-carpet - show test coverage for Go source files To view the test coverage in the terminal, just run go-carpet. It works outside of the GOPATH direc

Sergey Mudrik 225 May 11, 2022
Test your command line interfaces on windows, linux and osx and nodes viá ssh and docker

Commander Define language independent tests for your command line scripts and programs in simple yaml files. It runs on windows, osx and linux It can

null 200 May 6, 2022
Cloud Spanner load generator to load test your application and pre-warm the database before launch

GCSB GCSB Quickstart Create a test table Load data into table Run a load test Operations Load Single table load Multiple table load Loading into inter

Cloud Spanner Ecosystem 19 Apr 14, 2022
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 524 May 8, 2022
A Master list of Go Programming Tutorials, their write-ups, their source code and their current build status!

TutorialEdge TutorialEdge.net Go Tutorials ??‍?? ??‍?? Welcome to the TutorialEdge Go Repository! The goal of this repo is to be able to keep track of

TutorialEdge 265 Apr 29, 2022
Terratest is a Go library that makes it easier to write automated tests for your infrastructure code.

Terratest is a Go library that makes it easier to write automated tests for your infrastructure code. It provides a variety of helper functions and patterns for common infrastructure testing tasks,

Gruntwork 6.1k May 11, 2022
Run a real Postgres database locally on Linux, OSX or Windows as part of another Go application or test

embedded-postgres Run a real Postgres database locally on Linux, OSX or Windows as part of another Go application or test. When testing this provides

Fergus Strange 366 May 8, 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 205 Apr 4, 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 86 May 5, 2022
Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

GoConvey is awesome Go testing Welcome to GoConvey, a yummy Go testing tool for gophers. Works with go test. Use it in the terminal or browser accordi

SmartyStreets 7.1k May 6, 2022
A Go test assertion library for verifying that two representations of JSON are semantically equal

jsonassert is a Go test assertion library for verifying that two representations of JSON are semantically equal. Usage Create a new *jsonassert.Assert

Roger Guldbrandsen 83 May 7, 2022
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 775 May 6, 2022