jx/internal/resource/http_test.go

107 lines
2.1 KiB
Go
Raw Normal View History

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
2024-04-10 19:38:12 +00:00
"context"
_ "encoding/json"
2024-04-10 19:38:12 +00:00
"fmt"
"github.com/stretchr/testify/assert"
_ "gopkg.in/yaml.v3"
2024-04-10 19:38:12 +00:00
"io"
"log/slog"
2024-04-10 19:38:12 +00:00
"net/http"
"net/http/httptest"
_ "net/url"
_ "os"
_ "path/filepath"
_ "strings"
"testing"
2024-04-10 19:38:12 +00:00
"regexp"
)
func TestNewHTTPResource(t *testing.T) {
2024-04-10 19:38:12 +00:00
h := NewHTTP()
assert.NotNil(t, h)
}
func TestHTTPDecode(t *testing.T) {
h := NewHTTP()
assert.NotNil(t, h)
decl:=`
endpoint: "https://example.foo"
body: |-
test body
`
assert.Nil(t, h.LoadDecl(decl))
assert.Equal(t, "test body", h.Content)
2024-04-10 19:38:12 +00:00
}
func TestHTTPRead(t *testing.T) {
h := NewHTTP()
assert.NotNil(t, h)
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
assert.Equal(t, req.URL.String(), "/resource/user/foo")
2024-04-10 20:27:34 +00:00
n,e := rw.Write([]byte(`
2024-04-10 19:38:12 +00:00
type: "user"
attributes:
name: "foo"
gecos: "foo user"
`))
2024-04-10 20:27:34 +00:00
assert.Nil(t, e)
assert.Greater(t, n, 0)
2024-04-10 19:38:12 +00:00
}))
defer server.Close()
decl := fmt.Sprintf(`
endpoint: "%s/resource/user/foo"
`, server.URL)
assert.Nil(t, h.LoadDecl(decl))
_,e := h.Read(context.Background())
assert.Nil(t, e)
assert.Greater(t, len(h.Content), 0)
2024-04-10 19:38:12 +00:00
assert.Nil(t, h.Validate())
}
func TestHTTPCreate(t *testing.T) {
2024-05-09 07:39:45 +00:00
ctx := context.Background()
2024-04-10 19:38:12 +00:00
userdecl := `
type: "user"
attributes:
name: "foo"
gecos: "foo user"
`
h := NewHTTP()
assert.NotNil(t, h)
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
assert.Equal(t, req.URL.String(), "/resource/user")
body, err := io.ReadAll(req.Body)
assert.Nil(t, err)
assert.Equal(t, userdecl, string(body))
assert.Equal(t, "application/yaml", req.Header.Get("content-type"))
2024-04-10 19:38:12 +00:00
}))
defer server.Close()
re := regexp.MustCompile(`(?m)^(.*)$`)
decl := fmt.Sprintf(`
endpoint: "%s/resource/user"
headers:
- name: "content-type"
value: "application/yaml"
body: |
%s
`, server.URL, re.ReplaceAllString(userdecl, " $1"))
assert.Nil(t, h.LoadDecl(decl))
assert.Greater(t, len(h.Content), 0)
slog.Info("TestHTTPCreate()", "resource", h, "decl", decl)
2024-05-09 07:39:45 +00:00
e := h.Create(ctx)
2024-04-10 19:38:12 +00:00
assert.Nil(t, e)
}