Skip to content

Commit

Permalink
fix #38 MustCompile method will return nopQuery object instead of…
Browse files Browse the repository at this point in the history
… `nil` when input expr is an invalid XPath expression.
  • Loading branch information
zhengchun committed Nov 2, 2019
1 parent 668f667 commit d50eb4d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
11 changes: 11 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ type query interface {
Clone() query
}

// nopQuery is an empty query that always return nil for any query.
type nopQuery struct {
query
}

func (nopQuery) Select(iterator) NodeNavigator { return nil }

func (nopQuery) Evaluate(iterator) interface{} { return nil }

func (nopQuery) Clone() query { return nopQuery{} }

// contextQuery is returns current node on the iterator object query.
type contextQuery struct {
count int
Expand Down
2 changes: 1 addition & 1 deletion xpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func Compile(expr string) (*Expr, error) {
func MustCompile(expr string) *Expr {
exp, err := Compile(expr)
if err != nil {
return nil
return &Expr{s: expr, q: nopQuery{}}
}
return exp
}
16 changes: 16 additions & 0 deletions xpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ func TestCompile(t *testing.T) {
t.Fatalf("/a/b/(c, .[not(c)]) should be correct but got error %s", err)
}
}

func TestMustCompile(t *testing.T) {
expr := MustCompile("//")
if expr == nil {
t.Fatal("// should be compiled but got nil object")
}

if wanted := (nopQuery{}); expr.q != wanted {
t.Fatalf("wanted nopQuery object but got %s", expr)
}
iter := expr.Select(createNavigator(html))
if iter.MoveNext() {
t.Fatal("should be an empty node list but got one")
}
}

func TestSelf(t *testing.T) {
testXPath(t, html, ".", "html")
testXPath(t, html.FirstChild, ".", "head")
Expand Down

0 comments on commit d50eb4d

Please sign in to comment.