Created
July 16, 2020 21:27
-
-
Save jdheyburn/94eb1513395ae46eac6aa9721d089d3c to your computer and use it in GitHub Desktop.
Modified gotest template files allowing for enhanced error testing in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{define "function"}} | |
{{- $f := .}} | |
func {{.TestName}}(t *testing.T) { | |
{{- with .Receiver}} | |
{{- if .IsStruct}} | |
{{- if .Fields}} | |
type fields struct { | |
{{- range .Fields}} | |
{{Field .}} {{.Type}} | |
{{- end}} | |
} | |
{{- end}} | |
{{- end}} | |
{{- end}} | |
{{- if .TestParameters}} | |
type args struct { | |
{{- range .TestParameters}} | |
{{Param .}} {{.Type}} | |
{{- end}} | |
} | |
{{- end}} | |
tests := []struct { | |
name string | |
{{- with .Receiver}} | |
{{- if and .IsStruct .Fields}} | |
fields fields | |
{{- else}} | |
{{Receiver .}} {{.Type}} | |
{{- end}} | |
{{- end}} | |
{{- if .TestParameters}} | |
args args | |
{{- end}} | |
{{- range .TestResults}} | |
{{Want .}} {{.Type}} | |
{{- end}} | |
{{- if .ReturnsError}} | |
wantErr error | |
{{- end}} | |
}{ | |
// TODO: Add test cases. | |
} | |
for {{if (or .Subtests (not .IsNaked))}} _, tt := {{end}} range tests { | |
{{- if .Subtests }}t.Run(tt.name, func(t *testing.T) { {{- end -}} | |
{{- with .Receiver}} | |
{{- if .IsStruct}} | |
{{Receiver .}} := {{if .Type.IsStar}}&{{end}}{{.Type.Value}}{ | |
{{- range .Fields}} | |
{{.Name}}: tt.fields.{{Field .}}, | |
{{- end}} | |
} | |
{{- end}} | |
{{- end}} | |
{{- range .Parameters}} | |
{{- if .IsWriter}} | |
{{Param .}} := &bytes.Buffer{} | |
{{- end}} | |
{{- end}} | |
{{template "results" $f}} {{template "call" $f}} | |
{{- if .ReturnsError}} | |
if err != nil && tt.wantErr == nil { | |
assert.Fail(t, fmt.Sprintf( | |
"Error not expected but got one:\n"+ | |
"error: %q", err), | |
) | |
{{- if .TestResults}} | |
{{if .Subtests }}return{{else}}continue{{end}} | |
{{- end}} | |
} | |
if tt.wantErr != nil { | |
assert.EqualError(t, err, tt.wantErr.Error()) | |
{{- if .TestResults}} | |
{{if .Subtests }}return{{else}}continue{{end}} | |
{{- end}} | |
} | |
{{- end}} | |
{{- range .TestResults}} | |
assert.Equal(t, tt.{{Want .}}, {{Got .}}) | |
{{- end}} | |
{{- if .Subtests }} }) {{- end -}} | |
} | |
} | |
{{end}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{define "results"}} {{range $i, $el := .Results}}{{if $i}}, {{end}}{{Got .}}{{end}}{{if .ReturnsError}}{{if not .OnlyReturnsError}}, {{end}}err{{end}} {{if or .Results .ReturnsError}} := {{end}} {{end}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment