-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathxpath.py
More file actions
39 lines (33 loc) · 1.2 KB
/
xpath.py
File metadata and controls
39 lines (33 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import re
from lxml import etree as lxmletree
def check_xpath(etree, fname, path, check, be_found=True):
nodes = list(etree.xpath(path))
if check is None:
assert nodes == [], f'found any nodes matching xpath {path!r} in file {fname}'
return
else:
assert nodes != [], f'did not find any node matching xpath {path!r} in file {fname}'
if callable(check):
check(nodes)
elif not check:
# only check for node presence
pass
else:
def get_text(node):
return lxmletree.tostring(node, encoding='unicode', method='text')
rex = re.compile(check)
if be_found:
if any(rex.search(get_text(node)) for node in nodes):
return
msg = (
f'{check!r} not found in any node matching path {path} in {fname}: '
f'{[node.text for node in nodes]!r}'
)
else:
if all(not rex.search(get_text(node)) for node in nodes):
return
msg = (
f'Found {check!r} in a node matching path {path} in {fname}: '
f'{[node.text for node in nodes]!r}'
)
raise AssertionError(msg)