Golang - 文本/模板单元测试,涵盖所有用例

时间:2018-05-28 08:45:23

标签: go

我有以下示例(类似于我们在prod中所拥有的)“text / template”代码,它工作正常,现在我想为它创建一个单元测试来检查函数以及text/template看到我覆盖了100%的代码...

这里的问题是如何进行文本/模板单元测试,其中包含所有案例。我目前是文本/模板的新手,我想确保它按预期工作。

请访问: https://play.golang.org/p/203Al36Zigk

这是模板:

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 个答案:

答案 0 :(得分:3)

您应该设置一个专门用于测试模板文件输出的template_test文件。

为此,查看golang text/template package的来源总是一个好主意。

举个例子(根据你的情况进行调整),你有src/text/template/example_test.go使用经典的table-driven test方法:

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
}

对于断言部分,请查看src/text/template/multi_test.go,其中multiParseTest定义为具有模板的结构*和预期结果,允许执行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])
}

答案 1 :(得分: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()
    }

使用此断言包编写测试用例 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())
    })

}

代码覆盖率报告命令

go test -coverprofile=coverage.out
go tool cover -html=coverage.out