From 8a81173fc81fa3289dba89a5deae3730d7dc3e8c Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Wed, 26 Jun 2024 16:15:33 +0200 Subject: [PATCH] Update method tests --- app/repository/method_update.go | 4 +-- app/repository/method_update_test.go | 43 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 app/repository/method_update_test.go diff --git a/app/repository/method_update.go b/app/repository/method_update.go index 82a0d40..b561cb1 100644 --- a/app/repository/method_update.go +++ b/app/repository/method_update.go @@ -14,7 +14,7 @@ func (m *UpdateMethod[T]) Init(repo *RepoBase[T]) { m.repo = repo } -func (m UpdateMethod[T]) Update(filter interface{}, values map[string]interface{}) (int64, error) { +func (m UpdateMethod[T]) Update(filter interface{}, values map[string]any) (int64, error) { var ( model T ) @@ -23,7 +23,7 @@ func (m UpdateMethod[T]) Update(filter interface{}, values map[string]interface{ if err != nil { return 0, err } - result := query.Updates(values) + result := query.Model(&model).Updates(values) if result.Error != nil { return 0, result.Error } diff --git a/app/repository/method_update_test.go b/app/repository/method_update_test.go new file mode 100644 index 0000000..8c0c0b0 --- /dev/null +++ b/app/repository/method_update_test.go @@ -0,0 +1,43 @@ +package repository + +import ( + "fmt" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/assert" +) + +func TestUpdateMethod(t *testing.T) { + t.Run("Update", func(t *testing.T) { + sqldb, db, mock := NewMockDB() + defer sqldb.Close() + + repo := RepoBase[MyModel]{} + repo.Init(db, nil) + + cnt := 10 + filter := MyModelFilter{ + CntGT: &cnt, + } + values := map[string]any{ + "cnt": 111, + "value": 222, + } + + sql := "UPDATE my_models SET cnt=$1,value=$2 WHERE my_models.cnt > $3" + mock.ExpectBegin() + mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))). + WithArgs(values["cnt"], values["value"], cnt). + WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectCommit() + + _, err := repo.Update(filter, values) + assert.Nil(t, err) + + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("there were unfulfilled expectations: %s", err) + } + }) +}