summaryrefslogtreecommitdiffstats
path: root/plugin/rpcplugin/http_test.go
blob: afaaf7756e01a821808169af000c5b919e1c7a60 (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
package rpcplugin

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func testHTTPResponseWriterRPC(w http.ResponseWriter, f func(w http.ResponseWriter)) {
	r1, w1 := io.Pipe()
	r2, w2 := io.Pipe()

	c1 := NewMuxer(NewReadWriteCloser(r1, w2), false)
	defer c1.Close()

	c2 := NewMuxer(NewReadWriteCloser(r2, w1), true)
	defer c2.Close()

	id, server := c1.Serve()
	go ServeHTTPResponseWriter(w, server)

	remote := ConnectHTTPResponseWriter(c2.Connect(id))
	defer remote.Close()

	f(remote)
}

func TestHTTP(t *testing.T) {
	w := httptest.NewRecorder()

	testHTTPResponseWriterRPC(w, func(w http.ResponseWriter) {
		headers := w.Header()
		headers.Set("Test-Header-A", "a")
		headers.Set("Test-Header-B", "b")
		w.Header().Set("Test-Header-C", "c")
		w.WriteHeader(http.StatusPaymentRequired)
		n, err := w.Write([]byte("this is "))
		assert.Equal(t, 8, n)
		assert.NoError(t, err)
		n, err = w.Write([]byte("a test"))
		assert.Equal(t, 6, n)
		assert.NoError(t, err)
	})

	r := w.Result()
	defer r.Body.Close()

	assert.Equal(t, http.StatusPaymentRequired, r.StatusCode)

	body, err := ioutil.ReadAll(r.Body)
	assert.NoError(t, err)
	assert.EqualValues(t, "this is a test", body)

	assert.Equal(t, "a", r.Header.Get("Test-Header-A"))
	assert.Equal(t, "b", r.Header.Get("Test-Header-B"))
	assert.Equal(t, "c", r.Header.Get("Test-Header-C"))
}