Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_once():
"""Test that `once()` method works propers.
"""
# very similar to "test_emit" but also makes sure that the event
# gets removed afterwards
ee = EventEmitter()
def once_handler(data, error=None):
nt.assert_equals(data, 'emitter is emitted!')
if (error):
raise ItWorkedException
# Tests to make sure that after event is emitted that it's gone.
ee.once('event', once_handler)
ee.emit('event', 'emitter is emitted!')
nt.assert_equal(ee._events['event'], [])
# Tests to make sure callback fires. "Hides" other exceptions.
with nt.assert_raises(ItWorkedException) as it_worked: # noqa
ee.once('event', once_handler)
ee.emit('event', 'emitter is emitted!', True)
EventEmitter
])
def test_emit_error(cls):
"""Errors raise with no event handler, otherwise emit on handler"""
call_me = Mock()
ee = cls()
test_exception = PyeeTestException('lololol')
with raises(PyeeTestException):
ee.emit('error', test_exception)
@ee.on('error')
def on_error(exc):
call_me()
def __init__(self, application, request, **kwargs):
super().__init__(application, request, **kwargs)
self.emitter = EventEmitter()
self.should_auth = should_auth
self.heartbeat = heartbeat
self.channels = []
self.reconnect_count = 0
super().__init__(
url=self.gen_url(),
header=self.header(),
on_message=self.on_message,
on_close=self.on_close,
on_open=self.on_open,
on_error=self.on_error,
on_pong=self.on_pong,
**kwargs
)
super(EventEmitter, self).__init__()
self.on('subscribe', self.on_subscribe)
if not id in self.data[collection]:
self.data[collection][id] = {}
for key, value in fields.items():
self.data[collection][id][key] = value
def change_data(self, collection, id, fields, cleared):
for key, value in fields.items():
self.data[collection][id][key] = value
for key in cleared:
del self.data[collection][id][key]
def remove_data(self, collection, id):
del self.data[collection][id]
class MeteorClient(EventEmitter):
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False):
EventEmitter.__init__(self)
self.collection_data = CollectionData()
self.ddp_client = DDPClient(url, auto_reconnect=auto_reconnect,
auto_reconnect_timeout=auto_reconnect_timeout, debug=debug)
self.ddp_client.on('connected', self.connected)
self.ddp_client.on('socket_closed', self.closed)
self.ddp_client.on('failed', self.failed)
self.ddp_client.on('added', self.added)
self.ddp_client.on('changed', self.changed)
self.ddp_client.on('removed', self.removed)
self.ddp_client.on('reconnected', self._reconnected)
self.connected = False
self.subscriptions = {}
self._login_data = None
self._login_token = None
def __init__(self):
self.log = create_logger()
self.ui_block = pyee.EventEmitter()
self.ui_dialog = pyee.EventEmitter()
self.ui_imsg = pyee.EventEmitter()
self._in_msg = pyee.EventEmitter()
self._in_msg.on('block_actions', self._handle_block_actions)
self._in_msg.on('dialog_submission', self._handle_dialog_submit)
self._in_msg.on('interactive_message', self._handle_imsg)
self.config = SlackAppConfig()
self._connected = False
await self._on_close()
async def createSession(self, targetInfo: Dict) -> 'CDPSession':
"""Create new session."""
resp = await self.send(
'Target.attachToTarget',
{'targetId': targetInfo['targetId']}
)
sessionId = resp.get('sessionId')
session = CDPSession(self, targetInfo['type'], sessionId, self._loop)
self._sessions[sessionId] = session
return session
class CDPSession(EventEmitter):
"""Chrome Devtools Protocol Session.
The :class:`CDPSession` instances are used to talk raw Chrome Devtools
Protocol:
* protocol methods can be called with :meth:`send` method.
* protocol events can be subscribed to with :meth:`on` method.
Documentation on DevTools Protocol can be found
`here `__.
"""
def __init__(self, connection: Union[Connection, 'CDPSession'],
targetType: str, sessionId: str,
loop: asyncio.AbstractEventLoop) -> None:
"""Make new session."""
self.running = False
self.sleeping = False
def recognizer_conf_hash(config):
"""Hash of the values important to the listener."""
c = {
'listener': config.get('listener'),
'hotwords': config.get('hotwords'),
'stt': config.get('stt'),
'opt_in': config.get('opt_in', False)
}
return hash(json.dumps(c, sort_keys=True))
class RecognizerLoop(EventEmitter):
""" EventEmitter loop running speech recognition.
Local wake word recognizer and remote general speech recognition.
"""
def __init__(self):
super(RecognizerLoop, self).__init__()
self.mute_calls = 0
self._load_config()
def _load_config(self):
"""Load configuration parameters from configuration."""
config = Configuration.get()
self.config_core = config
self._config_hash = recognizer_conf_hash(config)
self.lang = config.get('lang')
from typing import Any, Awaitable, Dict, Generator, List, Optional, Set, Union
from pyee import EventEmitter
from pyppeteer import helper
from pyppeteer.connection import CDPSession
from pyppeteer.element_handle import ElementHandle
from pyppeteer.errors import NetworkError
from pyppeteer.execution_context import ExecutionContext, JSHandle
from pyppeteer.errors import ElementHandleError, PageError, TimeoutError
from pyppeteer.util import merge_dict
logger = logging.getLogger(__name__)
class FrameManager(EventEmitter):
"""FrameManager class."""
Events = SimpleNamespace(
FrameAttached='frameattached',
FrameNavigated='framenavigated',
FrameDetached='framedetached',
LifecycleEvent='lifecycleevent',
FrameNavigatedWithinDocument='framenavigatedwithindocument',
)
def __init__(self, client: CDPSession, frameTree: Dict, page: Any) -> None:
"""Make new frame manager."""
super().__init__()
self._client = client
self._page = page
self._frames: OrderedDict[str, Frame] = OrderedDict()