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

Add enviroment variable support for unit testing #176

Merged
merged 3 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
15 changes: 11 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,25 @@ import (
// eg., `INFURA_LOG_LEVEL` will override "log.level" config item from the config file.
const viperEnvPrefix = "infura"

// Logrus logging levels for alert hooking.
var alertHookLevels = []logrus.Level{
logrus.FatalLevel, logrus.WarnLevel, logrus.ErrorLevel,
}

func Init() {
// init viper
viper.MustInit(viperEnvPrefix)
// init logger
initLogger()

// init pprof
pprof.MustInit()
// init metrics
metrics.MustInit()
// init alert
alert.InitDingRobot()
// init misc util
rpcutil.MustInit()
blacklist.MustInit()

// init store
store.MustInit()
// init node
Expand Down Expand Up @@ -70,8 +75,10 @@ func initLogger() {
}

// add alert hook for logrus fatal/warn/error level
hookLevels := []logrus.Level{logrus.FatalLevel, logrus.WarnLevel, logrus.ErrorLevel}
logrus.AddHook(alert.NewLogrusAlertHook(hookLevels))
alerter := alert.MustNewDingTalkAlerterFromViper()
if alerter != nil {
logrus.AddHook(alert.NewLogrusAlertHook(alerter, alertHookLevels))
}

// customize logger here...
adaptGethLogger()
Expand Down
56 changes: 25 additions & 31 deletions rpc/ethbridge/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"testing"

"github.com/Conflux-Chain/confura/rpc/cfxbridge"
sdk "github.com/Conflux-Chain/go-conflux-sdk"
"github.com/ethereum/go-ethereum/common"
"github.com/openweb3/web3go"
ethTypes "github.com/openweb3/web3go/types"
Expand All @@ -14,57 +13,52 @@ import (
)

var (
ethHttpNode = "http://evmtestnet.confluxrpc.com"
cfxHttpNode = "http://test.confluxrpc.com"

ethClient *web3go.Client
cfxClient sdk.ClientOperator

ethClient *web3go.Client
ethNetworkId *uint64
)

func setup() error {
var err error
// Please set the following enviroment before start:
// `TEST_ETH_CLIENT_ENDPOINT`: EVM space JSON-RPC endpoint to construct sdk client.

if ethClient, err = web3go.NewClient(ethHttpNode); err != nil {
return errors.WithMessage(err, "failed to new web3go client")
func TestMain(m *testing.M) {
if err := setup(); err != nil {
panic(errors.WithMessage(err, "failed to setup"))
}

if ethNetworkId, err = ethClient.Eth.ChainId(); err != nil {
return errors.WithMessage(err, "failed to get eth chainid")
code := 0
if ethClient != nil {
code = m.Run()
}

if cfxClient, err = sdk.NewClient(cfxHttpNode); err != nil {
return errors.WithMessage(err, "failed to new cfx client")
if err := teardown(); err != nil {
panic(errors.WithMessage(err, "failed to tear down"))
}

return nil
os.Exit(code)
}

func teardown() (err error) {
if ethClient != nil {
ethClient.Provider().Close()
func setup() error {
ethHttpNode := os.Getenv("TEST_ETH_CLIENT_ENDPOINT")
if len(ethHttpNode) == 0 {
return nil
}

if cfxClient != nil {
cfxClient.Close()
ethClient = web3go.MustNewClient(ethHttpNode)
chainId, err := ethClient.Eth.ChainId()
if err != nil {
return errors.WithMessage(err, "failed to get eth chainid")
}

ethNetworkId = chainId
return nil
}

func TestMain(m *testing.M) {
if err := setup(); err != nil {
panic(errors.WithMessage(err, "failed to setup"))
}

code := m.Run()

if err := teardown(); err != nil {
panic(errors.WithMessage(err, "failed to tear down"))
func teardown() (err error) {
if ethClient != nil {
ethClient.Provider().Close()
}

os.Exit(code)
return nil
}

func TestConvertBlockHeader(t *testing.T) {
Expand Down
80 changes: 53 additions & 27 deletions test/_rpc_test.go → test/rpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,71 @@ package test
import (
"encoding/json"
"math/big"
"os"
"testing"
"time"

"github.com/Conflux-Chain/confura/util/rpc"
sdk "github.com/Conflux-Chain/go-conflux-sdk"
"github.com/Conflux-Chain/go-conflux-sdk/types"
"github.com/Conflux-Chain/go-conflux-sdk/types/cfxaddress"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

var (
fullnode = rpc.MustNewCfxClient(
"http://main.confluxrpc.org/v2",
rpc.WithClientRetryCount(3),
rpc.WithClientRetryInterval(time.Second),
rpc.WithClientRequestTimeout(time.Second),
)
// CHANGE TO INFURA URL BELOW TO TEST
infura = rpc.MustNewCfxClient(
"http://main.confluxrpc.org/v2",
rpc.WithClientRetryCount(3),
rpc.WithClientRetryInterval(time.Second),
rpc.WithClientRequestTimeout(time.Second),
)
fullnode, infura sdk.ClientOperator

wcfx = cfxaddress.MustNewFromBase32("cfx:acg158kvr8zanb1bs048ryb6rtrhr283ma70vz70tx")
wcfxTest = cfxaddress.MustNewFromBase32("cfxtest:achs3nehae0j6ksvy1bhrffsh1rtfrw1f6w1kzv46t")
)

// Please set the following enviroments to start:
// `TEST_CFX_FULL_NODE`: Core space full node endpoint as benchmarking data source.
// `TEST_CFX_INFURA_NODE`: Core space infura service endpoint to be validated against.

func TestMain(m *testing.M) {
if err := setup(); err != nil {
panic(errors.WithMessage(err, "failed to setup"))
}

code := 0
if fullnode != nil && infura != nil {
code = m.Run()
}

if err := teardown(); err != nil {
panic(errors.WithMessage(err, "failed to tear down"))
}

os.Exit(code)
}

func setup() error {
cfxHttpNode := os.Getenv("TEST_CFX_FULL_NODE")
if len(cfxHttpNode) > 0 {
fullnode = sdk.MustNewClient(cfxHttpNode)
}

cfxHttpNode = os.Getenv("TEST_CFX_INFURA_NODE")
if len(cfxHttpNode) > 0 {
infura = sdk.MustNewClient(cfxHttpNode)
}

return nil
}

func teardown() (err error) {
if fullnode != nil {
fullnode.Close()
}

if infura != nil {
infura.Close()
}

return nil
}

func mustGetTestEpoch(t require.TestingT, epoch *types.Epoch, deltaToLatestState int64) *types.Epoch {
num, err := fullnode.GetEpochNumber(epoch)
require.NoError(t, err)
Expand Down Expand Up @@ -74,11 +110,11 @@ func TestGetAdmin(t *testing.T) {
func testGetLogs(t *testing.T, expectedCount int, filter types.LogFilter) {
logs1, err := fullnode.GetLogs(filter)
require.NoError(t, err)
assert.Equal(t, len(logs1), expectedCount)
assert.Equal(t, expectedCount, len(logs1))

logs2, err := infura.GetLogs(filter)
require.NoError(t, err)
assert.Equal(t, len(logs2), expectedCount)
assert.Equal(t, expectedCount, len(logs2))

json1 := mustMarshalJSON(t, logs1)
json2 := mustMarshalJSON(t, logs2)
Expand All @@ -104,8 +140,6 @@ func TestGetLogs(t *testing.T) {

// filter: blocks
testGetLogs(t, 17, types.LogFilter{
FromEpoch: types.NewEpochNumberUint64(10477303),
ToEpoch: types.NewEpochNumberUint64(10477315),
BlockHashes: []types.Hash{
types.Hash("0x9071c4446dfe9a8ce22175863c53b3b99bd596d89470423c5bb4a262c4a8716c"),
types.Hash("0x3e722a9a61ada255c334d7fea10179b6ae6f084af293e1ef136a7b6f856edbcf"),
Expand All @@ -114,8 +148,6 @@ func TestGetLogs(t *testing.T) {

// filter: contract address + blocks
testGetLogs(t, 6, types.LogFilter{
FromEpoch: types.NewEpochNumberUint64(10477303),
ToEpoch: types.NewEpochNumberUint64(10477315),
Address: []types.Address{
cfxaddress.MustNewFromBase32("cfx:acckucyy5fhzknbxmeexwtaj3bxmeg25b2b50pta6v"),
cfxaddress.MustNewFromBase32("cfx:acdrf821t59y12b4guyzckyuw2xf1gfpj2ba0x4sj6"),
Expand All @@ -135,12 +167,6 @@ func TestGetLogs(t *testing.T) {
{types.Hash("0x0000000000000000000000001e61c5dab363c1fdb903b61178b380d2cc7df999")},
},
})

// filter: limit
testGetLogs(t, 8, types.LogFilter{
FromEpoch: types.NewEpochNumberUint64(10477303),
ToEpoch: types.NewEpochNumberUint64(10477315),
})
}

func TestErrorWithData(t *testing.T) {
Expand Down
22 changes: 0 additions & 22 deletions util/alert/_alert_test.go

This file was deleted.

36 changes: 0 additions & 36 deletions util/alert/_logrus_hook_test.go

This file was deleted.

64 changes: 64 additions & 0 deletions util/alert/alert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package alert

import (
"os"
"testing"

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

var (
alerter *DingTalkAlerter
)

// Please set the following enviroments to start:
// `TEST_DINGTALK_WEBHOOK`: webhook URL for dingtalk channel.
// `TEST_DINGTALK_SECRET`: secret for authentication.

func TestMain(m *testing.M) {
if err := setup(); err != nil {
panic(errors.WithMessage(err, "failed to setup"))
}

code := m.Run()

if err := teardown(); err != nil {
panic(errors.WithMessage(err, "failed to tear down"))
}

os.Exit(code)
}

func setup() error {
webhook := os.Getenv("TEST_DINGTALK_WEBHOOK")
secret := os.Getenv("TEST_DINGTALK_SECRET")

if len(webhook) == 0 || len(secret) == 0 {
return nil
}

alerter = NewDingTalkAlerter(AlertConfig{
DingTalk: DingTalkConfig{
Enabled: true,
WebHook: webhook,
Secret: secret,
},
})

return nil
}

func teardown() (err error) {
// nothing needs to be done
return nil
}

func TestDingTalkAlert(t *testing.T) {
if alerter == nil {
t.SkipNow()
}

err := alerter.Send("info", "hi", "this is a test")
assert.NoError(t, err)
}
Loading
Loading