Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove database interface #220

Merged
merged 3 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ linters-settings:
- ok
- ip
- no
- td # test_data
- ts # test_suite
- db
- tt # table tests
- i # i *discordgo.InteractionCreate
Expand Down
1 change: 0 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ devtools:
mock:
mockgen -source=./pkg/client/interface.go -destination=./pkg/client/mock.go -package=client
mockgen -source=./pkg/wallet/interface.go -destination=./pkg/wallet/mock.go -package=wallet
mockgen -source=./internal/repository/interface.go -destination=./internal/repository/mock.go -package=repository

### proto file generate
proto:
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func run(cmd *cobra.Command, _ []string) {
return
}

response := botEngine.ParseAndExecute(entity.AppIDCLI, "0", input)
response := botEngine.ParseAndExecute(entity.PlatformIDCLI, "0", input)

cmd.Printf("%v\n%v", response.Title, response.Message)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ require (
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.10.0
go.uber.org/mock v0.5.0
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67
golang.org/x/text v0.21.0
google.golang.org/grpc v1.69.2
google.golang.org/protobuf v1.36.1
Expand Down Expand Up @@ -58,6 +57,7 @@ require (
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/x448/float16 v0.8.4 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20241223144023-3abc09e42ca8 // indirect
Expand Down
2 changes: 1 addition & 1 deletion internal/delivery/grpc/pagu.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func newPaguServer(server *Server) *paguServer {
}

func (ps *paguServer) Run(_ context.Context, req *pagu.RunRequest) (*pagu.RunResponse, error) {
res := ps.engine.ParseAndExecute(entity.AppIDgRPC, req.Id, req.Command)
res := ps.engine.ParseAndExecute(entity.PlatformIDWeb, req.Id, req.Command)

return &pagu.RunResponse{
Response: res.Message,
Expand Down
2 changes: 1 addition & 1 deletion internal/delivery/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (hh *HTTPHandler) Run(ctx echo.Context) error {
return err
}

cmdResult := hh.engine.ParseAndExecute(entity.AppIDHTTP, ctx.RealIP(), r.Command)
cmdResult := hh.engine.ParseAndExecute(entity.PlatformIDReserved, ctx.RealIP(), r.Command)

return ctx.JSON(http.StatusOK, RunResponse{
Result: cmdResult.Message,
Expand Down
4 changes: 2 additions & 2 deletions internal/engine/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type Command struct {
Name string
Help string
Args []Args // should be nil for commands.
AppIDs []entity.AppID
AppIDs []entity.PlatformID
SubCommands []*Command
Middlewares []MiddlewareFunc
Handler HandlerFunc
Expand Down Expand Up @@ -100,7 +100,7 @@ func (cmd *Command) HelpResult() CommandResult {
}
}

func (cmd *Command) HasAppID(appID entity.AppID) bool {
func (cmd *Command) HasAppID(appID entity.PlatformID) bool {
return slices.Contains(cmd.AppIDs, appID)
}

Expand Down
4 changes: 2 additions & 2 deletions internal/engine/command/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import (
type MiddlewareFunc func(caller *entity.User, cmd *Command, args map[string]string) error

type MiddlewareHandler struct {
db repository.IDatabase
db *repository.Database
wallet wallet.IWallet
}

func NewMiddlewareHandler(d repository.IDatabase, w wallet.IWallet) *MiddlewareHandler {
func NewMiddlewareHandler(d *repository.Database, w wallet.IWallet) *MiddlewareHandler {
return &MiddlewareHandler{
db: d,
wallet: w,
Expand Down
8 changes: 4 additions & 4 deletions internal/engine/command/phoenix/faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ func (pt *Phoenix) faucetHandler(
}

if err = pt.db.AddFaucet(&entity.PhoenixFaucet{
UserID: caller.ID,
Address: toAddr,
Amount: pt.faucetAmount,
TransactionHash: txHash,
UserID: caller.ID,
Address: toAddr,
Amount: pt.faucetAmount,
TxHash: txHash,
}); err != nil {
return cmd.ErrorResult(err)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/engine/command/phoenix/phoenix.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ const (
type Phoenix struct {
ctx context.Context
wallet wallet.IWallet
db repository.IDatabase
db *repository.Database
clientMgr client.IManager
faucetAmount amount.Amount
}

func NewPhoenix(ctx context.Context, wlt wallet.IWallet, faucetAmount amount.Amount,
clientMgr client.IManager, db repository.IDatabase,
clientMgr client.IManager, db *repository.Database,
) *Phoenix {
return &Phoenix{
ctx: ctx,
Expand Down
7 changes: 5 additions & 2 deletions internal/engine/command/phoenix/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
)

//nolint:unused // remove me after I am used
func (pt *Phoenix) walletHandler(cmd *command.Command, _ entity.AppID, _ string, _ ...string) command.CommandResult {
return cmd.SuccessfulResultF("Pagu Phoenix Address: %s\nBalance: %d", pt.wallet.Address(), pt.wallet.Balance())
func (pt *Phoenix) walletHandler(cmd *command.Command,
_ entity.PlatformID, _ string, _ ...string,
) command.CommandResult {
return cmd.SuccessfulResultF(
"Pagu Phoenix Address: %s\nBalance: %d", pt.wallet.Address(), pt.wallet.Balance())
}
109 changes: 38 additions & 71 deletions internal/engine/command/voucher/claim_test.go
Original file line number Diff line number Diff line change
@@ -1,103 +1,70 @@
package voucher

import (
"errors"
"testing"

"github.com/pagu-project/pagu/internal/engine/command"
"github.com/pagu-project/pagu/internal/entity"
"github.com/pagu-project/pagu/pkg/amount"
"github.com/stretchr/testify/assert"
"go.uber.org/mock/gomock"
)

func TestClaimNormal(t *testing.T) {
voucher, db, client, wallet := setup(t)
func TestClaim(t *testing.T) {
td := setup(t)

validatorAddr := "pc1p123"
t.Run("normal", func(t *testing.T) {
amt, _ := amount.NewAmount(100)
db.EXPECT().GetVoucherByCode("12345678").Return(
entity.Voucher{
ValidMonths: 1,
Amount: amt,
ID: 1,
}, nil,
).AnyTimes()
voucherCode := "12345678"
caller := &entity.User{DBModel: entity.DBModel{ID: 1}}
cmd := &command.Command{}

t.Run("Invalid Voucher Code", func(t *testing.T) {
args := make(map[string]string)
args["code"] = "0"
args["address"] = "pc1z"
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, length must be 8")
})

client.EXPECT().GetValidatorInfo(validatorAddr).Return(
t.Run("Voucher Code Not Issued Yet", func(t *testing.T) {
args := make(map[string]string)
args["code"] = voucherCode
args["address"] = "pc1z"
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, no voucher found")
})

t.Run("Claim a Voucher", func(t *testing.T) {
testVoucher := td.createTestVoucher(t, WithCode(voucherCode))
validatorAddr := "pc1p123"

td.clientManager.EXPECT().GetValidatorInfo(validatorAddr).Return(
nil, nil,
).AnyTimes()

client.EXPECT().FindPublicKey(validatorAddr, false).Return(
td.clientManager.EXPECT().FindPublicKey(validatorAddr, false).Return(
validatorAddr, nil,
).AnyTimes()

wallet.EXPECT().BondTransaction(validatorAddr, validatorAddr, "voucher 12345678 claimed by Pagu", amt).Return(
td.wallet.EXPECT().BondTransaction(gomock.Any(), validatorAddr,
"voucher 12345678 claimed by Pagu", testVoucher.Amount).Return(
"0x1", nil,
).AnyTimes()

db.EXPECT().ClaimVoucher(uint(1), "0x1", uint(1)).Return(
nil,
).AnyTimes()

cmd := &command.Command{}
caller := &entity.User{ID: 1}

args := make(map[string]string)
args["code"] = "12345678"
args["code"] = testVoucher.Code
args["address"] = validatorAddr
result := voucher.claimHandler(caller, cmd, args)
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.True(t, result.Successful)
assert.Equal(t, result.Message, "Voucher claimed successfully!\n\n https://pacviewer.com/transaction/0x1")
})

t.Run("wrong code", func(t *testing.T) {
cmd := &command.Command{}
caller := &entity.User{ID: 1}

t.Run("Claim again", func(t *testing.T) {
args := make(map[string]string)
args["code"] = "0"
args["code"] = voucherCode
args["address"] = "pc1z"
result := voucher.claimHandler(caller, cmd, args)
result := td.voucherCmd.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, length must be 8")
assert.Equal(t, result.Message, "An error occurred: voucher code claimed before")
})
}

func TestClaimNotFound(t *testing.T) {
voucher, db, _, _ := setup(t)

db.EXPECT().GetVoucherByCode("12345678").Return(
entity.Voucher{}, errors.New(""),
).AnyTimes()

cmd := &command.Command{}
caller := &entity.User{ID: 1}

args := make(map[string]string)
args["code"] = "12345678"
args["address"] = "pc1z"
result := voucher.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code is not valid, no voucher found")
}

func TestClaimAlreadyClaimed(t *testing.T) {
voucher, db, _, _ := setup(t)

db.EXPECT().GetVoucherByCode("12345678").Return(
entity.Voucher{
TxHash: "123456789",
}, nil,
).AnyTimes()

cmd := &command.Command{}
caller := &entity.User{ID: 1}

args := make(map[string]string)
args["code"] = "12345678"
args["address"] = "pc1z"
result := voucher.claimHandler(caller, cmd, args)
assert.False(t, result.Successful)
assert.Equal(t, result.Message, "An error occurred: voucher code claimed before")
}
Loading
Loading