Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cssselect/xpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ def join(self, combiner: str, other: XPathExpr) -> Self:
# Test that the string is not empty and does not contain whitespace
is_non_whitespace = re.compile(r"[^ \t\r\n\f]+").fullmatch

# Characters not allowed in XML 1.0, which therefore cannot be part of an XPath
# expression either.
_has_non_xml_char = re.compile(
"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]"
).search


def _or_conditions(conditions: list[str]) -> str:
"""Join conditions with "or"."""
Expand Down Expand Up @@ -284,6 +290,8 @@ def xpath_pseudo_element(
@staticmethod
def xpath_literal(s: str) -> str:
s = str(s)
if _has_non_xml_char(s):
raise ExpressionError(f"{s!r} contains a character not allowed in XML")
if "'" not in s:
s = f"'{s}'"
elif '"' not in s:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_cssselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1219,6 +1219,14 @@ def test_input_preprocessing(self) -> None:
# A raw NUL in an identifier becomes a valid U+FFFD name character.
assert str(next(tokenize("foo\x00bar"))) == "<IDENT 'foo�bar' at 0>"

def test_non_xml_characters(self) -> None:
# Characters not allowed in XML cannot be put in an XPath string.
css_to_xpath = GenericTranslator().css_to_xpath
with pytest.raises(ExpressionError):
css_to_xpath('*[aval="x\x01y"]')
with pytest.raises(ExpressionError):
css_to_xpath(':contains("x\uffffy")')

def test_xpath_pseudo_elements(self) -> None:
class CustomTranslator(GenericTranslator):
def xpath_pseudo_element(
Expand Down
27 changes: 15 additions & 12 deletions tests/test_hypothesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@
import typing
from typing import TYPE_CHECKING

import pytest
from hypothesis import given
from hypothesis import strategies as st
from lxml import etree

from cssselect import GenericTranslator, HTMLTranslator, SelectorError, parse
from cssselect import (
ExpressionError,
GenericTranslator,
HTMLTranslator,
SelectorError,
parse,
)
from cssselect.parser import (
Token,
TokenStream,
Expand Down Expand Up @@ -191,10 +196,7 @@ def test_css_like(css: str) -> None:
xpath = translator.css_to_xpath(css)
except SelectorError:
continue
# Escapes like "\b" can produce characters not allowed in XML, a known
# problem tested by test_escape_translates_non_xml().
if not any(c in NON_XML_CHARS for c in xpath):
etree.XPath(xpath)
etree.XPath(xpath)
try:
selectors = parse(css)
except SelectorError:
Expand All @@ -205,7 +207,13 @@ def test_css_like(css: str) -> None:
def check_escape_translates(context: str, char: str) -> None:
css = context.format(f"\\{ord(char):x} ")
for translator in (GenericTranslator(), HTMLTranslator()):
etree.XPath(translator.css_to_xpath(css))
try:
xpath = translator.css_to_xpath(css)
except ExpressionError:
# Characters not allowed in XML cannot be put in an XPath string.
assert char in NON_XML_CHARS
continue
etree.XPath(xpath)


@given(
Expand All @@ -216,11 +224,6 @@ def test_escape_translates(context: str, char: str) -> None:
check_escape_translates(context, char)


@pytest.mark.xfail(
raises=ValueError,
strict=True,
reason="Characters not allowed in XML end up in the XPath expression",
)
@given(st.sampled_from(ESCAPE_CONTEXTS), st.sampled_from(NON_XML_CHARS))
def test_escape_translates_non_xml(context: str, char: str) -> None:
check_escape_translates(context, char)
Loading