async def test_call_blocknotify_and_has_block(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy, cmds={'blocknotify': 'echo "%s"'}) with patch.object(AsyncIOHTTPClient, '_call', side_effect=fake_call()): with patch.object(Poller, '_exec_command', side_effect=lambda x, y: None) as exec_mock: assert exec_mock.call_count == 0 await poller.blocknotify() assert exec_mock.call_count == 1
async def test_call_walletnotify_and_has_no_trans(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy, cmds={'walletnotify': 'echo "%s"'}) with patch.object(AsyncIOHTTPClient, '_call', side_effect=fake_call(['-eth_getFilterChanges'])): with patch.object(Poller, '_exec_command', side_effect=lambda x, y: None) as exec_mock: assert exec_mock.call_count == 0 await poller.walletnotify() assert exec_mock.call_count == 0
async def setUp(self): self.connection = connection.ConnectionHandler( 'Kappa', 'irc.twitch.tv', 6667) self.channel = Channel('botgotsthis', self.connection) self.whisper = WhisperMessage('botgotsthis', 'Kappa') patcher = patch('bot.config', autospec=True) self.addCleanup(patcher.stop) self.mock_config = patcher.start() self.mock_config.botnick = 'botgotsthis' patcher = patch('bot.utils.now', autospec=True) self.addCleanup(patcher.stop) self.mock_now = patcher.start() self.now = datetime(2000, 1, 1, 0, 0, 0) self.mock_now.return_value = self.now patcher = patch('bot.coroutine.join.disconnected') self.addCleanup(patcher.stop) self.mock_disconnected = patcher.start() with patch('asyncio.open_connection') as mock_connection,\ patch('sys.stdout', new_callable=StringIO),\ patch.object(connection.ConnectionHandler, 'login'): self.mock_transport = Mock(spec=asyncio.Transport) self.mock_reader = Mock(asyncio.StreamReader) self.mock_writer = Mock(asyncio.StreamWriter) self.mock_writer.transport = self.mock_transport mock_connection.return_value = self.mock_reader, self.mock_writer await self.connection.connect()
async def test_start_stop(self): with self.assertRaises(AssertionError): await self.get_admin_server().start() settings = {"admin.admin_insecure_mode": False} with self.assertRaises(AssertionError): await self.get_admin_server(settings).start() settings = { "admin.admin_insecure_mode": True, "admin.admin_api_key": "test-api-key", } with self.assertRaises(AssertionError): await self.get_admin_server(settings).start() settings = { "admin.admin_insecure_mode": False, "admin.admin_api_key": "test-api-key", } server = self.get_admin_server(settings) await server.start() await server.stop() with patch.object(web.TCPSite, "start", CoroutineMock()) as mock_start: mock_start.side_effect = OSError("Failure to launch") with self.assertRaises(AdminSetupError): await self.get_admin_server(settings).start()
def setUp(self): self.now = datetime(2000, 1, 1) self.channel = Mock(spec=Channel) self.channel.channel = 'botgotsthis' self.channel.sessionData = {} self.data = Mock(spec=CacheStore) self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.permissionSet = { 'owner': False, 'manager': False, 'staff': False, 'admin': False, 'globalMod': False, } self.permissions = MagicMock(spec=WhisperPermissionSet) self.permissions.__getitem__.side_effect = \ lambda k: self.permissionSet[k] self.args = WhisperCommandArgs(self.data, 'botgotsthis', Message(''), self.permissions, self.now) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database
def setUp(self): self.now = datetime(2000, 1, 1) self.send = Mock(spec=send) self.data = Mock(spec=CacheStore) self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.permissionSet = { 'owner': False, 'manager': False, 'inOwnerChannel': False, 'staff': False, 'admin': False, 'globalMod': False, 'broadcaster': False, 'moderator': False, 'subscriber': False, 'permitted': False, 'chatModerator': False, 'bannable': True, } self.permissions = MagicMock(spec=ChatPermissionSet) self.permissions.__getitem__.side_effect = \ lambda k: self.permissionSet[k] self.args = ManageBotArgs(self.data, self.permissions, self.send, 'botgotsthis', Message('')) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database
def testTlsServerServeForever(self): ''' Test StartTcpServer serve_forever() method ''' with patch('asyncio.base_events.Server.serve_forever', new_callable=asynctest.CoroutineMock) as serve: with patch.object(ssl.SSLContext, 'load_cert_chain') as mock_method: server = yield from StartTlsServer(context=self.context,address=("127.0.0.1", 0), loop=self.loop) yield from server.serve_forever() serve.assert_awaited()
def setUp(self): self.now = datetime(2000, 1, 1) self.tags = IrcMessageTags() self.channel = Mock(spec=Channel) self.channel.channel = 'botgotsthis' self.data = Mock(spec=CacheStore) self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.permissionSet = { 'owner': False, 'inOwnerChannel': False, 'staff': False, 'admin': False, 'globalMod': False, 'broadcaster': False, 'moderator': False, 'subscriber': False, 'chatModerator': False, } self.permissions = MagicMock(spec=ChatPermissionSet) self.permissions.inOwnerChannel = False self.permissions.__getitem__.side_effect = \ lambda k: self.permissionSet[k] self.messages = ['Kappa'] self.args = CustomProcessArgs(self.data, self.channel, self.tags, 'botgotsthis', self.permissions, 'botgotsthis', '', 'kappa', self.messages) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database
async def test_method__is_account_trans_and_trans_exists(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy) with patch.object(AsyncIOHTTPClient, '_call', side_effect=fake_call()): txid = '0x9c864dd0e7fdcfb3bd7197020ac311cbacef1aa29b49791223427bbedb6d36ad' is_account_trans = await poller._is_account_trans(txid) assert is_account_trans is True
async def test_report_state_all(agents): """Test a disconnect message.""" config = MockConfig(agent_user_ids=agents) data = {} with patch.object(config, "async_report_state") as mock: await config.async_report_state_all(data) assert sorted(mock.mock_calls) == sorted( [call(data, agent) for agent in agents])
async def test_responder_webhook(self): with patch.object(AdminServer, "send_webhook", autospec=True) as sender: admin_server = self.get_admin_server() test_topic = "test_topic" test_payload = {"test": "TEST"} await admin_server.responder.send_webhook(test_topic, test_payload) sender.assert_awaited_once_with(admin_server, test_topic, test_payload)
def setUp(self): self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.send = Mock(spec=send) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database
async def test_method__build_filter_which_not_exists(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy) with patch.object(AsyncIOHTTPClient, '_call', side_effect=fake_call('-')): with pytest.raises(KeyError) as excinfo: await poller._build_filter('doesnotexists') assert 'doesnotexists' in str(excinfo)
def testStartTlsServer(self): ''' Test that the modbus tls asyncio server starts correctly ''' with patch.object(ssl.SSLContext, 'load_cert_chain') as mock_method: identity = ModbusDeviceIdentification(info={0x00: 'VendorName'}) self.loop = asynctest.Mock(self.loop) server = yield from StartTlsServer(context=self.context,loop=self.loop,identity=identity) self.assertEqual(server.control.Identity.VendorName, 'VendorName') self.assertIsNotNone(server.sslctx) if PYTHON_VERSION >= (3, 6): self.loop.create_server.assert_called_once()
async def test_method__poll_with_reconnect_when_droped(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy) with patch.object(AsyncIOHTTPClient, '_call', side_effect=return_once( lambda: BadResponseError('test', code=-99999999), then=fake_call())): poller._pending = '0x6f4111062b3db311e6521781f4ef0046' await poller._poll_with_reconnect('pending')
def testTlsServerServeNoDefer(self): ''' Test StartTcpServer without deferred start (immediate execution of server) ''' with patch('asyncio.base_events.Server.serve_forever', new_callable=asynctest.CoroutineMock) as serve: with patch.object(ssl.SSLContext, 'load_cert_chain') as mock_method: server = yield from StartTlsServer(context=self.context, address=("127.0.0.1", 0), loop=self.loop, defer_start=False) serve.assert_awaited()
async def test_sync_entities_all(agents, result): """Test sync entities .""" config = MockConfig(agent_user_ids=set(agents.keys())) with patch.object( config, "async_sync_entities", side_effect=lambda agent_user_id: agents[agent_user_id], ) as mock: res = await config.async_sync_entities_all() assert sorted(mock.mock_calls) == sorted([call(agent) for agent in agents]) assert res == result
def testTlsServerServeForeverTwice(self): ''' Call on serve_forever() twice should result in a runtime error ''' with patch.object(ssl.SSLContext, 'load_cert_chain') as mock_method: server = yield from StartTlsServer(context=self.context,address=("127.0.0.1", 0), loop=self.loop) if PYTHON_VERSION >= (3, 7): server_task = asyncio.create_task(server.serve_forever()) else: server_task = asyncio.ensure_future(server.serve_forever()) yield from server.serving with self.assertRaises(RuntimeError): yield from server.serve_forever() server.server_close()
async def test_media_title(player, state, source, channel, title): """Test media title.""" from homeassistant.components.arcam_fmj.media_player import ArcamFmj state.get_source.return_value = source with patch.object(ArcamFmj, "media_channel", new_callable=PropertyMock) as media_channel: media_channel.return_value = channel data = await update(player) if title is None: assert "media_title" not in data.attributes else: assert data.attributes["media_title"] == title
def setUp(self): self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.send = Mock(spec=send) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database patcher = patch('bot.utils.joinChannel', autospec=True) self.addCleanup(patcher.stop) self.mock_join = patcher.start()
async def test_method__build_filter_which_exists(self): with patch('ethereumd.poller.Poller.poll'): poller = Poller(self.rpc_proxy) with patch.object(AsyncIOHTTPClient, '_call', side_effect=fake_call()): # latest filter for blocks assert hasattr(poller, '_latest') is False, \ 'Poller must not have here _latest attr' await poller._build_filter('latest') assert hasattr(poller, '_latest') is True, \ 'Poller must have here _latest attr' # pending filter for transacs assert hasattr(poller, '_pending') is False, \ 'Poller must not have here _pending attr' await poller._build_filter('pending') assert hasattr(poller, '_pending') is True, \ 'Poller must have here _pending attr'
def setUp(self): self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.send = Mock(spec=send) patcher = patch('bot.utils.partChannel', autospec=True) self.addCleanup(patcher.stop) self.mock_part = patcher.start() patcher = patch('bot.config', autospec=True) self.addCleanup(patcher.stop) self.mock_config = patcher.start() self.mock_config.botnick = 'botgotsthis' patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database
async def test_server_handler_index_type_error_call(self, event_loop): server = await self.init_server(event_loop) data = { 'jsonrpc': '2.0', 'method': 'getblockcount', 'params': [], 'id': 'test', } request = Request(json=data) def _raise_error(): raise TypeError('test') with patch.object(EthereumProxy, 'getblockcount', side_effect=_raise_error): response = await server.handler_index(request) parsed = json.loads(response.body) assert parsed['error']['code'] == -1 assert parsed['error']['message'] == 'test' assert parsed['result'] is None
def setUp(self): self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.database.isChannelBannedReason.return_value = None self.send = Mock(spec=send) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database patcher = patch(library.__name__ + '.auto_join_add') self.addCleanup(patcher.stop) self.mock_add = patcher.start() self.mock_add.return_value = True patcher = patch(library.__name__ + '.auto_join_delete') self.addCleanup(patcher.stop) self.mock_delete = patcher.start() self.mock_delete.return_value = True
def setUp(self): self.now = datetime(2000, 1, 1) self.tags = IrcMessageTags() self.channel = Mock(spec=Channel) self.channel.channel = 'botgotsthis' self.channel.sessionData = {} self.data = Mock(spec=CacheStore) self.data.hasFeature.side_effect = lambda c, f: f in self.features self.database = MagicMock(spec=DatabaseMain) self.database.__aenter__.return_value = self.database self.database.__aexit__.return_value = False self.features = [] self.database.hasFeature.side_effect = lambda c, f: f in self.features self.permissionSet = { 'owner': False, 'manager': False, 'inOwnerChannel': False, 'staff': False, 'admin': False, 'globalMod': False, 'broadcaster': False, 'moderator': False, 'subscriber': False, 'permitted': False, 'chatModerator': False, 'bannable': True, } self.permissions = MagicMock(spec=ChatPermissionSet) self.permissions.inOwnerChannel = False self.permissions.__getitem__.side_effect = \ lambda k: self.permissionSet[k] self.args = ChatCommandArgs(self.data, self.channel, self.tags, 'botgotsthis', Message(''), self.permissions, self.now) patcher = patch.object(DatabaseMain, 'acquire') self.addCleanup(patcher.stop) self.mock_database = patcher.start() self.mock_database.return_value = self.database