如何在测试中传递参数,例如用户名和密码

huangapple go评论72阅读模式
英文:

How to pass arguments such as username and password in a test

问题

我使用以下代码来初始化与avi控制器的连接:

func TestAvi(t *testing.T) {
	aviClient, err := clients.NewAviClient("<CONTROLLERNAME>", "<USERID>",
		session.SetPassword("<PASSWORD>"),
		session.SetTenant("<TENANT>"),
		session.SetInsecure)
	if err != nil {
		t.Error(err)
	}

然后我运行go test命令来运行这段代码。
我想将CONTROLLERNAME、USERID、PASSWORD和TENANT外部化,这样我就可以将它们作为参数传递给go test命令。

请问需要什么帮助?

英文:

I use below code to initialize connection to avi controller,

func TestAvi(t *testing.T) {
	aviClient, err := clients.NewAviClient(&quot;&lt;CONTROLLERNAME&gt;&quot;, &quot;&lt;USERID&gt;&quot;,
		session.SetPassword(&quot;&lt;PASSWORD&quot;),
		session.SetTenant(&quot;&lt;TENANT&gt;&quot;),
		session.SetInsecure)
	if err != nil {
		t.Error(err)
	}

And then I run go test command to run the code.
I would like to externalize CONTROLLERNAME, USERID, PASSWORD and TENANT. So that I can pass those as arguments to go test command.

Any assistance please?

答案1

得分: 3

我不建议通过命令行参数传递这些信息,因为它们经常被记录。

一个简单且广泛使用的解决方案是通过环境变量传递这些信息,你可以使用os.Getenv()函数来读取它们。

如何设置环境变量完全取决于你,可能因系统而异。

例如:

func TestAvi(t *testing.T) {
    controller := os.Getenv("AVI_CONTROLLERNAME")
    password := os.Getenv("AVI_PASSWORD")
    tenant := os.Getenv("AVI_TENANT")
    userID := os.Getenv("AVI_USERID")
    
    aviClient, err := clients.NewAviClient(controller, userID,
        session.SetPassword(password),
        session.SetTenant(tenant),
        session.SetInsecure)

    // ...
}
英文:

I don't recommend passing those via CLI args, they are often logged.

A simple and most widely used solution is to pass such information via environment variables, which you can read using the os.Getenv() function.

How you set the environment variables is entirely up to you and may vary from system to system.

For example:

func TestAvi(t *testing.T) {
    controller := os.Getenv(&quot;AVI_CONTROLLERNAME&quot;)
    password := os.Getenv(&quot;AVI_PASSWORD&quot;)
    tenant := os.Getenv(&quot;AVI_TENANT&quot;)
    userID := os.Getenv(&quot;AVI_USERID&quot;)
    
    aviClient, err := clients.NewAviClient(controller, userID,
        session.SetPassword(password),
        session.SetTenant(tenant),
        session.SetInsecure)

    // ...
}

huangapple
  • 本文由 发表于 2022年4月25日 16:06:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/71996315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定