def setUp(self): patcher1 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.load_config') # NOQA self.addCleanup(patcher1.stop) self.mock_load_config = patcher1.start() patcher2 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.SlackUser') # NOQA self.addCleanup(patcher2.stop) self.mock_slack_user = patcher2.start() patcher3 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.http_post_request') # NOQA self.addCleanup(patcher3.stop) self.mock_http_post_request = patcher3.start() patcher4 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.get_trigger_payload') # NOQA self.addCleanup(patcher4.stop) self.mock_get_trigger_payload = patcher4.start() self.slack_message = SlackMessage(type="message", user="******", channel="C2147483705", text="This is a dummy message") from charlesbot_pagerduty_escalations.pagerdutyescalations import PagerdutyEscalations # NOQA self.pd = PagerdutyEscalations() self.pd.slack = MagicMock() self.pd.slack.send_channel_message = MagicMock() self.pd.pd_service_mappings = { "service1": "pd_key_1" }
async def test_thinking_sleep(self): with OpsDroid() as opsdroid: mock_connector_int = Connector({ 'name': 'shell', 'thinking-delay': 3, 'type': 'connector', 'module_path': 'opsdroid-modules.connector.shell' }, opsdroid=opsdroid) with amock.patch('asyncio.sleep') as mocksleep_int: message = events.Message("hi", "user", "default", mock_connector_int) with self.assertRaises(TypeError): await message.respond("Hello there") self.assertTrue(mocksleep_int.called) # Test thinking-delay with a list mock_connector_list = Connector({ 'name': 'shell', 'thinking-delay': [1, 4], 'type': 'connector', 'module_path': 'opsdroid-modules.connector.shell' }, opsdroid=opsdroid) with amock.patch('asyncio.sleep') as mocksleep_list: message = events.Message("hi", "user", "default", mock_connector_list) with self.assertRaises(TypeError): await message.respond("Hello there") self.assertTrue(mocksleep_list.called)
def setUp(self): patcher1 = patch('charlesbot.plugins.ping_plugin.Ping.schedule_ping_frequency') # NOQA self.addCleanup(patcher1.stop) self.mock_schedule_ping_frequency = patcher1.start() patcher2 = patch('charlesbot.plugins.ping_plugin.Ping.get_package_version_number') # NOQA self.addCleanup(patcher2.stop) self.mock_get_package_version_number = patcher2.start() from charlesbot.plugins.ping_plugin import Ping self.ping = Ping() self.ping.send_version_message = MagicMock()
async def test_web_start(self): """Check the stats handler.""" with OpsDroid() as opsdroid: with amock.patch('aiohttp.web.AppRunner.setup') as mock_runner, \ amock.patch('aiohttp.web.TCPSite.__init__') as mock_tcpsite, \ amock.patch('aiohttp.web.TCPSite.start') as mock_tcpsite_start: mock_tcpsite.return_value = None app = web.Web(opsdroid) await app.start() self.assertTrue(mock_runner.called) self.assertTrue(mock_tcpsite.called) self.assertTrue(mock_tcpsite_start.called)
def setUp(self): patcher1 = patch('charlesbot_rundeck.rundeck_lock.RundeckLock.seed_job_list') # NOQA self.addCleanup(patcher1.stop) self.mock_seed_job_list = patcher1.start() patcher2 = patch('charlesbot_rundeck.rundeck_lock.http_get_request') self.addCleanup(patcher2.stop) self.mock_http_get_request = patcher2.start() from charlesbot_rundeck.rundeck_lock import RundeckLock self.rd_lock = RundeckLock("token", "url", "channel", [])
def setUp(self): patcher1 = patch('charlesbot_rundeck.rundeck_lock.RundeckLock.seed_job_list') # NOQA self.addCleanup(patcher1.stop) self.mock_seed_job_list = patcher1.start() patcher2 = patch('charlesbot.slack.slack_connection.SlackConnection.api_call') # NOQA self.addCleanup(patcher2.stop) self.mock_api_call = patcher2.start() from charlesbot_rundeck.rundeck_lock import RundeckLock self.rd_lock = RundeckLock("token", "url", "channel", [])
def setUp(self): patcher1 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.load_config') # NOQA self.addCleanup(patcher1.stop) self.mock_load_config = patcher1.start() patcher2 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.print_service_list') # NOQA self.addCleanup(patcher2.stop) self.mock_print_service_list = patcher2.start() patcher3 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.trigger_escalation_incident') # NOQA self.addCleanup(patcher3.stop) self.mock_trigger_escalation_incident = patcher3.start() from charlesbot_pagerduty_escalations.pagerdutyescalations import PagerdutyEscalations # NOQA self.pd = PagerdutyEscalations()
async def test_call_luisai(self): opsdroid = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) message = Message("schedule meeting", "user", "default", mock_connector) config = {'name': 'luisai', 'appid': 'test', 'appkey': 'test', 'verbose': True} result = amock.Mock() result.json = amock.CoroutineMock() result.json.return_value = { "query": "schedule meeting", "topScoringIntent": { "intent": "Calendar.Add", "score": 0.900492251 }, "intents": [ { "intent": "Calendar.Add", "score": 0.900492251 } ], "entities": [] } with amock.patch('aiohttp.ClientSession.get') as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) await luisai.call_luisai(message, config) self.assertTrue(patched_request.called)
async def test_get_random_actor_paged(client, token): with mock.patch.object(TMDbClient, 'get_data') as _get_data, \ mock.patch('atmdb.client.random.randrange', return_value=15) as randrange: first_page = future_from({ 'page': 1, 'results': [{}] * 10, 'total_results': 20, 'total_pages': 2, }) second_page = future_from({ 'page': 2, 'results': ([{}] * 4) + [{'id': 1, 'name': 'Some Person'}, {}], 'total_results': 20, 'total_pages': 2, }) person = future_from({'biography': 'extra stuff'}) _get_data.side_effect = [first_page, second_page, person] result = await client.get_random_popular_person(1) assert result.name == 'Some Person' assert result.biography == 'extra stuff' _get_data.assert_has_calls([ mock.call('https://api.themoviedb.org/3/person/popular' '?page=1&api_key={}'.format(token)), mock.call('https://api.themoviedb.org/3/person/popular' '?page=2&api_key={}'.format(token)), mock.call('https://api.themoviedb.org/3/person/1' '?api_key={}'.format(token)), ])
def test_setup_discovery(self, samsung_mock, wol_mock): """Testing setup of platform with discovery.""" with mock.patch( 'homeassistant.components.media_player.samsungtv.socket'): add_entities = mock.Mock() setup_platform(self.hass, {}, add_entities, discovery_info=DISCOVERY_INFO)
def setUp(self): patcher1 = patch('charlesbot_hello_world.helloworld.HelloWorld.load_config') # NOQA self.addCleanup(patcher1.stop) self.mock_load_config = patcher1.start() from charlesbot_hello_world.helloworld import HelloWorld test_plug = HelloWorld() # NOQA
def setUp(self): patcher1 = patch('charlesbot.robot.Robot.initialize_robot') self.addCleanup(patcher1.stop) self.mock_initialize_robot = patcher1.start() from charlesbot.robot import Robot self.robot = Robot()
async def test_parse_message(self): response = { 'messages': [ { "_id": "ZbhuIO764jOIu", "rid": "Ipej45JSbfjt9", "msg": "hows it going", "ts": "2018-05-11T16:05:41.047Z", "u": { "_id": "ZbhuIO764jOIu", "username": "******", "name": "Fábio Rosado" }, "_updatedAt": "2018-05-11T16:05:41.489Z", "editedBy": None, "editedAt": None, "emoji": None, "avatar": None, "alias": None, "customFields": None, "attachments": None, "mentions": [], "channels": [] } ]} with OpsDroid() as opsdroid, \ amock.patch('opsdroid.core.OpsDroid.parse') as mocked_parse: await self.connector._parse_message(response) self.assertLogs('_LOGGER', 'debug') self.assertTrue(mocked_parse.called) self.assertEqual("2018-05-11T16:05:41.047Z", self.connector.latest_update)
def test_setup(self, samsung_mock, wol_mock): """Testing setup of platform.""" with mock.patch( 'homeassistant.components.media_player.samsungtv.socket'): add_entities = mock.Mock() setup_platform( self.hass, WORKING_CONFIG, add_entities)
async def test_call_sapcai(self): opsdroid = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) message = Message("Hello" "user", "default", mock_connector) config = {'name': 'recastai', 'access-token': 'test'} result = amock.Mock() result.json = amock.CoroutineMock() result.json.return_value = { 'results': { "uuid": "f482bddd-a9d7-41ae-aae3-6e64ad3f02dc", "source": "hello", "intents": [ { "slug": "greetings", "confidence": 0.99 } ], "act": "assert", "type": None, "sentiment": "vpositive", "entities": {}, "language": "en", "processing_language": "en", "version": "2.10.1", "timestamp": "2017-11-15T07:41:48.935990+00:00", "status": 200 } } with amock.patch('aiohttp.ClientSession.post') as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) await sapcai.call_sapcai(message, config) self.assertTrue(patched_request.called)
def setUp(self): patcher1 = patch('charlesbot_rundeck.rundeck_job.http_get_request') self.addCleanup(patcher1.stop) self.mock_http_get_request = patcher1.start() from charlesbot_rundeck.rundeck_job import RundeckJob self.rd_job = RundeckJob()
async def test_parse_message_channel(self): response = {'result': [{ "update_id": 427647860, "message": { "message_id": 12, "from": { "id": 649671308, "is_bot": False, "first_name": "A", "last_name": "User", "username": "******", "language_code": "en-GB" }, "chat": { "id": 649671308, "first_name": "A", "last_name": "User", "username": "******", "type": "channel" }, "date": 1538756863, "text": "Hello" } }]} with amock.patch('opsdroid.core.OpsDroid.parse'): await self.connector._parse_message(response) self.assertLogs('_LOGGER', 'debug')
async def test_reconnect(self): connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid()) connector.connect = amock.CoroutineMock() with amock.patch('asyncio.sleep') as mocked_sleep: await connector.reconnect(10) self.assertTrue(connector.connect.called) self.assertTrue(mocked_sleep.called)
def test_train_rasanlu(self): with OpsDroid() as opsdroid: opsdroid.eventloop = asyncio.new_event_loop() opsdroid.config["parsers"] = [{"name": "rasanlu"}] with amock.patch('opsdroid.parsers.rasanlu.train_rasanlu'): opsdroid.train_parsers({}) opsdroid.eventloop.close()
async def test_parse_edited_message(self): response = {'result': [{ 'update_id': 246644499, 'edited_message': { 'message_id': 150, 'from': { 'id': 245245245, 'is_bot': False, 'first_name': 'IOBreaker', 'language_code': 'en'}, 'chat': { 'id': 245245245, 'first_name': 'IOBreaker', 'type': 'private'}, 'date': 1551797346, 'edit_date': 1551797365, 'text': 'hello2'}}]} response_copy = list(response) mocked_status = amock.CoroutineMock() mocked_status.status = 200 with amock.patch('opsdroid.core.OpsDroid.parse') as mocked_parse, \ amock.patch.object(self.connector.session, 'post') \ as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(mocked_status) self.assertTrue(response['result'][0].get('edited_message')) await self.connector._parse_message(response)
async def test__get_existing_models(self): result = amock.Mock() result.status = 200 result.json = amock.CoroutineMock() result.json.return_value = { "available_projects": { "default": { "available_models": [ "fallback" ], "status": "ready" }, "opsdroid": { "available_models": [ "hello", "world" ], "status": "ready" } } } with amock.patch('aiohttp.ClientSession.get') as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) models = await rasanlu._get_existing_models( {"project": "opsdroid"}) self.assertEqual(models, ["hello", "world"])
async def test_parse_message_username(self): response = {'result': [{ "update_id": 427647860, "message": { "message_id": 12, "from": { "id": 649671308, "is_bot": False, "first_name": "A", "last_name": "User", "username": "******", "language_code": "en-GB" }, "chat": { "id": 649671308, "first_name": "A", "last_name": "User", "username": "******", "type": "private" }, "date": 1538756863, "text": "Hello" } }]} with amock.patch('opsdroid.core.OpsDroid.parse') as mocked_parse: await self.connector._parse_message(response) self.assertTrue(mocked_parse.called)
async def test__get_existing_models_exception(self): with amock.patch('aiohttp.ClientSession.get') as patched_request: patched_request.return_value = asyncio.Future() patched_request.side_effect = ClientOSError() models = await rasanlu._get_existing_models( {"project": "opsdroid"}) self.assertRaises(ClientOSError) self.assertEqual(models, [])
def setUp(self): configure_lang({}) self.connector = ConnectorTelegram({ 'name': 'telegram', 'token': 'bot:765test', 'whitelisted-users': ['user', 'test', 'AnUser'] }, opsdroid=OpsDroid()) with amock.patch('aiohttp.ClientSession') as mocked_session: self.connector.session = mocked_session
def test_setup_none(self, samsung_mock, wol_mock, mocked_warn): """Testing setup of platform with no data.""" with mock.patch( 'homeassistant.components.media_player.samsungtv.socket'): add_entities = mock.Mock() setup_platform(self.hass, {}, add_entities, discovery_info=None) mocked_warn.assert_called_once_with("Cannot determine device") add_entities.assert_not_called()
def setUp(self): patcher1 = patch('charlesbot.slack.slack_connection.SlackConnection.api_call') # NOQA self.addCleanup(patcher1.stop) self.mock_api_call = patcher1.start() from charlesbot.slack.slack_connection import SlackConnection self.slack_connection = SlackConnection() from charlesbot.slack.slack_user import SlackUser self.su = SlackUser()
async def test__get_existing_models_fails(self): result = amock.Mock() result.status = 404 result.json = amock.CoroutineMock() result.json.return_value = {} with amock.patch('aiohttp.ClientSession.get') as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) models = await rasanlu._get_existing_models({}) self.assertEqual(models, [])
def setUp(self): patcher1 = patch('charlesbot_rundeck.rundeck.Rundeck.load_config') self.addCleanup(patcher1.stop) self.mock_load_config = patcher1.start() from charlesbot_rundeck.rundeck import Rundeck self.rd = Rundeck() self.rd.rundeck_lock = MagicMock() self.rd.rundeck_lock.toggle_rundeck_lock = CoroutineMock() self.rd.rundeck_lock.print_lock_status = CoroutineMock()
async def test_get_data_other_error(client): with mock.patch('atmdb.client.aiohttp.ClientSession', SimpleSessionMock) as session: session.configure_mock(side_effect=[ dict(code=HTTPStatus.NOT_FOUND, body=dict(status_message='testing error handling')), ]) data = await client.get_data('dummy_url') assert data is None assert len(session.call_args_list) == 1 session.assert_called_with('dummy_url', headers=client.headers)
def setUp(self): patcher1 = patch('charlesbot.robot.Robot.initialize_robot') self.addCleanup(patcher1.stop) self.mock_initialize_robot = patcher1.start() patcher2 = patch('charlesbot.robot.Robot.is_running') self.addCleanup(patcher2.stop) self.mock_is_running = patcher2.start() self.mock_slack = MagicMock() self.mock_slack.get_stream_messages = CoroutineMock() patcher3 = patch('charlesbot.robot.Robot.queue_message') self.addCleanup(patcher3.stop) self.mock_queue_message = patcher3.start() from charlesbot.robot import Robot self.robot = Robot() self.robot.slack = self.mock_slack self.mock_is_running.side_effect = [True, False] # single iteration
async def test_parse_message_emoji(self): response = { "result": [ { "update_id": 427647860, "message": { "message_id": 12, "from": { "id": 649671308, "is_bot": False, "first_name": "A", "last_name": "User", "username": "******", "language_code": "en-GB", }, "chat": { "id": 649671308, "first_name": "A", "last_name": "User", "username": "******", "type": "private", }, "date": 1538756863, "sticker": { "width": 512, "height": 512, "emoji": "😔", "set_name": "YourALF", "thumb": { "file_id": "AAQCABODB_MOAARYC8yRaPPoIIZBAAIC", "file_size": 8582, "width": 128, "height": 128, }, "file_id": "CAADAgAD3QMAAsSraAu37DAtdiNpAgI", "file_size": 64720, }, }, } ] } with amock.patch("opsdroid.core.OpsDroid.parse"): await self.connector._parse_message(response) self.assertLogs("_LOGGER", "debug")
async def test__is_model_loaded(self): result = amock.Mock() result.status = 200 result.json = amock.CoroutineMock() with amock.patch("aiohttp.ClientSession.get") as patched_request: result.json.return_value = { "fingerprint": { "config": ["7625d69d93053ac8520a544d0852c626"], "domain": ["229b51e41876bbcbbbfbeddf79548d5a"], "messages": ["cf7eda7edcae128a75ee8c95d3bbd680"], "stories": ["b5facea681fd00bc7ecc6818c70d9639"], "trained_at": 1556527123.42784, "version": "2.6.2", }, "model_file": "/app/models/model.tar.gz", "num_active_training_jobs": 2, } patched_request.side_effect = None patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) self.assertEqual( await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}), True) self.assertEqual( await rasanlu._is_model_loaded({ "model_filename": "model.tar.gz", "token": "12345" }), True, ) result.status = 500 self.assertEqual( await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}), False, ) patched_request.side_effect = ( aiohttp.client_exceptions.ClientConnectorError( "key", amock.Mock())) self.assertEqual( await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}), None)
async def test_call_rasanlu(self): opsdroid = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) message = Message("how's the weather outside", "user", "default", mock_connector) config = { "name": "rasanlu", "access-token": "test", "min-score": 0.3, "token": "12345", } result = amock.Mock() result.status = 200 result.json = amock.CoroutineMock() result.json.return_value = { "entities": [{ "end": 32, "entity": "state", "extractor": "ner_crf", "confidence": 0.854, "start": 25, "value": "running", }], "intent": { "confidence": 0.5745766766665303, "name": "get_weather" }, "intent_ranking": [ { "confidence": 0.5745766766665303, "name": "get_weather" }, { "confidence": 0.42542332333346977, "name": "other_weather" }, ], "text": "how's the weather outside", } with amock.patch("aiohttp.ClientSession.post") as patched_request: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(result) await rasanlu.call_rasanlu(message.text, config) self.assertTrue(patched_request.called)
async def test_get_message(self): self.connector.group = "test" response = amock.Mock() response.status = 200 response.json = amock.CoroutineMock() response.return_value = { "messages": [{ "_id": "ZbhuIO764jOIu", "rid": "Ipej45JSbfjt9", "msg": "hows it going", "ts": "2018-05-11T16:05:41.047Z", "u": { "_id": "ZbhuIO764jOIu", "username": "******", "name": "Fábio Rosado", }, "_updatedAt": "2018-05-11T16:05:41.489Z", "editedBy": None, "editedAt": None, "emoji": None, "avatar": None, "alias": None, "customFields": None, "attachments": None, "mentions": [], "channels": [], }] } with OpsDroid() as opsdroid, amock.patch.object( self.connector.session, "get") as patched_request, amock.patch.object( self.connector, "_parse_message") as mocked_parse_message, amock.patch( "asyncio.sleep") as mocked_sleep: patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(response) await self.connector._get_message() self.assertTrue(patched_request.called) self.assertTrue(mocked_parse_message.called) self.assertTrue(mocked_sleep.called) self.assertLogs("_LOGGER", "debug")
async def test_parse_watson(self): with OpsDroid() as opsdroid: opsdroid.modules = { "parsers": [{ "config": { "name": "watson", "enabled": True } }] } watson_intent = "" skill = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) match_watson(watson_intent)(skill) message = Message("Hello world", "user", "default", mock_connector) with amock.patch("opsdroid.parsers.watson.parse_watson"): tasks = await opsdroid.parse(message) self.assertEqual(len(tasks), 3)
async def test_respond(opsdroid): opsdroid = amock.CoroutineMock() connector = ConnectorGitHub({"name": "github", "token": "test"}, opsdroid=opsdroid) with amock.patch("aiohttp.ClientSession.post") as patched_request: mockresponse = amock.CoroutineMock() mockresponse.status = 201 patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(mockresponse) resp = await connector.send( Message( text="test", user="******", target="opsdroid/opsdroid#1", connector=connector, ) ) assert patched_request.called assert resp
async def test_can_call_handler_without_annotation(self): """ For backward compatiilty, wew can call a handler that receives one parameter and does not have any type annotations """ @self.app.http.get(["/"]) async def handler(): return web.json_response({"OK": True}) async with HttpClientContext(self.app) as client: settings_mock = Settings() with mock.patch( "asyncworker.signals.handlers.http.settings", settings_mock ): resp = await client.get("/") self.assertEqual(200, resp.status) self.assertEqual({"OK": True}, await resp.json())
async def test_print_invite(self): builder: ContextBuilder = StubContextBuilder(self.test_settings) builder.update_settings({ "debug.print_invitation": True, "invite_base_url": "http://localhost" }) conductor = test_module.Conductor(builder) with async_mock.patch("sys.stdout", new=StringIO()) as captured: await conductor.setup() wallet = await conductor.context.inject(BaseWallet) await wallet.create_public_did() await conductor.start() await conductor.stop() value = captured.getvalue() assert "http://localhost?c_i=" in captured.getvalue()
async def test_parse_witai(self): with OpsDroid() as opsdroid: opsdroid.config["parsers"] = {"witai": {"enabled": True}} witai_intent = "" skill = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) match_witai(witai_intent)(skill) message = Message( text="Hello world", user="******", target="default", connector=mock_connector, ) with amock.patch("opsdroid.parsers.witai.parse_witai"): tasks = await opsdroid.parse(message) self.assertEqual(len(tasks), 1) for task in tasks: await task
def test_cursor_field(query): with mock.patch("mongodb_streams.find") as m: xs = [dict(surname=i) for i in iter(LETTERS)] m.return_value = xs r = query(""" { UserNodes(cursorField: surname) { nodes { surname } } } """) pretty(r) print(m.call_args) nodes = r["data"]["UserNodes"]["nodes"] assert len(nodes) == len(LETTERS) assert sorted(nodes, key=lambda x: x["surname"]) == nodes
async def test_respond(self): post_response = amock.Mock() post_response.status = 200 with OpsDroid() as opsdroid, \ amock.patch('aiohttp.ClientSession.post') as patched_request: self.assertTrue(opsdroid.__class__.instances) test_message = Message(text="This is a test", user="******", room="test", connector=self.connector) patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(post_response) await test_message.respond("Response") self.assertTrue(patched_request.called) self.assertLogs('_LOGGER', 'debug')
async def test_alertnotify_invalid_func_with_error_raise_and_notify(self): class IncorrectFakePoller(FakePoller): @alertnotify(exceptions=(RuntimeError, )) async def invalid_func(self): raise RuntimeError('Incorrect') poller = IncorrectFakePoller(alertnotify='echo "%s"') assert poller.has_alertnotify is True with patch('asyncio.create_subprocess_exec') as sp_mock: process_mock = CoroutineMock() attrs = {'communicate.return_value': ('output', 'error')} process_mock.configure_mock(**attrs) sp_mock.return_value = process_mock await poller.invalid_func() assert sp_mock.call_count == 1 assert process_mock.communicate.call_count == 1
async def test_typing_sleep(self): with OpsDroid() as opsdroid: mock_connector = Connector( { "name": "shell", "typing-delay": 6, "type": "connector", "module_path": "opsdroid-modules.connector.shell", }, opsdroid=opsdroid, ) with amock.patch("asyncio.sleep") as mocksleep: message = events.Message("hi", "user_id", "user", "default", mock_connector) with self.assertRaises(TypeError): await message.respond("Hello there") self.assertTrue(mocksleep.called)
async def test_switch_connection_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test error handling of the WLED switches.""" aioclient_mock.post("http://example.local:80/json/state", exc=aiohttp.ClientError) await init_integration(hass, aioclient_mock) with patch("homeassistant.components.wled.WLEDDataUpdateCoordinator.async_refresh"): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.wled_rgb_light_nightlight"}, blocking=True, ) await hass.async_block_till_done() state = hass.states.get("switch.wled_rgb_light_nightlight") assert state.state == STATE_UNAVAILABLE
async def test_ping_websocket(self): """Test pinging the websocket.""" import websockets connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid()) with amock.patch('asyncio.sleep', new=amock.CoroutineMock()) \ as mocked_sleep: connector.websocket = amock.CoroutineMock() connector.websocket.send = amock.CoroutineMock() await connector.ping_websocket() self.assertTrue(mocked_sleep.called) self.assertTrue(connector.websocket.send.called) connector.reconnect = amock.CoroutineMock() connector.websocket.send.side_effect = \ websockets.exceptions.ConnectionClosed(500, "Mock Error") await connector.ping_websocket() self.assertTrue(connector.reconnect.called)
async def test_webhook_failure(opsdroid, caplog): connector = ConnectorTwitch(connector_config, opsdroid=opsdroid) caplog.set_level(logging.DEBUG) post_response = amock.Mock() post_response.status = 500 post_response.json = amock.CoroutineMock() with amock.patch("aiohttp.ClientSession.post", new=amock.CoroutineMock()) as mocked_session: mocked_session.return_value = asyncio.Future() mocked_session.return_value.set_result(post_response) await connector.webhook("subscribers", "subscribe") assert "Error:" in caplog.text
async def test_connect(self): connector = ConnectorWebexTeams({"access-token": "abc123"}, opsdroid=OpsDroid()) opsdroid = amock.CoroutineMock() opsdroid.eventloop = self.loop connector.clean_up_webhooks = amock.CoroutineMock() connector.subscribe_to_rooms = amock.CoroutineMock() connector.set_own_id = amock.CoroutineMock() with amock.patch( "websockets.connect", new=amock.CoroutineMock()) as mocked_websocket_connect: await connector.connect() self.assertTrue(connector.clean_up_webhooks.called) self.assertTrue(connector.subscribe_to_rooms.called) self.assertTrue(connector.set_own_id.called)
def test_many_users(query): with mock.patch("mongodb_streams.find") as m: m.side_effect = [[dict(surname="xxx")], [dict(surname="xxx")]] r = query(""" { UserNodes(where: { surname: { eq: "xxx" } }) { nodes { surname } } } """) pretty(r) pretty(m.call_args_list) nodes = r["data"]["UserNodes"]["nodes"] assert len(nodes) == 1 assert nodes[0]["surname"] == "xxx"
async def test_respond(opsdroid): """Test that responding sends a message.""" post_response = amock.Mock() post_response.status = 200 with amock.patch("aiohttp.ClientSession.post", new=amock.CoroutineMock()) as patched_request: assert opsdroid.__class__.instances connector = ConnectorFacebook({}, opsdroid=opsdroid) room = "a146f52c-548a-11e8-a7d1-28cfe949e12d" test_message = Message(text="Hello world", user="******", target=room, connector=connector) patched_request.return_value = asyncio.Future() patched_request.return_value.set_result(post_response) await test_message.respond("Response") assert patched_request.called
async def test_thinking_delay(self): with OpsDroid() as opsdroid: mock_connector = Connector( { "name": "shell", "thinking-delay": 3, "type": "connector", "module_path": "opsdroid-modules.connector.shell", }, opsdroid=opsdroid, ) with amock.patch("opsdroid.events.Message._thinking_delay") as logmock: message = events.Message("hi", "user", "default", mock_connector) with self.assertRaises(TypeError): await message.respond("Hello there") self.assertTrue(logmock.called)
async def test_thinking_delay(self): opsdroid = amock.CoroutineMock() mock_connector = Connector( { 'name': 'shell', 'thinking-delay': 3, 'type': 'connector', 'module_path': 'opsdroid-modules.connector.shell' }, opsdroid=opsdroid) with amock.patch( 'opsdroid.message.Message._thinking_delay') as logmock: message = Message("hi", "user", "default", mock_connector) with self.assertRaises(NotImplementedError): await message.respond("Hello there") self.assertTrue(logmock.called)
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 controller_fixture( players, favorites, input_sources, playlists, change_data, dispatcher): """Create a mock Heos controller fixture.""" with patch("pyheos.Heos", autospec=True) as mock: mock_heos = mock.return_value for player in players.values(): player.heos = mock_heos mock_heos.dispatcher = dispatcher mock_heos.get_players.return_value = players mock_heos.players = players mock_heos.get_favorites.return_value = favorites mock_heos.get_input_sources.return_value = input_sources mock_heos.get_playlists.return_value = playlists mock_heos.load_players.return_value = change_data mock_heos.is_signed_in = True mock_heos.signed_in_username = "******" mock_heos.connection_state = const.STATE_CONNECTED yield mock_heos
async def test_setup(hass, remote): """Test Samsung TV integration is setup.""" with patch("homeassistant.components.samsungtv.bridge.Remote") as remote: await async_setup_component(hass, SAMSUNGTV_DOMAIN, MOCK_CONFIG) await hass.async_block_till_done() state = hass.states.get(ENTITY_ID) # test name and turn_on assert state assert state.name == "fake_name" assert (state.attributes[ATTR_SUPPORTED_FEATURES] == SUPPORT_SAMSUNGTV | SUPPORT_TURN_ON) # test host and port assert await hass.services.async_call(DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True) assert remote.call_args == call(REMOTE_CALL)
async def test_parse_luisai(self): with OpsDroid() as opsdroid: opsdroid.modules = { "parsers": [{"config": {"name": "luisai", "enabled": True}}] } luisai_intent = "" skill = amock.CoroutineMock() mock_connector = Connector({}, opsdroid=opsdroid) match_luisai_intent(luisai_intent)(skill) message = Message( text="Hello world", user="******", target="default", connector=mock_connector, ) with amock.patch("opsdroid.parsers.luisai.parse_luisai"): tasks = await opsdroid.parse(message) self.assertEqual(len(tasks), 3)
async def test_send_reply_id(self): reply = events.Reply("reply", linked_event="$hello", target="!hello:localhost") with OpsDroid() as _: with amock.patch(api_string.format("send_message_event")) as patched_send: patched_send.return_value = asyncio.Future() patched_send.return_value.set_result(None) await self.connector.send(reply) content = self.connector._get_formatted_message_body( reply.text, msgtype="m.text" ) content["m.relates_to"] = {"m.in_reply_to": {"event_id": "$hello"}} assert patched_send.called_once_with( "!test:localhost", "m.room.message", content )
async def test_simple_handler_200_response(self): """ Tests if a response is correctly handled, Starts a real aiohttp server """ @self.app.http.get(["/"]) async def index(): return web.json_response({"OK": True}) async with HttpClientContext(self.app) as client: settings_mock = Settings() with mock.patch( "asyncworker.signals.handlers.http.settings", settings_mock ): resp = await client.get("/") self.assertEqual(resp.status, 200) data = await resp.json() self.assertDictEqual({"OK": True}, data)
async def test_deploy_white_list(self): with mock.patch('tag_resolver_proxy.resolve_tags.docker_io.DockerIOTagResolver.resolve_tags') as resolve_tags, \ mock.patch.object(self._app['client'], 'post') as upstream_post: resolve_tags.return_value = \ 'docker.io/test/curl@sha256:8bb9ec6e86c87e436402a2952eba54ed636754ba61ddf84d1b6e4844396383c9' deployment = self._deployment('white_list') status, response = await self._admission_request(**deployment) self.assertEqual(200, status) self._assert_admission_response_equal( True, 'All images whitelisted', response, ) self.assertFalse(resolve_tags.called) self.assertFalse(upstream_post.called)
async def test_ledger_config_genesis_file_non_indy_wallet(self): settings = { "ledger.genesis_file": "/tmp/genesis/path", "default_endpoint": "http://1.2.3.4:8051", } mock_ledger = async_mock.MagicMock( type="indy", get_txn_author_agreement=async_mock.CoroutineMock( return_value={ "taa_required": True, "taa_record": { "digest": b"ffffffffffffffffffffffffffffffffffffffff" }, } ), get_latest_txn_author_acceptance=async_mock.CoroutineMock( return_value={"digest": b"1234567890123456789012345678901234567890"} ), ) mock_wallet = async_mock.MagicMock( type="trifold", set_did_endpoint=async_mock.CoroutineMock() ) context = InjectionContext(settings=settings, enforce_typing=False) context.injector.bind_instance(BaseLedger, mock_ledger) context.injector.bind_instance(BaseWallet, mock_wallet) with async_mock.patch.object( test_module, "accept_taa", async_mock.CoroutineMock() ) as mock_accept_taa, async_mock.patch( "builtins.open", async_mock.MagicMock() ) as mock_open: mock_open.return_value = async_mock.MagicMock( __enter__=async_mock.MagicMock( return_value=async_mock.MagicMock( read=async_mock.MagicMock( return_value="... genesis transactions ..." ) ) ) ) mock_accept_taa.return_value = True with self.assertRaises(test_module.ConfigError): await test_module.ledger_config(context, TEST_DID, provision=True)
async def test_get_wallet_profile_settings(self): extra_settings = {"extra_settings": "extra_settings"} all_wallet_record_settings = [ { "wallet_record_settings": "wallet_record_settings", "wallet.dispatch_type": "default", }, { "wallet_record_settings": "wallet_record_settings", "wallet.dispatch_type": "default", "wallet.webhook_urls": ["https://localhost:8090"], }, { "wallet_record_settings": "wallet_record_settings", "wallet.dispatch_type": "both", }, { "wallet_record_settings": "wallet_record_settings", "wallet.dispatch_type": "both", "wallet.webhook_urls": ["https://localhost:8090"], }, ] def side_effect(context, provision): return (InMemoryProfile(context=context), None) for idx, wallet_record_settings in enumerate( all_wallet_record_settings): wallet_record = WalletRecord( wallet_id=f"test.{idx}", settings=wallet_record_settings, ) with async_mock.patch( "aries_cloudagent.multitenant.manager.wallet_config" ) as wallet_config: wallet_config.side_effect = side_effect profile = await self.manager.get_wallet_profile( self.profile.context, wallet_record, extra_settings) assert (profile.settings.get("wallet_record_settings") == "wallet_record_settings") assert profile.settings.get( "extra_settings") == "extra_settings"