gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

new_test.go (1984B)


      1 package gtserror_test
      2 
      3 import (
      4 	"bytes"
      5 	"fmt"
      6 	"io"
      7 	"net/http"
      8 	"net/url"
      9 	"strings"
     10 	"testing"
     11 
     12 	"github.com/superseriousbusiness/gotosocial/internal/gtserror"
     13 	"github.com/superseriousbusiness/gotosocial/internal/log"
     14 )
     15 
     16 func TestResponseError(t *testing.T) {
     17 	testResponseError(t, http.Response{
     18 		Body: toBody(`{"error": "user not found"}`),
     19 		Request: &http.Request{
     20 			Method: "GET",
     21 			URL:    toURL("https://google.com/users/sundar"),
     22 		},
     23 		Status: "404 Not Found",
     24 	})
     25 	testResponseError(t, http.Response{
     26 		Body: toBody("Unauthorized"),
     27 		Request: &http.Request{
     28 			Method: "POST",
     29 			URL:    toURL("https://google.com/inbox"),
     30 		},
     31 		Status: "401 Unauthorized",
     32 	})
     33 	testResponseError(t, http.Response{
     34 		Body: toBody(""),
     35 		Request: &http.Request{
     36 			Method: "GET",
     37 			URL:    toURL("https://google.com/users/sundar"),
     38 		},
     39 		Status: "404 Not Found",
     40 	})
     41 }
     42 
     43 func testResponseError(t *testing.T, rsp http.Response) {
     44 	var body string
     45 	if rsp.Body == http.NoBody {
     46 		body = "<empty>"
     47 	} else {
     48 		var b []byte
     49 		rsp.Body, b = copyBody(rsp.Body)
     50 		trunc := len(b)
     51 		if trunc > 256 {
     52 			trunc = 256
     53 		}
     54 		body = string(b[:trunc])
     55 	}
     56 	expect := fmt.Sprintf(
     57 		"%s%s request to %s failed: status=\"%s\" body=\"%s\"",
     58 		func() string {
     59 			if gtserror.Caller {
     60 				return strings.Split(log.Caller(3), ".")[1] + ": "
     61 			}
     62 			return ""
     63 		}(),
     64 		rsp.Request.Method,
     65 		rsp.Request.URL.String(),
     66 		rsp.Status,
     67 		body,
     68 	)
     69 	err := gtserror.NewFromResponse(&rsp)
     70 	if str := err.Error(); str != expect {
     71 		t.Errorf("unexpected error string: recv=%q expct=%q", str, expect)
     72 	}
     73 }
     74 
     75 func toURL(u string) *url.URL {
     76 	url, err := url.Parse(u)
     77 	if err != nil {
     78 		panic(err)
     79 	}
     80 	return url
     81 }
     82 
     83 func toBody(s string) io.ReadCloser {
     84 	if s == "" {
     85 		return http.NoBody
     86 	}
     87 	r := strings.NewReader(s)
     88 	return io.NopCloser(r)
     89 }
     90 
     91 func copyBody(rc io.ReadCloser) (io.ReadCloser, []byte) {
     92 	b, err := io.ReadAll(rc)
     93 	if err != nil {
     94 		panic(err)
     95 	}
     96 	r := bytes.NewReader(b)
     97 	return io.NopCloser(r), b
     98 }