【问题标题】:Importing vault/builtin/credential/aws adds testing flags to command-line app导入 Vault/builtin/credential/aws 将测试标志添加到命令行应用程序
【发布时间】:2018-06-12 06:10:36
【问题描述】:

我正在创建一个快速而肮脏的 Go 应用程序来从 Vault 中提取应用程序机密,并使用 Vault 代码本身进行身份验证。作为其中的一部分,我从 github.com/hashicorp/vault/builtin/credential/aws 导入 aws 凭证模块。这一切都很好。

但是,在运行我的应用程序时,我注意到来自 Go“测试”模块的命令行标志出现在标志中。

这可以通过编译和运行以下示例脚本来重现:

package main

import (
    "flag"
    _ "github.com/hashicorp/vault/builtin/credential/aws"
    // Note: this import is masked only to make this demo script compile.
    // In my actual code I need to use it, and it is not masked.
)

var myFlag string

func main() {
    flag.StringVar(
        &myFlag, "myFlag", "", "Test flag",
    )
    flag.Parse()
    flag.Usage()
}

调用二进制文件时,标志如下所示:

Usage of poc:
  -myFlag string
        Test flag
  -test.bench regexp
        run only benchmarks matching regexp
  -test.benchmem
        print memory allocations for benchmarks
  -test.benchtime d
        run each benchmark for duration d (default 1s)
  -test.blockprofile file
        write a goroutine blocking profile to file
  -test.blockprofilerate rate
        set blocking profile rate (see runtime.SetBlockProfileRate) (default 1)
  -test.count n
        run tests and benchmarks n times (default 1)
  [... more flags from the go testing module ...]

我是 Go 新手,所以我完全有可能在这里做一些我不应该做的事情,但乍一看,将这个模块导入命令行工具似乎是合理的。

据我所见,模块中没有任何内容使用测试库(除了 backend_test.go),所以我对这些标志的出现方式有些困惑,尤其是因为它们没有出现在Vault 命令行界面本身。

是否可以在不包含这些标志的情况下导入和使用 Vault 的 credential/aws 模块?或者在定义我自己的之前以某种方式清除测试标志?

【问题讨论】:

  • 仅供参考,hashicorp 喜欢在 testing.go 而非 _test.go 文件中定义测试助手,以便其他包可以导入和使用助手。对于aws 包,它的一些非测试文件导入framework 包,该包确实有一个testing.go 文件,该文件从std lib 导入testing 包。因此,在使用 hashcorp 库时,请准备好让您的标志空间被测试标志污染。
  • 谢谢,很高兴知道。看起来使用单独的标志空间是要走的路。

标签: go command-line-interface hashicorp-vault


【解决方案1】:

那是因为即使您使用_ 屏蔽github.com/hashicorp/vault/builtin/credential/aws,导入实际发生了。并且包导入了testing,它会生成所有这些标志。

您可以使用新的 FlagSet 摆脱 testing 标志。

func main() {
    f:=flag.NewFlagSet("Your app name",flag.ExitOnError)
    f.StringVar(
        &myFlag, "myFlag", "", "Test flag",
    )
    f.Parse(os.Args)
    f.Usage()
}

游乐场:https://play.golang.org/p/O8ibPn77L46

【讨论】:

  • 对不起,我可能不太清楚,这个脚本是为了演示问题,不是我的实际代码。我需要使用aws模块,它是正确的,但是我不希望测试模块中的标志出现在我的应用中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 2015-11-10
相关资源
最近更新 更多