| 1 |
package homeassistant_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"net/http" |
| 6 |
"testing" |
| 7 |
"testing/synctest" |
| 8 |
|
| 9 |
"github.com/stretchr/testify/mock" |
| 10 |
"github.com/stretchr/testify/require" |
| 11 |
) |
| 12 |
|
| 13 |
func TestSendWithHTTPError(t *testing.T) { |
| 14 |
t.Parallel() |
| 15 |
synctest.Test(t, func(t *testing.T) { |
| 16 |
tests := []struct { |
| 17 |
name string |
| 18 |
statusCode int |
| 19 |
response string |
| 20 |
}{ |
| 21 |
{"bad request", http.StatusBadRequest, "invalid"}, |
| 22 |
{"unauthorized", http.StatusUnauthorized, "denied"}, |
| 23 |
{"not found", http.StatusNotFound, "missing"}, |
| 24 |
{"internal server error", http.StatusInternalServerError, "boom"}, |
| 25 |
} |
| 26 |
|
| 27 |
for _, tt := range tests { |
| 28 |
mockClient := &MockHTTPClient{} |
| 29 |
service := createTestService(t, validHomeAssistantURL, mockClient) |
| 30 |
|
| 31 |
mockClient.On("Do", mock.Anything). |
| 32 |
Return(createMockResponse(tt.statusCode, tt.response), nil). |
| 33 |
Once() |
| 34 |
|
| 35 |
err := service.Send("Test message", nil) |
| 36 |
require.Error(t, err, "Expected error for %s", tt.name) |
| 37 |
|
| 38 |
mockClient.AssertExpectations(t) |
| 39 |
} |
| 40 |
}) |
| 41 |
} |
| 42 |
|
| 43 |
func TestSendWithNetworkError(t *testing.T) { |
| 44 |
t.Parallel() |
| 45 |
synctest.Test(t, func(t *testing.T) { |
| 46 |
mockClient := &MockHTTPClient{} |
| 47 |
service := createTestService(t, validHomeAssistantURL, mockClient) |
| 48 |
|
| 49 |
mockClient.On("Do", mock.Anything). |
| 50 |
Return(nil, errors.New("connection refused")). |
| 51 |
Once() |
| 52 |
|
| 53 |
err := service.Send("Test message", nil) |
| 54 |
require.Error(t, err) |
| 55 |
|
| 56 |
mockClient.AssertExpectations(t) |
| 57 |
}) |
| 58 |
} |