| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package functions |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/stretchr/testify/assert" |
| 10 | "github.com/stretchr/testify/require" |
| 11 | ) |
| 12 | |
| 13 | func TestBuildJSONPayload(t *testing.T) { |
| 14 | tests := map[string]struct { |
| 15 | code int |
| 16 | message string |
| 17 | expectMsgKey string |
| 18 | expectErrorKey string |
| 19 | }{ |
| 20 | "success payload uses message key": { |
| 21 | code: 200, |
| 22 | message: "ok", |
| 23 | expectMsgKey: "ok", |
| 24 | }, |
| 25 | "error payload uses errorMessage key": { |
| 26 | code: 499, |
| 27 | message: "request canceled", |
| 28 | expectErrorKey: "request canceled", |
| 29 | }, |
| 30 | } |
| 31 | |
| 32 | for name, tc := range tests { |
| 33 | t.Run(name, func(t *testing.T) { |
| 34 | payload := BuildJSONPayload(tc.code, tc.message) |
| 35 | require.NotEmpty(t, payload) |
| 36 | |
| 37 | var decoded map[string]any |
| 38 | require.NoError(t, json.Unmarshal(payload, &decoded)) |
| 39 | |
| 40 | status, ok := decoded["status"].(float64) |
| 41 | require.True(t, ok) |
| 42 | assert.Equal(t, float64(tc.code), status) |
| 43 | |
| 44 | if tc.expectMsgKey != "" { |
| 45 | assert.Equal(t, tc.expectMsgKey, decoded["message"]) |
| 46 | _, hasErrorMessage := decoded["errorMessage"] |
| 47 | assert.False(t, hasErrorMessage) |
| 48 | } |
| 49 | if tc.expectErrorKey != "" { |
| 50 | assert.Equal(t, tc.expectErrorKey, decoded["errorMessage"]) |
| 51 | _, hasMessage := decoded["message"] |
| 52 | assert.False(t, hasMessage) |
| 53 | } |
| 54 | }) |
| 55 | } |
| 56 | } |