Skip to content
Snippets Groups Projects
Commit 3d2595e4 authored by Sercan Yesildal's avatar Sercan Yesildal
Browse files

test framework added

parent c9dfcd03
No related branches found
No related tags found
No related merge requests found
package db
import (
"database/sql"
"fmt"
"testing"
"time"
"github.com/go-sql-driver/mysql"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func CustomInit(path string, port string) error {
vp := viper.New()
vp.AddConfigPath(fmt.Sprintf(".%s%s/db", "/", path))
vp.SetConfigName("config")
vp.SetConfigType("json")
err := vp.ReadInConfig()
if err != nil {
return err
}
cfg = &mysql.Config{
User: vp.GetString("user"),
Passwd: vp.GetString("passwd"),
Net: "tcp",
Addr: port,
DBName: vp.GetString("dbName"),
Loc: time.Now().Local().Location(),
MaxAllowedPacket: 64 * 1024 * 1024,
AllowNativePasswords: true,
CheckConnLiveness: true,
ParseTime: true,
}
log.Info("Using DSN for DB: ", cfg.FormatDSN())
return nil
}
func connect() error {
udb, err := sql.Open(driverName, cfg.FormatDSN())
if err != nil {
return err
}
defer udb.Close()
return udb.Ping()
}
func prepareDatabase() error {
udb, err := sql.Open(driverName, cfg.FormatDSN())
if err != nil {
return err
}
defer udb.Close()
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `userAccount` (`id` int NOT NULL AUTO_INCREMENT, `mail` varchar(255) NOT NULL, `firstName` varchar(255) NOT NULL, `lastName` varchar(255) NOT NULL, PRIMARY KEY (`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `userGroup` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `userMeal` (`id` int NOT NULL AUTO_INCREMENT, `userId` int NOT NULL, `mealId` int NOT NULL, `date` DATE NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`userId`) REFERENCES userAccount(`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `favoriteMeal` (`id` int NOT NULL AUTO_INCREMENT, `userId` int NOT NULL, `mealId` int NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`userId`) REFERENCES userAccount(`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `shoppingDate` (`id` int NOT NULL AUTO_INCREMENT, `userId` int NOT NULL, `date` DATE NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`userId`) REFERENCES userAccount(`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `groupMeal` ( `id` int NOT NULL AUTO_INCREMENT, `groupId` int NOT NULL, `mealId` int NOT NULL, `date` DATE NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`groupId`) REFERENCES userGroup(`id`));")
if err != nil {
return err
}
_, err = udb.Exec("CREATE TABLE IF NOT EXISTS `userGroupRelation` (`id` int NOT NULL AUTO_INCREMENT, `groupId` int NOT NULL, `userId` int NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`groupId`) REFERENCES userGroup(`id`), FOREIGN KEY (`userId`) REFERENCES userAccount(`id`));")
if err != nil {
return err
}
return nil
}
func SetupTestDB(t *testing.T) func() {
pool, err := dockertest.NewPool("")
if err != nil {
t.Fatalf("Could not connect to docker: %s", err)
}
runDockerOpt := &dockertest.RunOptions{
Repository: "mariadb",
Tag: "10.5",
Env: []string{"MYSQL_ROOT_PASSWORD=secret", "MYSQL_DATABASE=planner"},
PortBindings: map[docker.Port][]docker.PortBinding{
"3306/tcp": {{HostIP: "localhost", HostPort: "3306/tcp"}},
},
}
fnConfig := func(config *docker.HostConfig) {
config.AutoRemove = true
config.RestartPolicy = docker.NeverRestart()
}
resource, err := pool.RunWithOptions(runDockerOpt, fnConfig)
if err != nil {
t.Fatalf("Could not start test DB: %s", err)
}
// retry until db server is ready
err = pool.Retry(func() error {
return connect()
})
if err != nil {
t.Fatalf("Could not connect to test DB: %s", err)
}
err = prepareDatabase()
if err != nil {
t.Fatalf("Could not setup test DB: %s", err)
}
return func() {
resource.Close()
}
}
......@@ -5,6 +5,7 @@ go 1.20
require (
github.com/go-sql-driver/mysql v1.7.1
github.com/gorilla/mux v1.8.0
github.com/ory/dockertest/v3 v3.10.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.16.0
google.golang.org/grpc v1.55.0
......@@ -12,21 +13,44 @@ require (
)
require (
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
github.com/containerd/continuity v0.4.1 // indirect
github.com/docker/cli v20.10.17+incompatible // indirect
github.com/docker/docker v20.10.7+incompatible // indirect
github.com/docker/go-connections v0.4.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/opencontainers/runc v1.1.7 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
golang.org/x/tools v0.11.0 // indirect
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
This diff is collapsed.
package handler
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"gitlab.reutlingen-university.de/yesildas/mealplanner2go/service/planner/db"
)
func TestCreateUser(t *testing.T) {
db.CustomInit("..", ":3306")
destroyDB := db.SetupTestDB(t)
defer destroyDB()
rr := httptest.NewRecorder()
json := `{"mail":"max.mustermann@gmail.com", "firstName":"Max", "lastName":"Mustermann"}`
req := httptest.NewRequest(http.MethodPost, "/user", bytes.NewBufferString(json))
req.Header.Set("Content-Type", "application/json")
handler := http.HandlerFunc(CreateUser)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler did not recognize valid request: %d", status)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment