summaryrefslogtreecommitdiff
path: root/internal/gtserror/new_test.go
blob: 8b4dae1bae71ef2f414d2c07171675cb0681d78c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package gtserror_test

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"testing"

	"github.com/superseriousbusiness/gotosocial/internal/gtserror"
	"github.com/superseriousbusiness/gotosocial/internal/log"
)

func TestResponseError(t *testing.T) {
	testResponseError(t, http.Response{
		Body: toBody(`{"error": "user not found"}`),
		Request: &http.Request{
			Method: "GET",
			URL:    toURL("https://google.com/users/sundar"),
		},
		Status: "404 Not Found",
	})
	testResponseError(t, http.Response{
		Body: toBody("Unauthorized"),
		Request: &http.Request{
			Method: "POST",
			URL:    toURL("https://google.com/inbox"),
		},
		Status: "401 Unauthorized",
	})
	testResponseError(t, http.Response{
		Body: toBody(""),
		Request: &http.Request{
			Method: "GET",
			URL:    toURL("https://google.com/users/sundar"),
		},
		Status: "404 Not Found",
	})
}

func testResponseError(t *testing.T, rsp http.Response) {
	var body string
	if rsp.Body == http.NoBody {
		body = "<empty>"
	} else {
		var b []byte
		rsp.Body, b = copyBody(rsp.Body)
		trunc := len(b)
		if trunc > 256 {
			trunc = 256
		}
		body = string(b[:trunc])
	}
	expect := fmt.Sprintf(
		"%s%s request to %s failed: status=\"%s\" body=\"%s\"",
		func() string {
			if gtserror.Caller {
				return strings.Split(log.Caller(3), ".")[1] + ": "
			}
			return ""
		}(),
		rsp.Request.Method,
		rsp.Request.URL.String(),
		rsp.Status,
		body,
	)
	err := gtserror.NewFromResponse(&rsp)
	if str := err.Error(); str != expect {
		t.Errorf("unexpected error string: recv=%q expct=%q", str, expect)
	}
}

func toURL(u string) *url.URL {
	url, err := url.Parse(u)
	if err != nil {
		panic(err)
	}
	return url
}

func toBody(s string) io.ReadCloser {
	if s == "" {
		return http.NoBody
	}
	r := strings.NewReader(s)
	return io.NopCloser(r)
}

func copyBody(rc io.ReadCloser) (io.ReadCloser, []byte) {
	b, err := io.ReadAll(rc)
	if err != nil {
		panic(err)
	}
	r := bytes.NewReader(b)
	return io.NopCloser(r), b
}