aboutsummaryrefslogtreecommitdiff
path: root/response_test.go
blob: ab2484f5ad11c5ae2f08f1221266bcdfffc824ca (plain) (blame)
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
99
100
101
102
103
package gemini

import (
	"io"
	"strings"
	"testing"
)

func TestReadResponse(t *testing.T) {
	tests := []struct {
		Raw    string
		Status int
		Meta   string
		Body   string
		Err    error
	}{
		{
			Raw:    "20 text/gemini\r\nHello, world!\nWelcome to my capsule.",
			Status: 20,
			Meta:   "text/gemini",
			Body:   "Hello, world!\nWelcome to my capsule.",
		},
		{
			Raw:    "10 Search query\r\n",
			Status: 10,
			Meta:   "Search query",
		},
		{
			Raw:    "30 /redirect\r\n",
			Status: 30,
			Meta:   "/redirect",
		},
		{
			Raw:    "31 /redirect\r\nThis body is ignored.",
			Status: 31,
			Meta:   "/redirect",
		},
		{
			Raw:    "99 Unknown status code\r\n",
			Status: 99,
			Meta:   "Unknown status code",
		},
		{
			Raw: "\r\n",
			Err: ErrInvalidResponse,
		},
		{
			Raw: "\n",
			Err: ErrInvalidResponse,
		},
		{
			Raw: "1 Bad response\r\n",
			Err: ErrInvalidResponse,
		},
		{
			Raw: "",
			Err: io.EOF,
		},
		{
			Raw: "10 Search query",
			Err: io.EOF,
		},
		{
			Raw: "20 text/gemini\nHello, world!",
			Err: io.EOF,
		},
		{
			Raw: "20 text/gemini\rHello, world!",
			Err: ErrInvalidResponse,
		},
		{
			Raw: "20 text/gemini\r",
			Err: io.EOF,
		},
		{
			Raw: "abcdefghijklmnopqrstuvwxyz",
			Err: ErrInvalidResponse,
		},
	}

	for _, test := range tests {
		t.Logf("%#v", test.Raw)
		resp, err := ReadResponse(io.NopCloser(strings.NewReader(test.Raw)))
		if err != test.Err {
			t.Errorf("expected err = %v, got %v", test.Err, err)
		}
		if test.Err != nil {
			// No response
			continue
		}
		if resp.Status != test.Status {
			t.Errorf("expected status = %d, got %d", test.Status, resp.Status)
		}
		if resp.Meta != test.Meta {
			t.Errorf("expected meta = %s, got %s", test.Meta, resp.Meta)
		}
		b, _ := io.ReadAll(resp.Body)
		body := string(b)
		if body != test.Body {
			t.Errorf("expected body = %#v, got %#v", test.Body, body)
		}
	}
}