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

chore: add cmd test #100

Merged
merged 2 commits into from
Jul 6, 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
1 change: 1 addition & 0 deletions assets/config-invalid.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[[chains]]
File renamed without changes.
13 changes: 13 additions & 0 deletions assets/config-with-warnings.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
interval = "@hourly"

[[chains]]
name = "bitsong"
pretty-name = "Bitsong"
keplr-name = "bitsong"
mintscan-prefix = "bitsong"
lcd-endpoints = ["https://lcd-bitsong-app.cosmostation.io"]
wallets = [
{ address = "bitsong14rvn7anf22e00vj5x3al4w50ns78s7n4t8yxcy", alias = "Validator wallet" },
]
type = "cosmos"
proposals-type = "v1beta1"
2 changes: 1 addition & 1 deletion assets/fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ func TestGetPanicOrFailPanic(t *testing.T) {
func TestGetPanicOrFailOk(t *testing.T) {
t.Parallel()

bytes := GetBytesOrPanic("valid-config.toml")
bytes := GetBytesOrPanic("config-valid.toml")
assert.NotNil(t, bytes)
}
File renamed without changes.
35 changes: 7 additions & 28 deletions cmd/cosmos-proposals-checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"main/pkg"
"main/pkg/fs"
"main/pkg/logger"
"os"

"github.com/spf13/cobra"
)
Expand All @@ -13,37 +12,22 @@ var (
version = "unknown"
)

type OsFS struct {
}

func (fs *OsFS) ReadFile(name string) ([]byte, error) {
return os.ReadFile(name)
}

func (fs *OsFS) WriteFile(name string, data []byte, perms os.FileMode) error {
return os.WriteFile(name, data, perms)
}

func (fs *OsFS) Create(path string) (fs.File, error) {
return os.Create(path)
}

func ExecuteMain(configPath string) {
filesystem := &OsFS{}
filesystem := &fs.OsFS{}
app := pkg.NewApp(configPath, filesystem, version)
app.Start()
}

func ExecuteValidateConfig(configPath string) {
filesystem := &OsFS{}
filesystem := &fs.OsFS{}

config, err := pkg.GetConfig(filesystem, configPath)
if err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Could not load config!")
logger.GetDefaultLogger().Panic().Err(err).Msg("Could not load config!")
}

if err := config.Validate(); err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Config is invalid!")
logger.GetDefaultLogger().Panic().Err(err).Msg("Config is invalid!")
}

if warnings := config.DisplayWarnings(); len(warnings) > 0 {
Expand Down Expand Up @@ -75,18 +59,13 @@ func main() {
}

rootCmd.PersistentFlags().StringVar(&ConfigPath, "config", "", "Config file path")
if err := rootCmd.MarkPersistentFlagRequired("config"); err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Could not set flag as required")
}
_ = rootCmd.MarkPersistentFlagRequired("config")

validateConfigCmd.PersistentFlags().StringVar(&ConfigPath, "config", "", "Config file path")
if err := validateConfigCmd.MarkPersistentFlagRequired("config"); err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Could not set flag as required")
}

_ = validateConfigCmd.MarkPersistentFlagRequired("config")
rootCmd.AddCommand(validateConfigCmd)

if err := rootCmd.Execute(); err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Could not start application")
logger.GetDefaultLogger().Panic().Err(err).Msg("Could not start application")
}
}
88 changes: 88 additions & 0 deletions cmd/cosmos-proposals-checker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package main

