Skip to content

Commit

Permalink
Add initial faucet tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zivkovicmilos committed Sep 15, 2023
1 parent b21c9d2 commit 634402b
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 14 deletions.
24 changes: 17 additions & 7 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ const (
DefaultNumAccounts = uint64(1)
)

var (
ErrInvalidListenAddress = errors.New("invalid listen address")
ErrInvalidChainID = errors.New("invalid chain ID")
ErrInvalidSendAmount = errors.New("invalid send amount")
ErrInvalidGasFee = errors.New("invalid gas fee")
ErrInvalidGasWanted = errors.New("invalid gas wanted")
ErrInvalidMnemonic = errors.New("invalid mnemonic")
ErrInvalidNumAccounts = errors.New("invalid number of faucet accounts")
)

var (
listenAddressRegex = regexp.MustCompile(`^\d{1,3}(\.\d{1,3}){3}:\d+$`)
amountRegex = regexp.MustCompile(`^\d+ugnot$`)
Expand Down Expand Up @@ -74,37 +84,37 @@ func DefaultConfig() *Config {
func ValidateConfig(config *Config) error {
// validate the listen address
if !listenAddressRegex.Match([]byte(config.ListenAddress)) {
return errors.New("invalid listen address")
return ErrInvalidListenAddress
}

// validate the chain ID
if config.ChainID == "" {
return errors.New("invalid chain ID")
return ErrInvalidChainID
}

// validate the send amount
if !amountRegex.Match([]byte(config.SendAmount)) {
return errors.New("invalid send amount")
return ErrInvalidSendAmount
}

// validate the gas fee
if !amountRegex.Match([]byte(config.GasFee)) {
return errors.New("invalid gas fee")
return ErrInvalidGasFee
}

// validate the gas wanted
if !numberRegex.Match([]byte(config.GasWanted)) {
return errors.New("invalid gas wanted")
return ErrInvalidGasWanted
}

// validate the mnemonic is bip39-compliant
if !bip39.IsMnemonicValid(config.Mnemonic) {
return fmt.Errorf("invalid mnemonic, %s", config.Mnemonic)
return fmt.Errorf("%w, %s", ErrInvalidMnemonic, config.Mnemonic)
}

// validate at least one faucet account is set
if config.NumAccounts < 1 {
return errors.New("invalid number of faucet accounts")
return ErrInvalidNumAccounts
}

return nil
Expand Down
80 changes: 80 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package config

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestConfig_ValidateConfig(t *testing.T) {
t.Parallel()

t.Run("invalid listen address", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.ListenAddress = "gno.land" // doesn't follow the format

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidListenAddress)
})

t.Run("invalid chain ID", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.ChainID = "" // empty

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidChainID)
})

t.Run("invalid send amount", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.SendAmount = "1000goo" // invalid denom

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidSendAmount)
})

t.Run("invalid gas fee", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.GasFee = "1000goo" // invalid denom

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidGasFee)
})

t.Run("invalid gas wanted", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.GasWanted = "totally a number" // invalid number

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidGasWanted)
})

t.Run("invalid mnemonic", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.Mnemonic = "maybe valid mnemonic" // invalid mnemonic

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidMnemonic)
})

t.Run("invalid num accounts", func(t *testing.T) {
t.Parallel()

cfg := DefaultConfig()
cfg.NumAccounts = 0 // invalid number of accounts

assert.ErrorIs(t, ValidateConfig(cfg), ErrInvalidNumAccounts)
})

t.Run("valid configuration", func(t *testing.T) {
t.Parallel()

assert.NoError(t, ValidateConfig(DefaultConfig()))
})
}
9 changes: 7 additions & 2 deletions faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/gnolang/faucet/estimate"
"github.com/gnolang/faucet/log"
"github.com/gnolang/faucet/log/noop"
"github.com/gnolang/gno/tm2/pkg/std"
"github.com/go-chi/chi/v5"
"github.com/rs/cors"
"golang.org/x/sync/errgroup"
Expand All @@ -29,7 +30,8 @@ type Faucet struct {
middlewares []Middleware // request middlewares
handlers []Handler // request handlers

keyring *keyring // the faucet keyring
keyring *keyring // the faucet keyring
sendAmount std.Coins // for fast lookup
}

// NewFaucet creates a new instance of the Gno faucet server
Expand Down Expand Up @@ -66,6 +68,9 @@ func NewFaucet(
return nil, fmt.Errorf("invalid configuration, %w", err)
}

