doo6568 2018-01-06 17:49
浏览 23
已采纳

将数据库凭据传递给进行中的测试?

I have tried couple of approaches (shown below) but I don't like any of them. So I decided to ask the community if there is a better way to do it.

Approach 1

Pass database credentials as arguments:

go test -args -db_user=test -db_pass=secret

Then use it in tests as:

package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")

func TestSomething(t *testing.T) {
    db := open(*dbUser, *dbPass)
}

Approach 2

Set environment variables before running tests:

$ export TEST_DB_USER=user
$ export TEST_DB_PASS=secret
$ go test

or

$ TEST_DB_USER=user TEST_DB_PASS=secret go test -v

Then use it in tests as:

package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")

func TestSomething(t *testing.T) {
    db := open(os.Getenv("TEST_DB_USER"), os.Getenv("TEST_DB_PASS"))
}

Approach 3

Use .env.test file and github.com/joho/godotenv package to load database connection credentials before running tests.

  • 写回答

1条回答 默认 最新

  • dongzhenyin2001 2018-01-06 18:21
    关注

    Environment variables tend to be best for this for the following reasons:

    • easier to set in your local environment persistently
    • most test infrastructure allows you to specify environment variables, and often has ways to mark them as "sensitive" (not visible after being set) and can be restricted by build type (to void leaking credentials to contributors)
    • environment variables are not visible in process listing/logs (unless intentionally listed). command-line flags are.
    • works with anything, not just go. (eg: if you need AWS credentials, the same settings will work for most AWS libraries).

    But overall, this is too broad a question. The ultimate answer depends on the people working on the project with a daily need to run tests. It also depends massively on your test infrastructure.

    And finally: if this is for unittests, you shouldn't need database credentials, external services should be mocked. You also don't want contributors to need database credentials to run unittests.

    If this is for integration tests, your test infrastructure will be the most important factor.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败