import (
"os"
"testing"

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

//nolint:paralleltest // disabled
func TestValidateConfigNoConfigProvided(t *testing.T) {
defer func() {
if r := recover(); r == nil {
require.Fail(t, "Expected to have a panic here!")
}
}()

os.Args = []string{"cmd", "validate-config"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestValidateConfigFailedToLoad(t *testing.T) {
defer func() {
if r := recover(); r == nil {
require.Fail(t, "Expected to have a panic here!")
}
}()

os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-not-found.toml"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestValidateConfigInvalid(t *testing.T) {
defer func() {
if r := recover(); r == nil {
require.Fail(t, "Expected to have a panic here!")
}
}()

os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-invalid.toml"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestValidateConfigWithWarnings(t *testing.T) {
os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-with-warnings.toml"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestValidateConfigValid(t *testing.T) {
os.Args = []string{"cmd", "validate-config", "--config", "../assets/config-valid.toml"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestStartNoConfigProvided(t *testing.T) {
defer func() {
if r := recover(); r == nil {
require.Fail(t, "Expected to have a panic here!")
}
}()

os.Args = []string{"cmd"}
main()
assert.True(t, true)
}

//nolint:paralleltest // disabled
func TestStartConfigProvided(t *testing.T) {
defer func() {
if r := recover(); r == nil {
require.Fail(t, "Expected to have a panic here!")
}
}()

os.Args = []string{"cmd", "--config", "../assets/config-invalid.toml"}
main()
assert.True(t, true)
}
6 changes: 3 additions & 3 deletions pkg/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@
func NewApp(configPath string, filesystem fs.FS, version string) *App {
config, err := GetConfig(filesystem, configPath)
if err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Could not load config")
logger.GetDefaultLogger().Panic().Err(err).Msg("Could not load config")

Check warning on line 37 in pkg/app.go

View check run for this annotation

Codecov / codecov/patch

pkg/app.go#L37

Added line #L37 was not covered by tests
}

if err = config.Validate(); err != nil {
logger.GetDefaultLogger().Fatal().Err(err).Msg("Provided config is invalid!")
logger.GetDefaultLogger().Panic().Err(err).Msg("Provided config is invalid!")

Check warning on line 41 in pkg/app.go

View check run for this annotation

Codecov / codecov/patch

pkg/app.go#L41

Added line #L41 was not covered by tests
}

if warnings := config.DisplayWarnings(); len(warnings) > 0 {
Expand Down Expand Up @@ -106,7 +106,7 @@
if _, err := c.AddFunc(a.Config.Interval, func() {
a.Report()
}); err != nil {
a.Logger.Fatal().Err(err).Msg("Error processing cron pattern")
a.Logger.Panic().Err(err).Msg("Error processing cron pattern")

Check warning on line 109 in pkg/app.go

View check run for this annotation

Codecov / codecov/patch

pkg/app.go#L109

Added line #L109 was not covered by tests
}
c.Start()
a.Logger.Info().Str("interval", a.Config.Interval).Msg("Scheduled proposals reporting")
Expand Down
3 changes: 2 additions & 1 deletion pkg/fetchers/test_fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func (f *TestFetcher) GetChainParams(ctx context.Context) (*types.ChainWithVotin
}

return &types.ChainWithVotingParams{
Chain: &types.Chain{Name: "test"},
Chain: &types.Chain{Name: "test"},
Params: []types.ChainParam{types.BoolParam{Value: true, Description: "param"}},
}, []error{}
}
96 changes: 96 additions & 0 deletions pkg/fetchers/test_fetcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package fetchers

import (
"context"
"testing"

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

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

fetcher1 := TestFetcher{WithProposalsError: true}
proposals1, height1, err1 := fetcher1.GetAllProposals(0, context.Background())
assert.Empty(t, proposals1)
assert.Equal(t, int64(123), height1)
require.Error(t, err1)

fetcher2 := TestFetcher{WithPassedProposals: true}
proposals2, height2, err2 := fetcher2.GetAllProposals(0, context.Background())
assert.NotEmpty(t, proposals2)
assert.Equal(t, int64(123), height2)
require.Nil(t, err2)

fetcher3 := TestFetcher{}
proposals3, height3, err3 := fetcher3.GetAllProposals(0, context.Background())
assert.NotEmpty(t, proposals3)
assert.Equal(t, int64(123), height3)
require.Nil(t, err3)
}

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

fetcher1 := TestFetcher{WithVoteError: true}
vote1, height1, err1 := fetcher1.GetVote("proposal", "vote", 0, context.Background())
assert.Nil(t, vote1)
assert.Equal(t, int64(456), height1)
require.Error(t, err1)

fetcher2 := TestFetcher{WithVote: true}
vote2, height2, err2 := fetcher2.GetVote("proposal", "vote", 0, context.Background())
assert.NotNil(t, vote2)
assert.Equal(t, int64(456), height2)
require.Nil(t, err2)

fetcher3 := TestFetcher{}
vote3, height3, err3 := fetcher3.GetVote("proposal", "vote", 0, context.Background())
assert.Nil(t, vote3)
assert.Equal(t, int64(456), height3)
require.Nil(t, err3)
}

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

fetcher1 := TestFetcher{WithTallyError: true}
tally1, err1 := fetcher1.GetTallies(context.Background())
assert.NotNil(t, tally1)
assert.Empty(t, tally1.TallyInfos)
assert.Nil(t, tally1.Chain)
require.Error(t, err1)

fetcher2 := TestFetcher{WithTallyNotEmpty: true}
tally2, err2 := fetcher2.GetTallies(context.Background())
assert.NotNil(t, tally2)
assert.NotEmpty(t, tally2.TallyInfos)
assert.NotNil(t, tally2.Chain)
require.Nil(t, err2) //nolint:testifylint // not working

fetcher3 := TestFetcher{}
tally3, err3 := fetcher3.GetTallies(context.Background())
assert.NotNil(t, tally3)
assert.Empty(t, tally3.TallyInfos)
assert.Nil(t, tally3.Chain)
require.Nil(t, err3) //nolint:testifylint // not working
}

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

fetcher1 := TestFetcher{WithParamsError: true}
params1, errs1 := fetcher1.GetChainParams(context.Background())
assert.NotNil(t, params1)
assert.Empty(t, params1.Params)
assert.Nil(t, params1.Chain)
require.NotEmpty(t, errs1)

fetcher2 := TestFetcher{}
params2, errs2 := fetcher2.GetChainParams(context.Background())
assert.NotNil(t, params2)
assert.NotEmpty(t, params2.Params)
assert.NotNil(t, params2.Chain)
require.Empty(t, errs2)
}
20 changes: 20 additions & 0 deletions pkg/fs/os_fs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package fs

import (
"os"
)

type OsFS struct {
}

func (fs *OsFS) ReadFile(name string) ([]byte, error) {
return os.ReadFile(name)
}

func (fs *OsFS) WriteFile(name string, data []byte, perms os.FileMode) error {
return os.WriteFile(name, data, perms)
}

func (fs *OsFS) Create(path string) (File, error) {
return os.Create(path)
}
33 changes: 33 additions & 0 deletions pkg/fs/os_fs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package fs

import (
"testing"

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

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

fs := &OsFS{}
file, err := fs.ReadFile("not-found.test")
assert.Empty(t, file)
require.Error(t, err)
}

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

fs := &OsFS{}
err := fs.WriteFile("/etc/fstab", []byte{}, 0)
require.Error(t, err)
}

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

fs := &OsFS{}
_, err := fs.Create("/etc/fstab")
require.Error(t, err)
}
4 changes: 2 additions & 2 deletions pkg/load_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestLoadConfigInvalidToml(t *testing.T) {

filesystem := &fs.TestFS{}

config, err := GetConfig(filesystem, "invalid-config.toml")
config, err := GetConfig(filesystem, "invalid.toml")

assert.Nil(t, config)
require.Error(t, err)
Expand All @@ -35,7 +35,7 @@ func TestLoadConfigValidToml(t *testing.T) {

filesystem := &fs.TestFS{}

config, err := GetConfig(filesystem, "valid-config.toml")
config, err := GetConfig(filesystem, "config-valid.toml")

require.NoError(t, err)
assert.NotNil(t, config)
Expand Down
Loading
Loading