|
| 1 | +package flow |
| 2 | + |
| 3 | +import ( |
| 4 | + "strconv" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/netobserv/gopipes/pkg/node" |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | +) |
| 11 | + |
| 12 | +const limiterLen = 50 |
| 13 | + |
| 14 | +func TestCapacityLimiter_NoDrop(t *testing.T) { |
| 15 | + // GIVEN a limiter-enabled pipeline |
| 16 | + pipeIn, pipeOut := capacityLimiterPipe() |
| 17 | + |
| 18 | + // WHEN it buffers less elements than it's maximum capacity |
| 19 | + for i := 0; i < 33; i++ { |
| 20 | + pipeIn <- []*Record{{Interface: strconv.Itoa(i)}} |
| 21 | + } |
| 22 | + |
| 23 | + // THEN it is able to retrieve all the buffered elements |
| 24 | + for i := 0; i < 33; i++ { |
| 25 | + elem := <-pipeOut |
| 26 | + require.Len(t, elem, 1) |
| 27 | + assert.Equal(t, strconv.Itoa(i), elem[0].Interface) |
| 28 | + } |
| 29 | + |
| 30 | + // AND not a single extra element |
| 31 | + select { |
| 32 | + case elem := <-pipeOut: |
| 33 | + assert.Failf(t, "unexpected element", "%#v", elem) |
| 34 | + default: |
| 35 | + // ok! |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func TestCapacityLimiter_Drop(t *testing.T) { |
| 40 | + // GIVEN a limiter-enabled pipeline |
| 41 | + pipeIn, pipeOut := capacityLimiterPipe() |
| 42 | + |
| 43 | + // WHEN it receives more elements than its maximum capacity |
| 44 | + // (it's not blocking) |
| 45 | + for i := 0; i < limiterLen*2; i++ { |
| 46 | + pipeIn <- []*Record{{Interface: strconv.Itoa(i)}} |
| 47 | + } |
| 48 | + |
| 49 | + // THEN it is only able to retrieve all the nth first buffered elements |
| 50 | + // (plus the single element that is buffered in the output channel) |
| 51 | + for i := 0; i < limiterLen+1; i++ { |
| 52 | + elem := <-pipeOut |
| 53 | + require.Len(t, elem, 1) |
| 54 | + assert.Equal(t, strconv.Itoa(i), elem[0].Interface) |
| 55 | + } |
| 56 | + |
| 57 | + // BUT not a single extra element |
| 58 | + select { |
| 59 | + case elem := <-pipeOut: |
| 60 | + assert.Failf(t, "unexpected element", "%#v", elem) |
| 61 | + default: |
| 62 | + // ok! |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func capacityLimiterPipe() (in chan<- []*Record, out <-chan []*Record) { |
| 67 | + inCh, outCh := make(chan []*Record), make(chan []*Record) |
| 68 | + |
| 69 | + init := node.AsInit(func(initOut chan<- []*Record) { |
| 70 | + for i := range inCh { |
| 71 | + initOut <- i |
| 72 | + } |
| 73 | + }) |
| 74 | + limiter := node.AsMiddle((&CapacityLimiter{}).Limit) |
| 75 | + term := node.AsTerminal(func(termIn <-chan []*Record) { |
| 76 | + for i := range termIn { |
| 77 | + outCh <- i |
| 78 | + } |
| 79 | + }, node.ChannelBufferLen(limiterLen)) |
| 80 | + |
| 81 | + init.SendsTo(limiter) |
| 82 | + limiter.SendsTo(term) |
| 83 | + |
| 84 | + init.Start() |
| 85 | + |
| 86 | + return inCh, outCh |
| 87 | +} |
0 commit comments