Skip to content

Commit

Permalink
Add database test
Browse files Browse the repository at this point in the history
  • Loading branch information
lfcifuentes committed Oct 12, 2023
1 parent e7bee73 commit e4ced52
Show file tree
Hide file tree
Showing 11 changed files with 277 additions and 30 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.env
.idea
.idea
coverage.out
70 changes: 69 additions & 1 deletion cmd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
"github.com/lfcifuentes/go-repository-pattern/database"
_ "github.com/lib/pq"
"github.com/spf13/cobra"
"log"
"os"
)

Expand All @@ -20,8 +23,73 @@ var Migrate = &cobra.Command{
}

func migrate() {
// Cargar las variables de entorno desde el archivo .env
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file:", err)
}

switch os.Getenv("DB_CONNECTION") {
case "psql":
migratePsql()
break
case "mysql":
migrateMysql()
break
default:
log.Fatal("DB CONNECTION NOT SUPPORTED")
}
}

func migratePsql() {
dbName := os.Getenv("DB_NAME")

// Crear la cadena de conexión para PostgreSQL sin especificar la base de datos
dsn := database.CreateConnectionWithoutDbString()

// Intenta conectar a PostgreSQL sin seleccionar una base de datos específica
db, err := sql.Open("postgres", dsn)
if err != nil {
log.Fatal("Error connecting to PostgreSQL:", err)
}
err = db.Ping()

if err != nil {
log.Fatal("Error pining to PostgreSQL:", err)
}

defer db.Close()

// Ejecuta la sentencia SQL para crear la base de datos si no existe
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s;", dbName))
if err != nil {
log.Fatal("Error creating database:", err)
}
fmt.Println("Database created or already exists.")

// Conectar a la base de datos recién creada
dsn = fmt.Sprintf("%s dbname=%s sslmode=disable", dsn, dbName)
db, err = sql.Open("postgres", dsn)
if err != nil {
log.Fatal("Error connecting to the created database:", err)
}
defer db.Close()

// Ejecuta las sentencias SQL desde schema.sql para crear tablas u otras estructuras de base de datos
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (
id serial PRIMARY KEY,
name VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255)
);`)
if err != nil {
log.Fatal("Error creating tables:", err)
}
fmt.Println("Tables created successfully.")
}

func migrateMysql() {
// DB credentials
godotenv.Load(".env")
user := os.Getenv("DB_USER")
pass := os.Getenv("DB_ROOT_PASSWORD")
database := os.Getenv("DB_NAME")
Expand Down
6 changes: 5 additions & 1 deletion cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
"github.com/lfcifuentes/go-repository-pattern/database"
"github.com/lfcifuentes/go-repository-pattern/users"
"github.com/spf13/cobra"
Expand All @@ -22,6 +23,10 @@ var Run = &cobra.Command{
}

func runServer() {
err := godotenv.Load(".env")
if err != nil {
log.Fatal(err)
}
// Configura la base de datos
db, err := database.CreateConnection()
if err != nil {
Expand All @@ -35,7 +40,6 @@ func runServer() {

// Configura el enrutador
router := users.NewRouter(r, db)
router = users.NewRouter(router, db)

// Inicia el servidor web
http.ListenAndServe(":8080", router)
Expand Down
7 changes: 7 additions & 0 deletions database/.env.ci
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
DB_NAME=db_test
DB_USER=test
DB_PORT=3307
DB_PASSWORD=password_test
DB_ROOT_PASSWORD=password_test
DB_HOST=localhost
DB_CONNECTION=psql
33 changes: 19 additions & 14 deletions database/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,40 @@ import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"os"
)

// CreateConnectionString create database connection string
func CreateConnectionString() string {
dbName := os.Getenv("DB_NAME")
// DB credentials
dns := CreateConnectionWithoutDbString()

// Crear la cadena de conexión para PostgreSQL sin especificar la base de datos
return fmt.Sprintf("%s dbname=%s", dns, dbName)
}

// CreateConnectionWithoutDbString
func CreateConnectionWithoutDbString() string {
// DB credentials
godotenv.Load(".env")
user := os.Getenv("DB_USER")
pass := os.Getenv("DB_PASSWORD")
database := os.Getenv("DB_NAME")
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")

return fmt.Sprintf(
"%v:%v@tcp(localhost:3306)/%v",
user,
pass,
database,
)
// Crear la cadena de conexión para PostgreSQL sin especificar la base de datos
return fmt.Sprintf("user=%s password=%s host=%s port=%s sslmode=disable",
user, pass, host, port)
}

// CreateConnection Create a new database connection
func CreateConnection() (*sql.DB, error) {
// Configura la base de datos
db, err := sql.Open(
"mysql",
"postgres",
CreateConnectionString(),
)
if err != nil {
return nil, err
}

return db, nil
return db, err
}
118 changes: 118 additions & 0 deletions database/migrations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package database

import (
"database/sql"
"fmt"
"github.com/joho/godotenv"
"github.com/stretchr/testify/assert"
"log"
"os"
"testing"
)

// TestCreateConnectionPsqlString
func TestCreateConnectionPsqlString(t *testing.T) {
// Cargar las variables de entorno desde el archivo .env
err := godotenv.Load(".env.psql-test")
if err != nil {
t.Fatalf("Error loading .env.ci file: %v", err)
}

expectedUser := os.Getenv("DB_USER")
expectedPass := os.Getenv("DB_PASSWORD")
expectedDB := os.Getenv("DB_NAME")
expectedPort := os.Getenv("DB_PORT")
expectedHost := os.Getenv("DB_HOST")

expectedConnectionString := fmt.Sprintf(
"user=%s password=%s host=%s port=%s sslmode=disable dbname=%s",
expectedUser, expectedPass, expectedHost, expectedPort, expectedDB,
)
fmt.Println(expectedConnectionString)
// Llamar a la función para crear la cadena de conexión
actualConnectionString := CreateConnectionString()

// Verificar que la cadena de conexión generada coincide con la esperada
assert.Equal(t, expectedConnectionString, actualConnectionString)
}

// TestCreateConnectionPsqlWithoutDbString
func TestCreateConnectionPsqlWithoutDbString(t *testing.T) {
// Cargar las variables de entorno desde el archivo .env
err := godotenv.Load(".env.psql-test")
if err != nil {
t.Fatalf("Error loading .env.ci file: %v", err)
}

expectedUser := os.Getenv("DB_USER")
expectedPass := os.Getenv("DB_PASSWORD")
expectedPort := os.Getenv("DB_PORT")
expectedHost := os.Getenv("DB_HOST")

expectedConnectionString := fmt.Sprintf(
"user=%s password=%s host=%s port=%s sslmode=disable",
expectedUser, expectedPass, expectedHost, expectedPort,
)
// Llamar a la función para crear la cadena de conexión
actualConnectionString := CreateConnectionWithoutDbString()

// Verificar que la cadena de conexión generada coincide con la esperada
assert.Equal(t, expectedConnectionString, actualConnectionString)
}

// TestCreatePsqlConnection
func TestCreatePsqlConnection(t *testing.T) {
// Cargar las variables de entorno desde el archivo .env
err := godotenv.Load(".env.psql-test")
if err != nil {
t.Fatalf("Error loading .env file: %v", err)
}
user := os.Getenv("DB_USER")
pass := os.Getenv("DB_PASSWORD")
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
database := os.Getenv("DB_NAME")

// Crear la cadena de conexión para PostgreSQL sin especificar la base de datos
dsn := fmt.Sprintf("user=%s password=%s host=%s port=%s sslmode=disable",
user, pass, host, port)

// Intenta conectar a PostgreSQL sin seleccionar una base de datos específica
db, err := sql.Open("postgres", dsn)
if err != nil {
log.Fatal("Error connecting to PostgreSQL:", err)
}
err = db.Ping()

if err != nil {
log.Fatal("Error pining to PostgreSQL:", err)
}

defer db.Close()

// Ejecuta la sentencia SQL para crear la base de datos si no existe
_, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", database))
if err != nil {
log.Fatal("Error deleting database:", err)
}
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s;", database))
if err != nil {
log.Fatal("Error creating database:", err)
}
fmt.Println("Database created or already exists.")

fmt.Println(CreateConnectionString())
// Llamar a la función para crear la conexión
db, err = CreateConnection()
defer db.Close() // Asegúrate de cerrar la conexión

// Verificar que no haya errores al crear la conexión
assert.NoError(t, err)

// Verificar que la conexión esté abierta
assert.NotNil(t, db)

// Intentar ejecutar una consulta simple para verificar la conexión a la base de datos
err = db.Ping()
assert.NoError(t, err)
}
31 changes: 31 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,36 @@ services:
volumes:
- mysql-data:/var/lib/mysql

mysql_test:
image: mysql:latest
container_name: repository-mysql-test
environment:
MYSQL_USER: ${DB_TEST_USERNAME}
MYSQL_PASSWORD: ${DB_TEST_PASSWORD}
MYSQL_ROOT_PASSWORD: ${DB_TEST_PASSWORD}
ports:
- "3307:3306"
volumes:
- mysql-data-test:/var/lib/mysql

postgres:
image: postgres:13
container_name: repository-postgres
environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
ports:
- "5436:5432"

postgres_test:
image: postgres:13
container_name: repository-postgres-test
environment:
POSTGRES_USER: ${DB_TEST_USERNAME}
POSTGRES_PASSWORD: ${DB_TEST_PASSWORD}
ports:
- "5438:5432"

volumes:
mysql-data:
mysql-data-test:
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/go-chi/render v1.0.3
github.com/go-sql-driver/mysql v1.7.1
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.8.4
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
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/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down
16 changes: 13 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@ go run main.go run
go run main.go migrate
```

### Testing
````shell
#### Testing

```bash
go test -cover ./...
````
```
```bash
go clean -testcache
```
```bash
go test ./... -coverprofile=coverage.out
```
```bash
go tool cover -html=coverage.out
```

### Start Mysql Services
```shell
Expand Down
Loading

0 comments on commit e4ced52

Please sign in to comment.