100 lines
2.6 KiB
Go
100 lines
2.6 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"
|
|
"decl/internal/identifier"
|
|
)
|
|
|
|
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 TestNewTransportHTTPWriter(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")
|
|
n, postBody := io.ReadAll(req.Body)
|
|
|
|
assert.Greater(t, n, 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 := NewHTTPWriter(u, context.Background())
|
|
assert.Nil(t, err)
|
|
assert.NotNil(t, h)
|
|
h.Writer()
|
|
h.PostRequest().Header.Add("foo", "bar")
|
|
|
|
// _, writeErr := h.Writer().Write(body)
|
|
// assert.Nil(t, writeErr)
|
|
}
|
|
|
|
|
|
func TestHTTPExt(t *testing.T) {
|
|
for _, v := range []struct { File identifier.ID
|
|
ExpectedExt string
|
|
ExpectedType string }{
|
|
{ File: "file:///tmp/foo/bar/baz.txt", ExpectedExt: "", ExpectedType: "txt" },
|
|
{ File: "file:///tmp/foo/bar/baz.txt.gz", ExpectedExt: "gz", ExpectedType: "txt" },
|
|
{ File: "file:///tmp/foo/bar/baz.quuz.txt.gz", ExpectedExt: "gz", ExpectedType: "txt" },
|
|
} {
|
|
u := v.File.Parse()
|
|
assert.Equal(t, "file", u.Scheme)
|
|
filetype, fileext := v.File.Extension()
|
|
assert.Equal(t, v.ExpectedType, filetype)
|
|
assert.Equal(t, v.ExpectedExt, fileext)
|
|
h, err := NewHTTP(u, context.Background())
|
|
assert.Nil(t, err)
|
|
assert.Equal(t, v.ExpectedType, h.exttype)
|
|
assert.Equal(t, v.ExpectedExt, h.fileext)
|
|
}
|
|
}
|