Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang dependencies registering sql driver in init() causing clash

Tags:

go

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?

like image 305
jcmturner Avatar asked Aug 09 '17 11:08

jcmturner


1 Answers

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.

like image 110
Ainar-G Avatar answered Oct 19 '22 23:10

Ainar-G