|
17 | 17 | package util_test
|
18 | 18 |
|
19 | 19 | import (
|
| 20 | + "encoding/json" |
| 21 | + "errors" |
20 | 22 | "html/template"
|
| 23 | + "io" |
| 24 | + "net/http" |
| 25 | + "net/http/httptest" |
21 | 26 | "testing"
|
22 | 27 |
|
23 | 28 | "github.com/orca-group/spirit/internal/util"
|
@@ -45,3 +50,58 @@ func TestCountLines(t *testing.T) {
|
45 | 50 |
|
46 | 51 | require.Equal(t, lines, template.HTML("<div>1</div><div>2</div>"))
|
47 | 52 | }
|
| 53 | + |
| 54 | +func TestHandleBodyDetection(t *testing.T) {} |
| 55 | +func TestHandleBodyJSON(t *testing.T) {} |
| 56 | +func TestHandleBodyMultipart(t *testing.T) {} |
| 57 | + |
| 58 | +func TestWriteJSON(t *testing.T) { |
| 59 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 60 | + err := util.WriteJSON[map[string]interface{}](w, 200, map[string]interface{}{ |
| 61 | + "test": "test", |
| 62 | + }) |
| 63 | + |
| 64 | + require.NoError(t, err) |
| 65 | + })) |
| 66 | + defer server.Close() |
| 67 | + |
| 68 | + res, err := http.Get(server.URL) |
| 69 | + require.NoError(t, err) |
| 70 | + |
| 71 | + require.Equal(t, http.StatusOK, res.StatusCode) |
| 72 | + |
| 73 | + x, _ := io.ReadAll(res.Body) |
| 74 | + var body map[string]interface{} |
| 75 | + json.Unmarshal(x, &body) |
| 76 | + |
| 77 | + require.Equal(t, body, map[string]interface{}{ |
| 78 | + "payload": map[string]interface{}{ |
| 79 | + "test": "test", |
| 80 | + }, |
| 81 | + "error": "", |
| 82 | + }) |
| 83 | +} |
| 84 | + |
| 85 | +func TestWriteError(t *testing.T) { |
| 86 | + e := errors.New("some error") |
| 87 | + |
| 88 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 89 | + err := util.WriteError(w, http.StatusInternalServerError, e) |
| 90 | + require.NoError(t, err) |
| 91 | + })) |
| 92 | + defer server.Close() |
| 93 | + |
| 94 | + res, err := http.Get(server.URL) |
| 95 | + require.NoError(t, err) |
| 96 | + |
| 97 | + require.Equal(t, http.StatusInternalServerError, res.StatusCode) |
| 98 | + |
| 99 | + x, _ := io.ReadAll(res.Body) |
| 100 | + var body map[string]interface{} |
| 101 | + json.Unmarshal(x, &body) |
| 102 | + |
| 103 | + require.Equal(t, body, map[string]interface{}{ |
| 104 | + "payload": map[string]interface{}{}, |
| 105 | + "error": e.Error(), |
| 106 | + }) |
| 107 | +} |
0 commit comments