(t *testing.T)
| 24 | ) |
| 25 | |
| 26 | func TestSendToChannel(t *testing.T) { |
| 27 | |
| 28 | t.Run("send_buffered_chan_success", func(t *testing.T) { |
| 29 | |
| 30 | c := make(chan string, 1) |
| 31 | ctx := context.Background() |
| 32 | if !SendToChannel(ctx, c, "data") { |
| 33 | t.Fatal("SendToChannel should return true when sending succeeds") |
| 34 | } |
| 35 | value := <-c |
| 36 | if value != "data" { |
| 37 | t.Errorf("expected to receive \"data\" from channel, but received %s", value) |
| 38 | } |
| 39 | |
| 40 | }) |
| 41 | |
| 42 | t.Run("send_unbuffered_chan_success", func(t *testing.T) { |
| 43 | c := make(chan string) |
| 44 | ctx := context.Background() |
| 45 | |
| 46 | go func() { |
| 47 | SendToChannel(ctx, c, "data") |
| 48 | }() |
| 49 | |
| 50 | value := <-c |
| 51 | if value != "data" { |
| 52 | t.Errorf("expected to receive \"data\" from channel, but received %s", value) |
| 53 | } |
| 54 | |
| 55 | }) |
| 56 | |
| 57 | t.Run("context_timeout", func(t *testing.T) { |
| 58 | // Using time.Sleep to simulating context timeout |
| 59 | |
| 60 | c := make(chan string) |
| 61 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) |
| 62 | defer cancel() |
| 63 | time.Sleep(1 * time.Second) // Set timeout |
| 64 | if k := SendToChannel(ctx, c, "hello"); k { |
| 65 | t.Fatal("context timeout but data sent successfully") |
| 66 | } else { |
| 67 | t.Log("failed to send data due to context timeout") |
| 68 | } |
| 69 | |
| 70 | }) |
| 71 | |
| 72 | t.Run("incorrect_type", func(t *testing.T) { |
| 73 | |
| 74 | defer func() { |
| 75 | if r := recover(); r != nil { |
| 76 | t.Log("test-ok") |
| 77 | } else { |
| 78 | t.Log("test-fail") |
| 79 | } |
| 80 | }() |
| 81 | c := make(chan int) |
| 82 | ctx := context.Background() |
| 83 | SendToChannel(ctx, c, "incorrect type") |
nothing calls this directly
no test coverage detected