lens @ 9ba05d26ee2382f3191e25ae7af5d462ba2a35e4

  1//go:build integration
  2
  3package sql
  4
  5import (
  6	"context"
  7	"os"
  8	"testing"
  9
 10	"github.com/google/go-cmp/cmp"
 11	"gorm.io/driver/sqlite"
 12	"gorm.io/gorm"
 13	"gorm.io/gorm/logger"
 14
 15	"git.sr.ht/~gabrielgio/img/pkg/components/auth"
 16)
 17
 18func setup(t *testing.T) (*gorm.DB, func()) {
 19	t.Helper()
 20
 21	file, err := os.CreateTemp("", "img_user_*.db")
 22	if err != nil {
 23		t.Fatalf("Error creating tmp error: %s", err.Error())
 24	}
 25
 26	db, err := gorm.Open(sqlite.Open(file.Name()), &gorm.Config{
 27		Logger: logger.Default.LogMode(logger.Info),
 28	})
 29	if err != nil {
 30		t.Fatalf("Error openning db, error %s", err.Error())
 31	}
 32
 33	err = Migrate(db)
 34	if err != nil {
 35		t.Fatalf("Error migrating db, error %s", err.Error())
 36	}
 37
 38	return db, func() {
 39		//nolint:errcheck
 40		os.Remove(file.Name())
 41	}
 42}
 43
 44func TestCreate(t *testing.T) {
 45	t.Parallel()
 46	db, tearDown := setup(t)
 47	defer tearDown()
 48
 49	repository := NewUserRepository(db)
 50
 51	id, err := repository.Create(context.Background(), &auth.CreateUser{
 52		Username: "new_username",
 53		Name:     "new_name",
 54	})
 55	if err != nil {
 56		t.Fatalf("Error creating: %s", err.Error())
 57	}
 58
 59	got, err := repository.Get(context.Background(), id)
 60	if err != nil {
 61		t.Fatalf("Error getting: %s", err.Error())
 62	}
 63	want := &auth.User{
 64		ID:       id,
 65		Username: "new_username",
 66		Name:     "new_name",
 67	}
 68
 69	if diff := cmp.Diff(want, got); diff != "" {
 70		t.Errorf("%s() mismatch (-want +got):\n%s", "Update", diff)
 71	}
 72}
 73
 74func TestUpdate(t *testing.T) {
 75	t.Parallel()
 76	db, tearDown := setup(t)
 77	defer tearDown()
 78
 79	repository := NewUserRepository(db)
 80
 81	id, err := repository.Create(context.Background(), &auth.CreateUser{
 82		Username: "username",
 83		Name:     "name",
 84	})
 85	if err != nil {
 86		t.Fatalf("Error creating user: %s", err.Error())
 87	}
 88
 89	err = repository.Update(context.Background(), id, &auth.UpdateUser{
 90		Username: "new_username",
 91		Name:     "new_name",
 92	})
 93	if err != nil {
 94		t.Fatalf("Error update user: %s", err.Error())
 95	}
 96
 97	got, err := repository.Get(context.Background(), id)
 98	if err != nil {
 99		t.Fatalf("Error getting user: %s", err.Error())
100	}
101	want := &auth.User{
102		ID:       id,
103		Username: "new_username",
104		Name:     "new_name",
105	}
106
107	if diff := cmp.Diff(want, got); diff != "" {
108		t.Errorf("%s() mismatch (-want +got):\n%s", "Update", diff)
109	}
110}