// InitConnection initializes the database connection func InitConnection() { err := config.InitEnv() if err != nil { log.Fatal(err) } if config.IsTestEnv() { return } connString := ConnString() c, err := sql.Open("mysql", connString) if err != nil { log.Println("[Error]", err) log.Fatal(ErrUnableToParseDBConnection) } err = VerifyConnection(c) if err != nil { log.Println("[Error]", err) log.Fatal(ErrUnableToConnectToDB) } Conn = c }
OverwriteEnv("ENV", "other") OverwriteEnv("DB_HOST", "host") OverwriteEnv("DB_PORT", "port") OverwriteEnv("DB_USER", "user") OverwriteEnv("DB_NAME", "test") }) AfterEach(func() { ResetEnv() }) Describe(".ConnString", func() { Context("when DB_DRIVER=mysql", func() { It("returns a mysql connection string", func() { os.Setenv("DB_DRIVER", "mysql") config.InitEnv() actual := ConnString() expected := "user@tcp(host:port)/" Expect(actual).To(Equal(expected)) }) }) Context("when DB_DRIVER=postgres", func() { It("returns a postgres connection string", func() { os.Setenv("DB_DRIVER", "postgres") config.InitEnv() actual := ConnString() expected := "postgres://user@host:port/test?sslmode=disable" Expect(actual).To(Equal(expected))