| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package dyncfg |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/stretchr/testify/assert" |
| 11 | ) |
| 12 | |
| 13 | func TestBoundedSend(t *testing.T) { |
| 14 | tests := map[string]struct { |
| 15 | run func(t *testing.T) BoundedSendResult |
| 16 | want BoundedSendResult |
| 17 | }{ |
| 18 | "buffered channel send succeeds": { |
| 19 | run: func(t *testing.T) BoundedSendResult { |
| 20 | t.Helper() |
| 21 | ch := make(chan int, 1) |
| 22 | got := BoundedSend(context.Background(), ch, 42, 50*time.Millisecond) |
| 23 | assert.Equal(t, 42, <-ch) |
| 24 | return got |
| 25 | }, |
| 26 | want: BoundedSendOK, |
| 27 | }, |
| 28 | "unbuffered channel send succeeds with receiver": { |
| 29 | run: func(t *testing.T) BoundedSendResult { |
| 30 | t.Helper() |
| 31 | ch := make(chan int) |
| 32 | received := make(chan int, 1) |
| 33 | go func() { received <- <-ch }() |
| 34 | got := BoundedSend(context.Background(), ch, 77, 50*time.Millisecond) |
| 35 | assert.Equal(t, 77, <-received) |
| 36 | return got |
| 37 | }, |
| 38 | want: BoundedSendOK, |
| 39 | }, |
| 40 | "context canceled before send returns context-done": { |
| 41 | run: func(t *testing.T) BoundedSendResult { |
| 42 | t.Helper() |
| 43 | ctx, cancel := context.WithCancel(context.Background()) |
| 44 | cancel() |
| 45 | ch := make(chan int) |
| 46 | return BoundedSend(ctx, ch, 1, 50*time.Millisecond) |
| 47 | }, |
| 48 | want: BoundedSendContextDone, |
| 49 | }, |
| 50 | "nil context uses background and times out": { |
| 51 | run: func(t *testing.T) BoundedSendResult { |
| 52 | t.Helper() |
| 53 | ch := make(chan int) |
| 54 | return BoundedSend[int](nil, ch, 1, 20*time.Millisecond) |
| 55 | }, |
| 56 | want: BoundedSendTimeout, |
| 57 | }, |
| 58 | "unbuffered channel without receiver times out": { |
| 59 | run: func(t *testing.T) BoundedSendResult { |
| 60 | t.Helper() |
| 61 | ch := make(chan int) |
| 62 | return BoundedSend(context.Background(), ch, 1, 20*time.Millisecond) |
| 63 | }, |
| 64 | want: BoundedSendTimeout, |
| 65 | }, |
| 66 | "expired context deadline returns context-done": { |
| 67 | run: func(t *testing.T) BoundedSendResult { |
| 68 | t.Helper() |
| 69 | ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) |
| 70 | defer cancel() |
| 71 | ch := make(chan int) |
| 72 | return BoundedSend(ctx, ch, 1, 50*time.Millisecond) |
| 73 | }, |
| 74 | want: BoundedSendContextDone, |
| 75 | }, |
| 76 | } |
| 77 | |
| 78 | for name, tc := range tests { |
| 79 | t.Run(name, func(t *testing.T) { |
| 80 | assert.Equal(t, tc.want, tc.run(t)) |
| 81 | }) |
| 82 | } |
| 83 | } |