gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:05:22 34 4
gpt4 key购买 nike

我有以下示例(类似于我们在 prod 中的示例)“文本/模板”代码可以正常工作,现在我想为其创建一个单元测试来检查函数以及 text/模板 看看我覆盖了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}}
`

最佳答案

您应该设置一个 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])
}

关于Golang - 覆盖所有用例的文本/模板单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50562372/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com