Skip to content

Commit

Permalink
Add HTMLSession.browser runtime exception, AsyncSession an async clos…
Browse files Browse the repository at this point in the history
…e method
  • Loading branch information
oldani authored and pigna90 committed Sep 19, 2018
1 parent 47a3646 commit 2d4c58d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions requests_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,8 @@ def __init__(self, **kwargs):
def browser(self):
if not hasattr(self, "_browser"):
self.loop = asyncio.get_event_loop()
if self.loop.is_running():
raise RuntimeError("Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.")
self._browser = self.loop.run_until_complete(super().browser)
return self._browser

Expand Down Expand Up @@ -711,3 +713,9 @@ def request(self, *args, **kwargs):
""" Partial original request func and run it in a thread. """
func = partial(super().request, *args, **kwargs)
return self.loop.run_in_executor(self.thread_pool, func)

async def close(self):
""" If a browser was created close it first. """
if hasattr(self, "_browser"):
await self._browser.close()
super().close()
17 changes: 17 additions & 0 deletions tests/test_requests_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,15 @@ def test_browser_session():
# assert count_chromium_process() == 0


@pytest.mark.ok
@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.ok
def test_browser_process():
for _ in range(3):
Expand All @@ -256,6 +265,14 @@ def test_browser_process():
assert r.html.page == None


@pytest.mark.ok
@pytest.mark.asyncio
async def test_async_browser_session():
session = AsyncHTMLSession()
browser = await session.browser
assert isinstance(browser, Browser)
await session.close()


if __name__ == '__main__':
test_containing()

0 comments on commit 2d4c58d

Please sign in to comment.