package mysqldriver import ( "context" "git.aiterp.net/stufflog/server/internal/slerrors" "git.aiterp.net/stufflog/server/models" "github.com/stretchr/testify/assert" "testing" "time" ) var user1 = models.User{ ID: "Test", Name: "Testy Tester", Active: true, Admin: false, Hash: []byte("$2y$12$tj/R/zDHrGy1Jsi57DUuSeCISYvEHb/F37p.9HGlyf72cIXnppeQK"), } var user2 = models.User{ ID: "Admin", Name: "Administrator", Active: true, Admin: true, Hash: []byte("$2y$12$tj/R/zDHrGy1Jsi57DUuSeCISYvEHb/F37p.9HGlyf72cIXnppeQK"), } var user2Updated = models.User{ ID: user2.ID, Name: "Dethroned Dictator", Active: false, Admin: false, Hash: []byte("$2y$12$7MuqYzV59HCtHJlRJCd/vOQIrFcMEMVhyySzJX.WlVtEJH3qHVPU2\n"), } func TestUserRepository(t *testing.T) { users := testDB.users ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() assert.NoError(t, clearTable("user")) // INSERT result, err := users.Insert(ctx, user1) assert.NoError(t, err) assert.Equal(t, user1, *result) result, err = users.Insert(ctx, user2) assert.NoError(t, err) assert.Equal(t, user2, *result) // FIND result, err = users.Find(ctx, user1.ID) assert.NoError(t, err) assert.Equal(t, &user1, result) result, err = users.Find(ctx, user2.ID) assert.NoError(t, err) assert.Equal(t, &user2, result) // FIND't result, err = users.Find(ctx, "NonExistent") assert.Error(t, err) assert.True(t, slerrors.IsNotFound(err)) assert.Nil(t, result) // LIST results, err := users.List(ctx, models.UserFilter{}) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2, &user1}, results) results, err = users.List(ctx, models.UserFilter{ Admin: ptrBool(true), }) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2}, results) results, err = users.List(ctx, models.UserFilter{ Active: ptrBool(true), }) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2, &user1}, results) results, err = users.List(ctx, models.UserFilter{ Active: ptrBool(false), }) assert.NoError(t, err) assert.Equal(t, []*models.User{}, results) results, err = users.List(ctx, models.UserFilter{ UserIDs: []string{user1.ID}, }) assert.NoError(t, err) assert.Equal(t, []*models.User{&user1}, results) results, err = users.List(ctx, models.UserFilter{ Limit: ptrInt(1), }) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2}, results) // UPDATE err = users.Save(ctx, user2Updated) assert.NoError(t, err) // LIST after UPDATE results, err = users.List(ctx, models.UserFilter{}) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2Updated, &user1}, results) // DELETE err = users.Delete(ctx, user1) assert.NoError(t, err) // LIST after DELETE results, err = users.List(ctx, models.UserFilter{}) assert.NoError(t, err) assert.Equal(t, []*models.User{&user2Updated}, results) // INSERT after DELETE result, err = users.Insert(ctx, user1) assert.NoError(t, err) assert.Equal(t, user1, *result) }