forked from psf/requests-html
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathtest_requests_html.py
324 lines (243 loc) · 8.32 KB
/
test_requests_html.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import os
from functools import partial
import pytest
from pyppeteer.browser import Browser
from pyppeteer.page import Page
from requests_html import HTMLSession, AsyncHTMLSession, HTML
from requests_file import FileAdapter
session = HTMLSession()
session.mount('file://', FileAdapter())
def get():
path = os.path.sep.join((os.path.dirname(os.path.abspath(__file__)), 'python.html'))
url = f'file://{path}'
return session.get(url)
@pytest.fixture
def async_get(event_loop):
"""AsyncSession cannot be created global since it will create
a different loop from pytest-asyncio. """
async_session = AsyncHTMLSession()
async_session.mount('file://', FileAdapter())
path = os.path.sep.join((os.path.dirname(os.path.abspath(__file__)), 'python.html'))
url = 'file://{}'.format(path)
return partial(async_session.get, url)
def test_file_get():
r = get()
assert r.status_code == 200
@pytest.mark.asyncio
async def test_async_file_get(async_get):
r = await async_get()
assert r.status_code == 200
def test_class_seperation():
r = get()
about = r.html.find('#about', first=True)
assert len(about.attrs['class']) == 2
def test_css_selector():
r = get()
about = r.html.find('#about', first=True)
for menu_item in (
'About', 'Applications', 'Quotes', 'Getting Started', 'Help',
'Python Brochure'
):
assert menu_item in about.text.split('\n')
assert menu_item in about.full_text.split('\n')
def test_containing():
r = get()
python = r.html.find(containing='python')
assert len(python) == 192
for e in python:
assert 'python' in e.full_text.lower()
def test_attrs():
r = get()
about = r.html.find('#about', first=True)
assert 'aria-haspopup' in about.attrs
assert len(about.attrs['class']) == 2
def test_links():
r = get()
about = r.html.find('#about', first=True)
assert len(about.links) == 6
assert len(about.absolute_links) == 6
@pytest.mark.asyncio
async def test_async_links(async_get):
r = await async_get()
about = r.html.find('#about', first=True)
assert len(about.links) == 6
assert len(about.absolute_links) == 6
def test_search():
r = get()
style = r.html.search('Python is a {} language')[0]
assert style == 'programming'
def test_xpath():
r = get()
html = r.html.xpath('/html', first=True)
assert 'no-js' in html.attrs['class']
a_hrefs = r.html.xpath('//a/@href')
assert '#site-map' in a_hrefs
def test_html_loading():
doc = """<a href='https://httpbin.org'>"""
html = HTML(html=doc)
assert 'https://httpbin.org' in html.links
assert isinstance(html.raw_html, bytes)
assert isinstance(html.html, str)
def test_anchor_links():
r = get()
r.html.skip_anchors = False
assert '#site-map' in r.html.links
@pytest.mark.parametrize('url,link,expected', [
('http://example.com/', 'test.html', 'http://example.com/test.html'),
('http://example.com', 'test.html', 'http://example.com/test.html'),
('http://example.com/foo/', 'test.html', 'http://example.com/foo/test.html'),
('http://example.com/foo/bar', 'test.html', 'http://example.com/foo/test.html'),
('http://example.com/foo/', '/test.html', 'http://example.com/test.html'),
('http://example.com/', 'http://xkcd.com/about/', 'http://xkcd.com/about/'),
('http://example.com/', '//xkcd.com/about/', 'http://xkcd.com/about/'),
])
def test_absolute_links(url, link, expected):
head_template = """<head><base href='{}'></head>"""
body_template = """<body><a href='{}'>Next</a></body>"""
# Test without `<base>` tag (url is base)
html = HTML(html=body_template.format(link), url=url)
assert html.absolute_links.pop() == expected
# Test with `<base>` tag (url is other)
html = HTML(
html=head_template.format(url) + body_template.format(link),
url='http://example.com/foobar/')
assert html.absolute_links.pop() == expected
def test_parser():
doc = """<a href='https://httpbin.org'>httpbin.org\n</a>"""
html = HTML(html=doc)
assert html.find('html')
assert html.element('a').text().strip() == 'httpbin.org'
@pytest.mark.render
def test_render():
r = get()
script = """
() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio,
}
}
"""
val = r.html.render(script=script)
for value in ('width', 'height', 'deviceScaleFactor'):
assert value in val
about = r.html.find('#about', first=True)
assert len(about.links) == 6
@pytest.mark.render
@pytest.mark.asyncio
async def test_async_render(async_get):
r = await async_get()
script = """
() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio,
}
}
"""
val = await r.html.arender(script=script)
for value in ('width', 'height', 'deviceScaleFactor'):
assert value in val
about = r.html.find('#about', first=True)
assert len(about.links) == 6
await r.html.browser.close()
@pytest.mark.render
def test_bare_render():
doc = """<a href='https://httpbin.org'>"""
html = HTML(html=doc)
script = """
() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio,
}
}
"""
val = html.render(script=script, reload=False)
for value in ('width', 'height', 'deviceScaleFactor'):
assert value in val
assert html.find('html')
assert 'https://httpbin.org' in html.links
@pytest.mark.render
@pytest.mark.asyncio
async def test_bare_arender():
doc = """<a href='https://httpbin.org'>"""
html = HTML(html=doc, async_=True)
script = """
() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio,
}
}
"""
val = await html.arender(script=script, reload=False)
for value in ('width', 'height', 'deviceScaleFactor'):
assert value in val
assert html.find('html')
assert 'https://httpbin.org' in html.links
await html.browser.close()
@pytest.mark.render
def test_bare_js_eval():
doc = """
<!DOCTYPE html>
<html>
<body>
<div id="replace">This gets replaced</div>
<script type="text/javascript">
document.getElementById("replace").innerHTML = "yolo";
</script>
</body>
</html>
"""
html = HTML(html=doc)
html.render()
assert html.find('#replace', first=True).text == 'yolo'
@pytest.mark.render
@pytest.mark.asyncio
async def test_bare_js_async_eval():
doc = """
<!DOCTYPE html>
<html>
<body>
<div id="replace">This gets replaced</div>
<script type="text/javascript">
document.getElementById("replace").innerHTML = "yolo";
</script>
</body>
</html>
"""
html = HTML(html=doc, async_=True)
await html.arender()
assert html.find('#replace', first=True).text == 'yolo'
await html.browser.close()
def test_browser_session():
""" Test browser instances is created and properly close when session is closed.
Note: session.close method need to be tested together with browser creation,
since not doing that will leave the browser running. """
session = HTMLSession()
assert isinstance(session.browser, Browser)
assert hasattr(session, "loop")
session.close()
# assert count_chromium_process() == 0
def test_browser_process():
for _ in range(3):
r = get()
r.html.render()
assert r.html.page is None
@pytest.mark.asyncio
async def test_browser_session_fail():
""" HTMLSession.browser should not be call within an existing event loop> """
session = HTMLSession()
with pytest.raises(RuntimeError):
session.browser
@pytest.mark.asyncio
async def test_async_browser_session():
session = AsyncHTMLSession()
browser = await session.browser
assert isinstance(browser, Browser)
await session.close()