unit-testing - 如何测试 CLI 标志 - 当前因“重新定义标志”而失败
问题描述
我有以下要测试的功能:
import (
"github.com/spf13/pflag"
)
func parseCLIFlags() cliOptions {
mode := pflag.StringP("mode", "m", "json", "file format")
outType := pflag.StringP("out-type", "o", "stdout", "Output format")
outFile := pflag.String("out-file", "", "Output file. Only used if `--out-type` is not stdout")
inFiles := pflag.StringArrayP("file", "f", []string{}, "Files to compare. Use this flag multiple times, once for each file.")
pflag.Parse()
options := cliOptions{
mode: *mode,
outType: *outType,
outFile: *outFile,
inFiles: *inFiles,
}
return options
}
我正在尝试使用以下测试进行测试:
func TestFlagsAreParsedCorrectly(t *testing.T) {
os.Args = []string{"schmp", "-f", "testdata/yaml/yaml_1.yaml", "--file", "testdata/yaml/yaml_2.yaml", "--mode", "yaml", "-o", "json", "--out-file", "sample.json"}
cliOptions := parseCLIFlags()
if cliOptions.mode != "yaml" {
t.Fatalf("could not set mode")
}
if cliOptions.outType != "json" {
t.Fatalf("could not set outType")
}
if cliOptions.outFile != "sample.json" {
t.Fatalf("could not set outFile")
}
if !reflect.DeepEqual(cliOptions.inFiles, []string{"testdata/yaml/yaml_1.yaml", "testdata/yaml/yaml_2.yaml"}) {
fmt.Println("could not set inFiles")
}
}
func TestCheckDefaultFlags(t *testing.T) {
os.Args = []string{"schmp"}
cliOptions := parseCLIFlags()
if cliOptions.mode != "json" {
t.Fatalf("default mode is not `json`")
}
}
但是我的测试很恐慌flag redefined: mode
知道如何解决此问题以便进行测试吗?
解决方案
根据@Adrian 的评论,我可以通过创建一个FlagSet
in来修复它parseCLIFlags
:
func parseCLIFlags() cliOptions {
flag := pflag.FlagSet{}
mode := flag.StringP("mode", "m", "json", "file format")
outType := flag.StringP("out-type", "o", "stdout", "Output format")
outFile := flag.String("out-file", "", "Output file. Only used if `--out-type` is not stdout")
inFiles := flag.StringArrayP("file", "f", []string{}, "Files to compare. Use this flag multiple times, once for each file.")
flag.Parse(os.Args[1:])
options := cliOptions{
mode: *mode,
outType: *outType,
outFile: *outFile,
inFiles: *inFiles,
}
return options
}
推荐阅读
- c++ - C++ 中的数字模式
- azure-devops - 如何使用来自 2 个不同管道的工件?
- elasticsearch - python elasticsearch从给定的doc_id获取字段
- kubernetes - Kubernetes v1.16.7 CronJob 数量超过 20k+ 且不执行
- reactjs - Typescript:如何通过自动完成向函数动态添加方法?
- javascript - jQuery 中的第二个子值检查
- ios - 如何在 iOS Swift 应用程序中使用 USB 打印机通过 iPad 打印?
- nlp - 如果我选择的词在预训练的词嵌入矩阵中没有任何嵌入向量怎么办?
- angular - 向 FormArray 提供除空数组以外的任何内容时,Angular 自定义验证器会中断
- flutter - 'AnimatedContainer'宽度的来回动画从设备屏幕的全宽到Flutter中的特定值