Skip to content

Commit ca714a4

Browse files
authored
Prevent find/2 from crashing with empty selector (#631)
Closes #605
1 parent 541bdce commit ca714a4

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

lib/floki/finder.ex

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,15 @@ defmodule Floki.Finder do
4242

4343
def find(html_tree, selector_as_string) when is_binary(selector_as_string) do
4444
selectors = Selector.Parser.parse(selector_as_string)
45-
find(html_tree, selectors)
45+
46+
if selectors != [] do
47+
find(html_tree, selectors)
48+
else
49+
[]
50+
end
4651
end
4752

48-
def find(html_tree, selector = %Selector{}) do
53+
def find(html_tree, %Selector{} = selector) do
4954
find(html_tree, [selector])
5055
end
5156

test/floki/selector/parser_test.exs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,4 +431,10 @@ defmodule Floki.Selector.ParserTest do
431431
assert capture_log(log_capturer("a + b@")) =~
432432
~r/module=Floki\.Selector\.Parser Unknown token ('@'|~c"@")\. Ignoring/
433433
end
434+
435+
test "empty selector" do
436+
tokens = tokenize("")
437+
438+
assert Parser.parse(tokens) == []
439+
end
434440
end

test/floki_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,13 @@ defmodule FlokiTest do
19861986
Floki.Finder.find(html_tree, [selector_struct_1, selector_struct_2])
19871987
end
19881988

1989+
# Floki.find/2 - Empty case
1990+
1991+
test "find with an empty selector" do
1992+
html = document!(@html)
1993+
assert Floki.find(html, "") == []
1994+
end
1995+
19891996
# Floki.get_by_id/2
19901997

19911998
test "get_by_id finds element with special characters" do

0 commit comments

Comments
 (0)