jx/internal/transport/http_readwriter_test.go
Matthew Rich eaaf0f8931
All checks were successful
Lint / golangci-lint (push) Successful in 10m38s
Declarative Tests / test (push) Successful in 38s
collect resource/doc errors and add to result. Add readwritecloser support for HTTP transport reading response data
2024-10-02 20:26:02 +00:00

92 lines
2.1 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package transport
import (
"github.com/stretchr/testify/assert"
"testing"
"fmt"
_ "os"
"io"
"net/url"
_ "path/filepath"
"context"
"net/http"
"net/http/httptest"
"log/slog"
_ "strings"
"decl/internal/ext"
)
/*
func TestNewTransportHTTPReader(t *testing.T) {
//ctx := context.Background()
body := []byte(`
type: "user"
attributes:
name: "foo"
gecos: "foo user"
`)
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
assert.Equal(t, req.URL.String(), "/resource/user")
n,e := rw.Write(body)
assert.Nil(t, e)
assert.Greater(t, n, 0)
assert.Equal(t, "bar", req.Header.Get("foo"))
}))
defer server.Close()
u, urlErr := url.Parse(fmt.Sprintf("%s/resource/user", server.URL))
assert.Nil(t, urlErr)
h, err := NewHTTPReader(u, context.Background())
assert.Nil(t, err)
assert.NotNil(t, h)
h.Reader()
h.GetRequest().Header.Add("foo", "bar")
resData, readErr := io.ReadAll(h.Reader())
assert.Nil(t, readErr)
assert.Greater(t, len(resData), 0)
assert.Equal(t, body, resData)
}
*/
func TestNewTransportHTTPReadWriter(t *testing.T) {
body := []byte(`
type: "user"
attributes:
name: "foo"
gecos: "foo user"
`)
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
assert.Equal(t, req.URL.String(), "/resource/user")
postBody, readErr := io.ReadAll(req.Body)
assert.Nil(t, readErr)
assert.Greater(t, len(postBody), 0)
assert.Equal(t, "bar", req.Header.Get("foo"))
assert.Equal(t, body, postBody)
}))
defer server.Close()
u, urlErr := url.Parse(fmt.Sprintf("%s/resource/user", server.URL))
assert.Nil(t, urlErr)
h, err := NewHTTPReadWriter(u, context.Background())
assert.Nil(t, err)
assert.NotNil(t, h)
rw := h.ReadWriter()
h.PostRequest().Header.Add("foo", "bar")
slog.Info("TestNewTransportHTTPReadWriter()", "http", h, "rw", rw)
_, ok := rw.(io.ReaderFrom)
assert.True(t, ok)
bodyReader := ext.NewStringReader(string(body))
copyBuffer := make([]byte, 32 * 1024)
_, writeErr := io.CopyBuffer(rw, io.NopCloser(bodyReader), copyBuffer)
assert.Nil(t, writeErr)
}