Skip to content

Commit

Permalink
feat(gather): introduce sync gather for easier async tests migration
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Aug 2, 2020
1 parent fdf2759 commit 066d988
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
34 changes: 33 additions & 1 deletion playwright/sync_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
# limitations under the License.

import asyncio
from typing import Any, Callable, Coroutine, Generic, Optional, TypeVar, cast
import sys
from typing import Any, Callable, Coroutine, Dict, Generic, List, Optional, TypeVar, cast

import greenlet

Expand Down Expand Up @@ -109,3 +110,34 @@ def once(self, event_name: str, handler: Any) -> None:

def remove_listener(self, event_name: str, handler: Any) -> None:
self._impl_obj.remove_listener(event_name, handler)

def _gather(self, actions: List[Callable]) -> List[Any]:
g_self = greenlet.getcurrent()
results: Dict[Callable, Any] = {}
exceptions: List[Exception] = []

def action_wrapper(action):
def body():
try:
results[action] = action()
except Exception as e:
results[action] = e
exceptions.append(e)
g_self.switch()
return body

async def task():
for action in actions:
g = greenlet.greenlet(action_wrapper(action))
g.switch()

self._loop.create_task(task())

while len(results) < len(actions):
dispatcher_fiber_.switch()

asyncio._set_running_loop(self._loop)
if exceptions:
raise exceptions[0]

return list(map(lambda action: results[action], actions))
10 changes: 10 additions & 0 deletions tests/sync/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,13 @@ def test_sync_set_default_timeout(page):
with pytest.raises(TimeoutError) as exc:
page.waitForFunction("false")
assert "Timeout 1ms exceeded." in exc.value.message


def test_close_should_reject_all_promises(context):
new_page = context.newPage()
with pytest.raises(Error) as exc_info:
new_page._gather([
lambda: new_page.evaluate("() => new Promise(r => {})"),
lambda: new_page.close()
])
assert "Protocol error" in exc_info.value.message

0 comments on commit 066d988

Please sign in to comment.