(t *testing.T)
| 103 | } |
| 104 | |
| 105 | func TestReceiveFromChannel(t *testing.T) { |
| 106 | // Since SendToChannel has already been tested, only buffered chan will be considered here |
| 107 | |
| 108 | t.Run("Success", func(t *testing.T) { |
| 109 | ctx := context.Background() |
| 110 | ch := make(chan string, 1) |
| 111 | SendToChannel(ctx, ch, "test-data") |
| 112 | value, ok := ReceiveFromChannel(ctx, ch) |
| 113 | if ok { |
| 114 | t.Log("successfully received data") |
| 115 | } |
| 116 | if value != "test-data" { |
| 117 | t.Errorf("receive failed,expected value to be \"test-data\", but it's %s", value) |
| 118 | } |
| 119 | |
| 120 | }) |
| 121 | |
| 122 | t.Run("Timeout", func(t *testing.T) { |
| 123 | |
| 124 | ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 125 | defer cancel() |
| 126 | ch := make(chan string, 1) |
| 127 | time.Sleep(1 * time.Second) |
| 128 | // No need to send data to SendToChannel as the context has been set to expire |
| 129 | value, ok := ReceiveFromChannel(ctx, ch) |
| 130 | if ok { |
| 131 | t.Fatal("due to timeout setting, it is expected that no value will be received from the channel") |
| 132 | } |
| 133 | if value != "" { |
| 134 | t.Errorf("expected zero value for string, but it's %s", value) |
| 135 | } |
| 136 | |
| 137 | }) |
| 138 | |
| 139 | t.Run("Canceled", func(t *testing.T) { |
| 140 | |
| 141 | ctx, cancel := context.WithCancel(context.Background()) |
| 142 | cancel() // Cancel context |
| 143 | ch := make(chan string, 1) |
| 144 | value, ok := ReceiveFromChannel(ctx, ch) |
| 145 | if ok { |
| 146 | t.Fatal("expected no value to be received from channel due to context cancellation") |
| 147 | } |
| 148 | if value != "" { |
| 149 | t.Errorf("expected zero value for string, but it's %s", value) |
| 150 | } |
| 151 | |
| 152 | }) |
| 153 | } |
nothing calls this directly
no test coverage detected