Skip to content

Instantly share code, notes, and snippets.

@kayslay
Created May 27, 2020 06:35
Show Gist options
  • Save kayslay/6110a5f892b256bf9896d9eeaf1b870b to your computer and use it in GitHub Desktop.
Save kayslay/6110a5f892b256bf9896d9eeaf1b870b to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"sync"
"testing"
"time"
)
var (
infoBatcher *infoBatchRequester
)
func Test_infoFetchPoll_ResolveINFO(t *testing.T) {
infoBatcher = &infoBatchRequester{
pending: map[string][]chan<- infoChan{},
infoSaver: mockInfoSaver{},
}
var wg sync.WaitGroup
now := time.Now()
// make 5 request to the get an info_id with the same id
for i := 0; i < 5; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
waitTime := time.Second * time.Duration(4+i)
_, err := run(fmt.Sprintf("same_info"), i, waitTime)
// not expecting error for the index greater than 1
if i > 1 && err != nil {
t.Errorf("not expection error %v on index %d", err, i)
}
}(i)
}
wg.Wait()
log.Println("completed in ", time.Since(now).Seconds())
}
// run calls infoBatcher.Request for an infoID
// it takes the infoID, the index of the call, and the duration for the deadline.
// duration t is the user canceling the request after time t
func run(infoID string, id int, t time.Duration) (infoModel, error) {
ctx, cancel := context.WithDeadline(context.TODO(), time.Now().Add(t))
defer cancel()
result := make(chan infoChan, 1) // using a buffered channel to prevent it from blocking if no
// receiver is available
infoBatcher.Request(infoID, result)
select {
case <-ctx.Done():
log.Println("CLOSED", id, infoID)
return infoModel{}, ctx.Err()
case r := <-result:
log.Println("PASSED", infoID, id, r)
return r.info, r.err
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment