add test for Func Create tables

main
Shuhrat Tultaganov 2022-12-13 19:24:42 +03:00
parent 1524ebced8
commit cdc88752da
7 changed files with 109 additions and 23 deletions

View File

@ -7,8 +7,9 @@ import (
)
type Bd struct {
config *ConfigBD
db *sql.DB
config *ConfigBD
db *sql.DB
filmsrepo *Filmsrepo
}
func New(config *ConfigBD) *Bd {
@ -32,3 +33,15 @@ func (b *Bd) Open() error {
func (b *Bd) Close() {
b.db.Close()
}
func (b *Bd) Films() *Filmsrepo {
if b.filmsrepo != nil {
return b.filmsrepo
}
b.filmsrepo = &Filmsrepo{
db: *b,
}
return b.filmsrepo
}

View File

@ -0,0 +1,19 @@
package bd_test
import (
"os"
"testing"
)
var (
database string
)
func TestMain(m *testing.M) {
database := os.Getenv("DATABASE_URL")
if database == "" {
database = "host=localhost user=admin password=root dbname=postgres sslmode=disable"
}
os.Exit(m.Run())
}

View File

@ -0,0 +1,22 @@
package bd_test
import (
"testing"
"git.ukamnya.ru/stulyaganov/RestApi/internal/bd"
"git.ukamnya.ru/stulyaganov/RestApi/internal/bd/model"
"github.com/stretchr/testify/assert"
)
func TestFilmRepo_Create(t *testing.T) {
s, teardown := bd.Testdb(t, "host=localhost user=admin password=root dbname=postgres sslmode=disable")
defer teardown("films")
u, err := s.Films().Create(&model.Films{
Id: 0,
Ru_title: "sdasdasda",
})
assert.NoError(t, err)
assert.NotNil(t, u)
}

View File

@ -0,0 +1,24 @@
package bd
import (
"git.ukamnya.ru/stulyaganov/RestApi/internal/bd/model"
)
type Filmsrepo struct {
db Bd
}
func (f *Filmsrepo) Create(m *model.Films) (*model.Films, error) {
if err := f.db.db.QueryRow(
"INSERT INTO films (id, ru_title, orig_title) VALUES($1, $2, $3) RETURNING id",
m.Id, m.Ru_title, m.Orig_title).Scan(&m.Id); err != nil {
return nil, err
}
return m, nil
}
func FindDyId(id int) (*model.Films, error) {
return nil, nil
}

View File

@ -1,9 +1,9 @@
package model
type Films struct {
id int
ru_title string
orig_title string
Id int
Ru_title string
Orig_title string
imdb_id string
kinopoisk_id string
posterUrl string

View File

@ -1,18 +0,0 @@
package repositoryes
import (
"git.ukamnya.ru/stulyaganov/RestApi/internal/bd"
"git.ukamnya.ru/stulyaganov/RestApi/internal/bd/model"
)
type Filmsrepo struct {
DB *bd.Bd
}
func Create(model.Films) (*model.Films, error) {
return nil, nil
}
func FindDyId(id int) (*model.Films, error) {
return nil, nil
}

View File

@ -0,0 +1,26 @@
package bd
import (
"fmt"
"strings"
"testing"
)
func Testdb(t *testing.T, databaseurl string) (*Bd, func(...string)) {
t.Helper()
config := NewConfig()
config.BaseUrlBd = databaseurl
s := New(config)
if err := s.Open(); err != nil {
t.Fatal(err)
}
return s, func(tables ...string) {
if len(tables) > 0 {
if _, err := s.db.Exec(fmt.Sprintf("TRUNCATE %s CASCADE", strings.Join(tables, ", "))); err != nil {
t.Fatal(err)
}
}
s.Close()
}
}