Skip to content

Commit

Permalink
Add more tests and fix old tests
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasBT committed Nov 19, 2023
1 parent c96bbdd commit 6ecc68c
Show file tree
Hide file tree
Showing 8 changed files with 812 additions and 66 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDN
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE=
github.com/shirou/gopsutil/v3 v3.23.8/go.mod h1:7hmCaBn+2ZwaZOr6jmPBZDfawwMGuo1id3C6aM8EDqQ=
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
Expand Down
3 changes: 2 additions & 1 deletion internal/infra/config/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const (
DefRetryAttempts = 3
DefRetryIntervalInitial = 1 * time.Second
DefRetryIntervalBackoff = 2 * time.Second
DefRateLimit = 1
)

type Config struct {
Expand All @@ -41,7 +42,7 @@ func InitConfig() (*Config, error) {
)
pollInterval := flag.Uint("p", DefPollInterval, "How often to query metrics, seconds")
hmacKey := flag.String("k", "", "HMAC key for integrity checks")
rateLimit := flag.Uint("l", 1, "Max number of active workers")
rateLimit := flag.Uint("l", DefRateLimit, "Max number of active workers")
flag.Parse()
if conf.Addr == "" {
conf.Addr = *addr
Expand Down
4 changes: 4 additions & 0 deletions internal/infra/config/agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func TestInitConfig(t *testing.T) {
RetryAttempts: DefRetryAttempts,
RetryIntervalBackoff: DefRetryIntervalBackoff,
RetryIntervalInitial: DefRetryIntervalInitial,
RateLimit: DefRateLimit,
},
},
{
Expand All @@ -41,6 +42,7 @@ func TestInitConfig(t *testing.T) {
RetryAttempts: DefRetryAttempts,
RetryIntervalBackoff: DefRetryIntervalBackoff,
RetryIntervalInitial: DefRetryIntervalInitial,
RateLimit: DefRateLimit,
},
},
{
Expand All @@ -55,6 +57,7 @@ func TestInitConfig(t *testing.T) {
RetryAttempts: DefRetryAttempts,
RetryIntervalBackoff: DefRetryIntervalBackoff,
RetryIntervalInitial: DefRetryIntervalInitial,
RateLimit: DefRateLimit,
},
},
{
Expand All @@ -69,6 +72,7 @@ func TestInitConfig(t *testing.T) {
RetryAttempts: DefRetryAttempts,
RetryIntervalBackoff: DefRetryIntervalBackoff,
RetryIntervalInitial: DefRetryIntervalInitial,
RateLimit: DefRateLimit,
},
},
}
Expand Down
112 changes: 112 additions & 0 deletions internal/infra/utils/retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package utils

import (
"context"
"errors"
"reflect"
"testing"
"time"

"github.com/matthiasBT/monitoring/internal/infra/logging"
)

var ErrSome = errors.New("some error")

type UnreliableCallCounter struct {
called int
stopFailuresAt int
}

func (cc *UnreliableCallCounter) do() (any, error) {
cc.called += 1
if cc.called == cc.stopFailuresAt {
time.Sleep(100 * time.Millisecond)
return 100500, nil
}
return nil, ErrSome
}

func TestRetrier_RetryChecked(t *testing.T) {
type args struct {
timeout time.Duration
f func() (any, error)
checkError func(error) bool
}
tests := []struct {
name string
args args
want any
wantErr error
}{
{
name: "success_first_try",
args: args{
f: func() (any, error) { return 100500, nil },
checkError: nil,
},
want: 100500,
wantErr: nil,
},
{
name: "success_second_try",
args: args{
f: (&UnreliableCallCounter{stopFailuresAt: 2}).do,
checkError: func(err error) bool { return errors.Is(err, ErrSome) },
},
want: 100500,
wantErr: nil,
},
{
name: "failure_on_unchecked_error",
args: args{
f: (&UnreliableCallCounter{stopFailuresAt: 2}).do,
checkError: func(err error) bool { return !errors.Is(err, ErrSome) },
},
want: nil,
wantErr: ErrSome,
},
{
name: "number_of_attempts_exceeded",
args: args{
f: (&UnreliableCallCounter{stopFailuresAt: 5}).do,
checkError: func(err error) bool { return errors.Is(err, ErrSome) },
},
want: nil,
wantErr: ErrSome,
},
{
name: "timeout",
args: args{
f: (&UnreliableCallCounter{stopFailuresAt: 5}).do,
checkError: func(err error) bool { return errors.Is(err, ErrSome) },
timeout: 1 * time.Millisecond,
},
want: nil,
wantErr: ErrRetryAborted,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := &Retrier{
Attempts: 2,
IntervalFirst: 100 * time.Millisecond,
IntervalIncrease: 100 * time.Millisecond,
Logger: logging.SetupLogger(),
}
ctx := context.Background()
if tt.args.timeout != 0 {
ctxt, cancel := context.WithTimeout(ctx, tt.args.timeout)
ctx = ctxt
defer cancel()
}
got, err := r.RetryChecked(ctx, tt.args.f, tt.args.checkError)
if err != nil && !errors.Is(err, tt.wantErr) {
t.Errorf("RetryChecked() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("RetryChecked() got = %v, want %v", got, tt.want)
}
})
}
}
61 changes: 61 additions & 0 deletions internal/server/adapters/filekeeper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package adapters

import (
"context"
"os"
"sync"
"testing"

common "github.com/matthiasBT/monitoring/internal/infra/entities"
"github.com/matthiasBT/monitoring/internal/infra/logging"
)

func TestFileKeeper_Flush(t *testing.T) {
tests := []struct {
name string
storageSnapshot []*common.Metrics
wantErr bool
}{
{
name: "flush_snapshot",
storageSnapshot: []*common.Metrics{
{
ID: "BarFoo1",
MType: common.TypeGauge,
Delta: nil,
Value: ptrfloat64(44.1),
},
{
ID: "BarFoo2",
MType: common.TypeGauge,
Delta: nil,
Value: ptrfloat64(55.5),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file, err := os.CreateTemp("", "example")
if err != nil {
t.Fatal("Failed to create a temporary file")
}
defer os.Remove(file.Name())
defer file.Close()
fs := &FileKeeper{
Logger: logging.SetupLogger(),
Path: file.Name(),
Lock: &sync.Mutex{},
}
if err := fs.Flush(context.Background(), tt.storageSnapshot); err != nil {
t.Errorf("Flush() error = %v", err)
}
restoredState := fs.Restore()
if len(restoredState) != len(tt.storageSnapshot) ||
!compare(restoredState[0], tt.storageSnapshot[0]) ||
!compare(restoredState[1], tt.storageSnapshot[1]) {
t.Errorf("State after Restore() is not equal")
}
})
}
}
Loading

0 comments on commit 6ecc68c

Please sign in to comment.