Sunday, June 10, 2018

Golang - text/template unit test to cover all the use-cases

Leave a Comment

i've the following example (similar of what we have in prod) "text/template" code which works OK, now I want to create for it unit test that check the function and also the text/template to see that I cover 100% of the code...the problem here is how to do the text/template unit test which cover all the cases, im currently new to text/template and I want to make sure it's working as expected.

please see

https://play.golang.org/p/203Al36Zigk

This is the template:

const tmpl = `#!/bin/bash {{- range .File.Dependency}} echo {{.EchoText}} {{- range .Install}} submitting {{.name}} {{- end}} {{.TypeCommand}} {{end}}  {{- range $k, $v := .API}} echo {{$k}} submitting {{$v}} {{end}} ` 

2 Answers

Answers 1

You should setup a template_test file dedicated to testing the output of your template file.

For that, looking at the sources of the golang text/template package is always a good idea.

As an example (to be adapted to your case), you have src/text/template/example_test.go which uses a classic table-driven test approach:

package template_test  import (     "log"     "os"     "strings"     "text/template" )  func ExampleTemplate() {     // Define a template.     const letter = ` Dear {{.Name}}, {{if .Attended}} It was a pleasure to see you at the wedding. {{- else}} It is a shame you couldn't make it to the wedding. {{- end}} {{with .Gift -}} Thank you for the lovely {{.}}. {{end}} Best wishes, Josie `      // Prepare some data to insert into the template.     type Recipient struct {         Name, Gift string         Attended   bool     }     var recipients = []Recipient{         {"Aunt Mildred", "bone china tea set", true},         {"Uncle John", "moleskin pants", false},         {"Cousin Rodney", "", false},     }      // Create a new template and parse the letter into it.     t := template.Must(template.New("letter").Parse(letter))      // Execute the template for each recipient.     for _, r := range recipients {         err := t.Execute(os.Stdout, r)         if err != nil {             log.Println("executing template:", err)         }     }      // Output:     // Dear Aunt Mildred,     //     // It was a pleasure to see you at the wedding.     // Thank you for the lovely bone china tea set.     //     // Best wishes,     // Josie     //     // Dear Uncle John,     //     // It is a shame you couldn't make it to the wedding.     // Thank you for the lovely moleskin pants.     //     // Best wishes,     // Josie     //     // Dear Cousin Rodney,     //     // It is a shame you couldn't make it to the wedding.     //     // Best wishes,     // Josie } 

For the assertion part, look in src/text/template/multi_test.go which defines multiParseTest as a structure with a template, *and an expected result, which allows to do assertions like:

result := tmpl.Root.String() if result != test.results[i] {     t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.results[i]) } 

Answers 2

yourcodefile.go

    type API map[string]string      type data struct {         File *File         API  API     }     func DynamicdataForTemplate() data {                     f := new(File)                     f.Dependency = []Dependency{{                         Name:    "ui",                         Type:    "runner",                         CWD:     "/ui",                         Install: []Install{{"name": "api"}},                     }, {                         Name:    "ui2",                         Type:    "runner2",                         CWD:     "/ui2",                         Install: []Install{{"name": "api2"}},                     }}                      datav := data{}                     datav.File = f                     datav.API = API{"runner3": "api3", "runner4": "api4"}                      return datav                 }   func ParseTemplate() error {                     parsedTempl, err := template.New("t").Parse(tmpl)                     err = parsedTempl.Execute(os.Stdout, DynamicdataForTemplate())                     return err }      func main() {         _ = ParseTemplate()     } 

use this Assertion Package for writing Test case https://github.com/stretchr/testify

yourcodefile_test.go

import (     "testify/assert"     "testing" )   func TestDynamicdataForTemplate(t *testing.T) {     t.Run("should return the Type", func(t *testing.T) {         dataType := data{}         assert.IsType(t, dataType, DynamicdataForTemplate())     }) }  func TestParseTemplate(t *testing.T) {     t.Run("should return the nil", func(t *testing.T) {         assert.Nil(t, ParseTemplate())     }) 

}

code coverage Report Command

go test -coverprofile=coverage.out go tool cover -html=coverage.out 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment