Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dogukanayd committed May 11, 2020
0 parents commit 66d6c83
Show file tree
Hide file tree
Showing 10 changed files with 342 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/.idea/
/vendor/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Doğukan Aydoğdu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions cmd/unit/mysqlunit/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash

function newContainer() {
docker kill mysql_test
docker container rm -f mysql_test
docker run -d --name mysql_test -p 3305:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test_database mysql
docker cp tables.sql mysql_test:/docker-entrypoint-initdb.d/init.sql
echo "completed"
}

newContainer
14 changes: 14 additions & 0 deletions cmd/unit/mysqlunit/tables.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

DROP DATABASE IF EXISTS test_database;
CREATE DATABASE test_database;

use test_database;

CREATE TABLE `test_table`
(
`id` int(11),
`name` varchar(500)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
56 changes: 56 additions & 0 deletions cmd/unit/mysqlunit/unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package mysqlunit

import (
"github.com/dogukanayd/go-test-database/databases/testmysql"
"testing"
"time"

"upper.io/db.v3/lib/sqlbuilder"
)

// NewUnit ...
func NewUnit(t *testing.T) (sqlbuilder.Database, func()) {
t.Helper()
c := testmysql.StartContainer(t)

connection, err := testmysql.Connections.ConnectOrReuse(testmysql.TestDatabaseName, c.Host)

if err != nil {
t.Fatalf("opening database connection: %v", err)
}

healthCheck(connection, t, c)

// teardown is the function that should be invoked when the caller is done
// with the database.
teardown := func() {
t.Helper()
_ = connection.Close()
testmysql.StopContainer(t, c)
}

return connection, teardown
}

// Wait for the database to be ready. Wait 100ms longer between each attempt.
// Do not try more than 20 times.
func healthCheck(connection sqlbuilder.Database, t *testing.T, c *testmysql.Container, ) {
var pingError error

maxAttempts := 20

for attempts := 1; attempts <= maxAttempts; attempts++ {
pingError = connection.Ping()

if pingError == nil {
break
}

time.Sleep(time.Duration(attempts) * 100 * time.Millisecond)
}

if pingError != nil {
testmysql.StopContainer(t, c)
t.Fatalf("waiting for database to be ready: %v", pingError)
}
}
35 changes: 35 additions & 0 deletions cmd/unit/mysqlunit/unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package mysqlunit

import (
"testing"
"upper.io/db.v3"
)

type TestTable struct {
Name string `db:"name"`
}

func TestNewUnit(t *testing.T) {
connection, tearDown := NewUnit(t)
defer tearDown()

t.Run("it should create user with name 'go awesome' and return", func(t *testing.T) {
u := TestTable{
Name: "go awesome",
}

connection.Collection("test_table").Insert(u)

err := connection.Collection("test_table").Find(db.Cond{
"name": "go awesome",
}).One(&u)

if err != nil {
t.Fatalf("error in unit_test: %v", err)
}

if u.Name != "go awesome" {
t.Error("can not find user name: go awesome")
}
})
}
43 changes: 43 additions & 0 deletions databases/testmysql/connection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package testmysql

import (
"upper.io/db.v3/lib/sqlbuilder"
"upper.io/db.v3/mysql"
)

// Connections
var Connections = &connection{list: make(map[string]sqlbuilder.Database)}

type connection struct {
list map[string]sqlbuilder.Database
}

const TestDatabaseName = "test_database"

// ConnectOrReuse connection
func (c *connection) ConnectOrReuse(dbName, host string) (sqlbuilder.Database, error) {
connection, ok := c.list[dbName]

// If connection does not exist or dead
if !ok || connection.Ping() != nil {
url := "root" + ":" + "root" + "@" + "tcp(" + host + ")"
url = url + "/" + dbName + "?charset=utf8mb4&collation=utf8mb4_unicode_ci"
dsn, err := mysql.ParseURL(url)

if err != nil {
return nil, err
}

session, err := mysql.Open(dsn)

if err != nil {
return nil, err
}

c.list[dbName] = session

return session, nil
}

return connection, nil
}
133 changes: 133 additions & 0 deletions databases/testmysql/docker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package testmysql

import (
"bytes"
"encoding/json"
"os/exec"
"testing"
"time"
)

// Container ..
type Container struct {
ID string
Host string
Name string
}

const ContainerName = "mysql_test"

// StartContainer ..
func StartContainer(t *testing.T) *Container {
t.Helper()

startContainerAndMigrate(t)

cmd := exec.Command("docker", "ps", "-aqf", "name=" + ContainerName)

var out bytes.Buffer
var stderr bytes.Buffer

cmd.Stdout = &out
cmd.Stderr = &stderr
_ = cmd.Run()

ci := out.String()

cmd = exec.Command("docker", "inspect", ContainerName)
out.Reset()
stderr.Reset()
cmd.Stdout = &out
cmd.Stderr = &stderr

if err := cmd.Run(); err != nil {
t.Fatalf("could not inspect container %s: %v", ci, stderr.String())

return nil
}

var doc []struct {
NetworkSettings struct {
Ports struct {
TCP3306 []struct {
HostIP string `json:"HostIp"`
HostPort string `json:"HostPort"`
} `json:"3306/tcp"`
} `json:"Ports"`
} `json:"NetworkSettings"`
}

if err := json.Unmarshal(out.Bytes(), &doc); err != nil {
t.Fatalf("could not decode json: %v", err)
}

network := doc[0].NetworkSettings.Ports.TCP3306[0]

c := Container{
ID: ci,
Host: network.HostIP + ":" + network.HostPort,
Name: ContainerName,
}

t.Log("DB Host: ", c.Host)
t.Log("DB Container: ", c.ID)

return &c
}

func startContainerAndMigrate(t *testing.T) {
var out bytes.Buffer
var stderr bytes.Buffer
t.Helper()

cmd := exec.Command("bash", "run.sh")
cmd.Stdout = &out
cmd.Stderr = &stderr

if err := cmd.Run(); err != nil {
t.Fatalf("could not build container %v", stderr.String())
}

maxAttempts := 20

for attempts := 1; attempts <= maxAttempts; attempts++ {
if out.String() == "completed" {
t.Log("test database up success")
}

time.Sleep(time.Duration(attempts) * 100 * time.Millisecond)
}
}

// StopContainer stops and removes the specified container.
// TODO: it should stop container by id
func StopContainer(t *testing.T, c *Container) {
t.Helper()

t.Log("container id", c.ID)

if err := exec.Command("docker", "kill", ContainerName).Run(); err != nil {
t.Fatalf("could not stop container: %v", err)
}

t.Log("Stopped:", c.ID)

if err := exec.Command("docker", "container", "rm", "-f", ContainerName).Run(); err != nil {
t.Fatalf("could not remove container: %v", err)
}

t.Log("Removed:", c.ID)
}

// DumpContainerLogs runs "docker logs" against the container and send it to t.Log
func DumpContainerLogs(t *testing.T, c *Container) {
t.Helper()

out, err := exec.Command("docker", "logs", c.ID).CombinedOutput()

if err != nil {
t.Fatalf("could not log container: %v", err)
}

t.Logf("Logs for %s\n%s:", c.ID, out)
}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/dogukanayd/go-test-database

go 1.13

require (
github.com/go-sql-driver/mysql v1.5.0 // indirect
github.com/stretchr/testify v1.5.1 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
upper.io/db.v3 v3.6.4+incompatible
)
17 changes: 17 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 h1:VpOs+IwYnYBaFnrNAeB8UUWtL3vEUnzSCL1nVjPhqrw=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
upper.io/db.v3 v3.6.4+incompatible h1:ZWpoGpfyvRDxMW1lYLBwwSurzodIvAUP4aYBsH/ePiY=
upper.io/db.v3 v3.6.4+incompatible/go.mod h1:FgTdD24eBjJAbPKsQSiHUNgXjOR4Lub3u1UMHSIh82Y=

0 comments on commit 66d6c83

Please sign in to comment.