Skip to content

Commit

Permalink
feat(domtest)!: add Request parser for DocumentFragment
Browse files Browse the repository at this point in the history
also changes the signature for the parsers
the previous type has been removed
  • Loading branch information
crhntr committed Jun 23, 2024
1 parent 97e0884 commit 5317d85
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
26 changes: 20 additions & 6 deletions domtest/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,15 @@ func Reader(t T, r io.Reader) spec.Document {
return dom.NewNode(node).(spec.Document)
}

func DocumentFragment(t T, r io.Reader, parent atom.Atom) []spec.Element {
func DocumentFragmentReader(t T, r io.Reader, parent atom.Atom) spec.DocumentFragment {
t.Helper()
nodes, err := html.ParseFragment(r, &html.Node{

body, err := io.ReadAll(r)
if err != nil {
t.Error(err)
return nil
}
nodes, err := html.ParseFragment(bytes.NewReader(body), &html.Node{
Type: html.ElementNode,
Data: parent.String(),
DataAtom: parent,
Expand All @@ -69,9 +75,17 @@ func DocumentFragment(t T, r io.Reader, parent atom.Atom) []spec.Element {
t.Error(err)
return nil
}
var result []spec.Element
for _, node := range nodes {
result = append(result, dom.NewNode(node).(spec.Element))
return dom.NewDocumentFragment(nodes)
}

func DocumentFragmentResponse(t T, res *http.Response, parent atom.Atom) spec.DocumentFragment {
t.Helper()
defer closeAndCheckError(t, res.Body)
return DocumentFragmentReader(t, res.Body, parent)
}

func closeAndCheckError(t T, c io.Closer) {
if err := c.Close(); err != nil {
t.Error(err)
}
return result
}
19 changes: 19 additions & 0 deletions domtest/document_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/html/atom"

"github.com/crhntr/dom/domtest"
"github.com/crhntr/dom/internal/fakes"
"github.com/crhntr/dom/spec"
)

var (
Expand Down Expand Up @@ -136,6 +138,23 @@ func TestResponse(t *testing.T) {
})
}

func TestDocumentFragment(t *testing.T) {
t.Run("when a valid html document is passed", func(t *testing.T) {
testingT := new(fakes.T)
res := &http.Response{
Body: io.NopCloser(strings.NewReader(fragmentHTML)),
}
fragment := domtest.DocumentFragmentResponse(testingT, res, atom.Body)

assert.Equal(t, testingT.ErrorCallCount(), 0, "it should not report errors")
assert.Equal(t, testingT.LogCallCount(), 0)
assert.NotZero(t, testingT.HelperCallCount())

require.NotNil(t, fragment)
require.Equal(t, spec.NodeTypeDocumentFragment, fragment.NodeType())
})
}

func TestReader(t *testing.T) {
testingT := new(fakes.T)
r := iotest.ErrReader(errors.New("banana"))
Expand Down

0 comments on commit 5317d85

Please sign in to comment.