Golang的依赖项在init()函数中注册SQL驱动程序导致冲突。

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

Golang dependencies registering sql driver in init() causing clash

问题

我有一些依赖于一些外部代码的Go测试,这些代码有一些init()方法来注册mysql驱动程序。我的代码也需要注册mysql驱动程序,因此在运行测试时会出现panic和错误信息"Register called twice for driver mysql"。

我发现我依赖的仓库中有一个vendors目录,其中包含了该驱动程序("vendors/github.com/go-sql-driver/mysql")。当我运行测试时,驱动程序中的init()方法被调用并注册了mysql驱动程序,导致冲突。

我能想到的最好的解决办法是将依赖项复制到我自己的vendors目录中,并从依赖项的vendors目录中删除mysql驱动程序。然而,我不太喜欢这种方法,因为它涉及到复制我的依赖项,然后通过删除文件来修改它。而且,我只是在运行测试时依赖于它,所以我不确定是否应该将其移动到我的vendors目录中。

有没有办法阻止在依赖项的供应商依赖项上调用init()方法呢?

英文:

I have some Go tests that depend on some external code which has init() methods that registers mysql drivers. My code also needs to register mysql drivers and I therefore end up with a panic and the error "Register called twice for driver mysql" when running my tests.

It seems that the repo I'm dependent on has a vendors directory with the driver in it ("vendors/github.com/go-sql-driver/mysql"). It seems that when I run my tests the init() methods in the driver are called and registers the mysql driver causing the clash.

The best option I can see would be to copy the dependency to my own vendors directory and remove the mysql driver from the dependency's vendor directory. However I'm not keen on this as it involves duplicating my dependency and then modifying it by deleting files. Also, I'm only dependent on this for running tests so I'm not sure I should be moving it to my vendors directory any way.

Is there a way to prevent init() being called on a dependency's vendor dependencies?

答案1

得分: 1

首先,我建议放弃这个依赖项。如果它正在注册一个数据库驱动程序(这是依赖项绝对不应该做的事情),我预测它会带来更多问题。我还建议您提出一个问题。

作为一种解决方法,您可以根据是否处于测试构建中导入该库。因此,您可以创建一个名为mysqlimport.go的文件,其中只包含以下内容:

// +build !test

import _ "github.com/go-sql-driver/mysql"

这样,只有在您不进行测试时才会调用此代码。尽管您将不得不使用go test -tags test来启动测试。

英文:

First of all, I would ditch the dependency. If it's registering a database driver - something that dependencies really should never do - I predict there will be more problems with it. Also I suggest opening an issue.

As a workaround, you can import the library depending on whether you are in a test build or not. So you will have a file called e.g. mysqlimport.go with nothing but

// +build !test

import _ "github.com/go-sql-driver/mysql"

This way this code will only be called when you're not testing. Although you'll have to start your tests with go test -tags test.

huangapple
  • 本文由 发表于 2017年8月9日 19:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45589270.html
匿名

发表评论

匿名网友

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

确定