// Set the send amount
f.sendAmount, _ = std.ParseCoins(f.config.SendAmount)

// Generate the keyring
f.keyring = newKeyring(f.config.Mnemonic, f.config.NumAccounts)

Expand All @@ -87,7 +92,7 @@ func NewFaucet(

// Set up the request handlers
for _, handler := range f.handlers {
f.mux.HandleFunc(handler.Pattern, handler.HandlerFunc)
f.mux.Post(handler.Pattern, handler.HandlerFunc)
}

return f, nil
Expand Down
141 changes: 141 additions & 0 deletions faucet_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package faucet

import (
"net/http"
"testing"

"github.com/gnolang/faucet/config"
"github.com/gnolang/faucet/log/noop"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestFaucet_NewFaucet(t *testing.T) {
t.Parallel()

t.Run("valid config", func(t *testing.T) {
t.Parallel()

f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(config.DefaultConfig()),
)

assert.NotNil(t, f)
assert.NoError(t, err)
})

t.Run("invalid config", func(t *testing.T) {
t.Parallel()

// Create an invalid configuration
invalidCfg := config.DefaultConfig()
invalidCfg.NumAccounts = 0

// Create a faucet instance with the invalid configuration
f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(invalidCfg),
)

// Make sure the error was caught
assert.Nil(t, f)
assert.ErrorIs(t, err, config.ErrInvalidNumAccounts)
})

t.Run("with CORS config", func(t *testing.T) {
t.Parallel()

// Example CORS config
corsConfig := config.DefaultCORSConfig()
corsConfig.AllowedOrigins = []string{"gno.land"}

validCfg := config.DefaultConfig()
validCfg.CORSConfig = corsConfig

// Create a valid faucet instance
// with a valid CORS configuration
f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(validCfg),
)

assert.NotNil(t, f)
assert.NoError(t, err)
})

t.Run("with middlewares", func(t *testing.T) {
t.Parallel()

middlewares := []Middleware{
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Example empty middleware
next.ServeHTTP(w, r)
})
},
}

cfg := config.DefaultConfig()
cfg.CORSConfig = nil // disable CORS middleware

f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(cfg),
WithMiddlewares(middlewares),
)

require.NotNil(t, f)
assert.NoError(t, err)

// Make sure the middleware was set
assert.Len(t, f.mux.Middlewares(), len(middlewares))
})

t.Run("with handlers", func(t *testing.T) {
t.Parallel()

handlers := []Handler{
{
Pattern: "/hello",
HandlerFunc: func(_ http.ResponseWriter, _ *http.Request) {
// Empty handler
},
},
}

f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(config.DefaultConfig()),
WithHandlers(handlers),
)

require.NotNil(t, f)
assert.NoError(t, err)

// Make sure the handler was set
routes := f.mux.Routes()
require.Len(t, routes, len(handlers)+1) // base "/" handler as well

assert.Equal(t, handlers[0].Pattern, routes[1].Pattern)
})

t.Run("with logger", func(t *testing.T) {
t.Parallel()

f, err := NewFaucet(
&mockEstimator{},
&mockClient{},
WithConfig(config.DefaultConfig()),
WithLogger(noop.New()),
)

assert.NotNil(t, f)
assert.NoError(t, err)
})
}
2 changes: 1 addition & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ func WithMiddlewares(middlewares []Middleware) Option {
// WithHandlers specifies the HTTP handlers for the faucet
func WithHandlers(handlers []Handler) Option {
return func(f *Faucet) {
f.handlers = handlers
f.handlers = append(f.handlers, handlers...)
}
}
6 changes: 2 additions & 4 deletions transfer.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ func (f *Faucet) transferFunds(address crypto.Address) error {
// findFundedAccount finds an account
// whose balance is enough to cover the send amount
func (f *Faucet) findFundedAccount() (std.Account, error) {
sendAmount, _ := std.ParseCoins(f.config.SendAmount)

for _, address := range f.keyring.getAddresses() {
// Fetch the account
account, err := f.client.GetAccount(address)
Expand All @@ -69,15 +67,15 @@ func (f *Faucet) findFundedAccount() (std.Account, error) {
balance := account.GetCoins()

// Make sure there are enough funds
if balance.IsAllLT(sendAmount) {
if balance.IsAllLT(f.sendAmount) {
f.logger.Error(
"account cannot serve requests",
"address",
address.String(),
"balance",
balance.String(),
"amount",
sendAmount,
f.sendAmount,
)

continue
Expand Down

0 comments on commit 634402b

Please sign in to comment.