package db import ( "bankline/internal/admin/auth" "bankline/pkg/logging" "errors" "github.com/stretchr/testify/assert" "golang.org/x/net/context" "regexp" "testing" "github.com/pashagolub/pgxmock" ) var ( // prepare mock colums = []string{"id", "password"} // request req = auth.LoginDTO{ Login: "admin@admin.com", } // expected want = auth.ResLoginDTO{ Id: 1, Password: "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i", } ) // Setup will prepare mock and account service instance func Run(t *testing.T) pgxmock.PgxPoolIface { t.Helper() mock, err := pgxmock.NewPool() if err != nil { t.Errorf("unexpected error occur: %v\n", err) } defer mock.Close() return mock } func TestGet(t *testing.T) { mock := Run(t) q := `select id, password from admin where login = $1 ;` t.Run("EXPECT SUCCESS", func(t *testing.T) { mock.ExpectQuery(regexp.QuoteMeta(q)). WithArgs(req.Login). WillReturnRows(mock.NewRows(colums). AddRow(1, "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i")) // actual logger := logging.GetLogger() ops := NewRepository(mock, logger) got, err := ops.Login(context.Background(), req) assert.NoError(t, err) assert.Equal(t, got.Id, want.Id) assert.Equal(t, got, want) }) t.Run("EXPECT FAIL", func(t *testing.T) { mock.ExpectQuery(regexp.QuoteMeta(q)). WithArgs(req.Login). WillReturnError(errors.New("error getting user data")) // actual logger := logging.GetLogger() ops := NewRepository(mock, logger) got, err := ops.Login(context.Background(), req) assert.Error(t, err) if got.Id == 0 { assert.Nil(t, nil) } }) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectation: %v\n", err) } }