Skip to content

Commit

Permalink
Enable to test response count
Browse files Browse the repository at this point in the history
  • Loading branch information
nakabonne committed Sep 20, 2020
1 parent cc43887 commit fc4fde8
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 7 deletions.
77 changes: 70 additions & 7 deletions attacker/attacker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,96 @@ package attacker

import (
"context"
"sync"
"testing"
"time"

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

func TestAttack(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

tests := []struct {
name string
target string
opts Options
want *Metrics
name string
target string
opts Options
want *Metrics
wantResCount int
}{
{
name: "no target given",
target: "",
want: nil,
},
{
name: "no result given back",
target: "http://host.xz",
opts: Options{
Attacker: &fakeAttacker{},
},
want: &Metrics{
StatusCodes: make(map[string]int),
Errors: []string{},
},
wantResCount: 0,
},
/*{
name: "two result given back",
target: "http://host.xz",
opts: Options{
Attacker: &fakeAttacker{
results: []*vegeta.Result{
{
Attack: "1",
},
{
Attack: "2",
},
},
},
},
want: &Metrics{
StatusCodes: make(map[string]int),
Errors: []string{},
},
wantResCount: 2,
},*/
}

for _, tt := range tests {
tt.opts.Attacker = &fakeAttacker{}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
w := &watcher{
resCh: make(chan *Result),
}

var wg sync.WaitGroup
wg.Add(1)
go w.countRes(ctx, &wg)
t.Run(tt.name, func(t *testing.T) {
got := Attack(ctx, tt.target, make(chan *Result), tt.opts)
got := Attack(ctx, tt.target, w.resCh, tt.opts)
cancel()
wg.Wait()
assert.Equal(t, tt.want, got)
assert.Equal(t, tt.wantResCount, w.count)
})
}
}

type watcher struct {
resCh chan *Result
count int
}

func (w *watcher) countRes(ctx context.Context, wg *sync.WaitGroup) {
for {
select {
case <-ctx.Done():
wg.Done()
return
case <-w.resCh:
w.count++
}
}
}
1 change: 1 addition & 0 deletions attacker/fake_attacker.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type fakeAttacker struct {

func (f *fakeAttacker) Attack(vegeta.Targeter, vegeta.Pacer, time.Duration, string) <-chan *vegeta.Result {
resultCh := make(chan *vegeta.Result)
defer close(resultCh)
for _, r := range f.results {
resultCh <- r
}
Expand Down

0 comments on commit fc4fde8

Please sign in to comment.