async def test_check_local_changes(self):
        path = "/tmp/test.txt"
        mocked_stat = asynctest.MagicMock(spec="os.stat")
        mocked_stat.st_mtime = 1479129162
        mocked_stat.st_mode = 33024
        with asynctest.patch("os.stat") as patched:
            patched.return_value = mocked_stat
            res = await self.control._check_local_changes(path)
            assert res is True

            # raise exception
            patched.side_effect = Exception("Test-Error")
            res = await self.control._check_local_changes(path)
            assert res is False
Beispiel #2
0
    def setUp(self):
        self.geoip = GeoIP()

        self.mock_response = asynctest.MagicMock()
        self.mock_response.content.read = asynctest.CoroutineMock()
        self.mock_get = asynctest.patch('aiohttp.ClientSession.get').start()
        self.mock_get.return_value.__aenter__.return_value = self.mock_response

        self.mock_exists = mock.patch('os.path.exists').start()
        self.mock_getmtime = mock.patch('os.path.getmtime').start()
        self.mock_time = mock.patch('time.time').start()

        self.mock_maybe_replace_db = mock.patch(
            __name__ + '.GeoIP._maybe_replace_db').start()
Beispiel #3
0
async def test_bot_run_event(dummy_bot, returns):
    func = am.CoroutineMock()
    func.side_effect = returns
    func.__name__ = 'func'
    event = Event()
    dummy_bot.forever_loop = am.MagicMock()
    dummy_bot.handle_bot_exception = am.CoroutineMock()

    await dummy_bot.run_event(func, event)

    if isinstance(returns, Abort):
        dummy_bot.forever_loop.set_exception.assert_called_once_with(returns)
    elif isinstance(returns, Exception):
        dummy_bot.handle_bot_exception.assert_awaited_once_with(
            func, event, returns)
Beispiel #4
0
    async def test_outstanding_request_timedout(self):
        cur_header_height = 1
        node_id = 123

        # mock node manager state
        self.syncmgr.nodemgr = asynctest.MagicMock()
        node1 = NeoNode(object(), object())
        node1.nodeid = node_id
        self.syncmgr.nodemgr.get_node_by_id.return_value = node1

        node2 = asynctest.MagicMock()  # NeoNode(object(), object())
        node2.nodeid.return_value = 456
        node2.get_headers = asynctest.CoroutineMock()
        self.syncmgr.nodemgr.get_node_with_min_failed_time.return_value = node2
        self.syncmgr.nodemgr.add_node_timeout_count = asynctest.CoroutineMock()

        # mock ledger state
        self.syncmgr.ledger = asynctest.MagicMock()
        # we pretend our local ledger has a height higher than what we just asked for
        self.syncmgr.ledger.cur_header_height = asynctest.CoroutineMock(
            return_value=1)
        self.syncmgr.ledger.header_hash_by_height = asynctest.CoroutineMock(
            return_value=b'')
        # ------

        # setup sync manager state to have an outstanding header request
        self.syncmgr.header_request = RequestInfo(cur_header_height + 1)
        fi = FlightInfo(node_id, cur_header_height + 1)
        fi.start_time = fi.start_time - 5  # decrease start time by 5 seconds to exceed timeout threshold
        self.syncmgr.header_request.add_new_flight(fi)

        with self.assertLogHandler('syncmanager', DEBUG) as log_context:
            await self.syncmgr.check_timeout()
            self.assertGreater(len(log_context.output), 0)
            self.assertTrue("Retry requesting headers starting at 2" in
                            log_context.output[-1])
Beispiel #5
0
def mock_ClientSession(**fake_session_kwargs):
    fake_session = asynctest.MagicMock(name="session", **fake_session_kwargs)

    class FakeClientSession:
        def __init__(self, *args, **kwargs):
            ...

        async def __aenter__(*args):
            return fake_session

        async def __aexit__(*args):
            pass

    with mock.patch("aiohttp.ClientSession", new=FakeClientSession, autospec=False):
        yield
    def __init__(self,
                 *args,
                 target_mock: asynctest.MagicMock = None,
                 **kwargs):
        """

        :param args:
        :param target_mock asynctest.MagicMock: Pass a mock here if you want to assert against it later
        :param kwargs:
        """
        if target_mock:
            self._session = target_mock
        else:
            self._session = asynctest.MagicMock(
                name='transactional_session_mock')
Beispiel #7
0
 async def test_login_ok(self):
     api_res = {"token": "foo"}
     self.client._session = asynctest.MagicMock(
         close=asynctest.CoroutineMock(return_value=None))
     self.client._post = asynctest.CoroutineMock(return_value=api_res)
     res = await self.client._login()
     assert res == api_res["token"]
     assert self.client._post.call_args_list[0][0][
         0] == 'https://example.com/api/auth'
     assert json.loads(self.client._post.call_args_list[0][0][1]) == {
         'password': '******',
         'username': '******'
     }
     assert self.client._post.call_args_list[0][1]["status"] == 201
     assert self.client._session == None
 async def test_new_sqs_client(self):
     self.control._sqs_client = None
     self.control._purge_sqs_queue = asynctest.CoroutineMock(return_value=True)
     mock_sqs_client = asynctest.MagicMock()
     mock_session = unittest.mock.MagicMock()
     mock_session.create_client = unittest.mock.MagicMock(return_value=mock_sqs_client)
     with asynctest.patch("aiobotocore.get_session") as patched:
         patched.return_value = mock_session
         client = await self.control.sqs_client
         assert mock_session.create_client.call_count == 1
         assert mock_session.create_client.call_args[0] == ("sqs",)
         assert mock_session.create_client.call_args[1]["region_name"] == "eu-central-1"
         assert client == mock_sqs_client
         assert client == self.control._sqs_client
         assert self.control._purge_sqs_queue.call_count == 1
Beispiel #9
0
    def test_dont_send_test_message_if_not_established(self):
        message = TestMessage()
        mock_queue = Queue()

        async def send_message(message: IPRPCMessage):
            mock_queue.put(message)

        self.channel._send_message = send_message
        tx_input = self.channel.tx_input
        self.channel.ipfs = asynctest.MagicMock()
        self.channel.start()
        tx_input.send(message)
        mock_queue.get()  # Hit the queue once to clear the PeeringHello
        with self.assertRaises(Empty):
            mock_queue.get(timeout=1)
        self.channel.terminate()
Beispiel #10
0
 async def test_is_draining_no(self):
     fake_response = mock.Mock(
         status=200,
         text=asynctest.CoroutineMock(
             return_value="",
         ),
     )
     fake_task = mock.Mock(host="fake_host", ports=[54321])
     with mock_ClientSession(
         get=mock.Mock(
             return_value=asynctest.MagicMock(
                 __aenter__=asynctest.CoroutineMock(return_value=fake_response),
             ),
         ),
     ):
         assert await self.drain_method.is_draining(fake_task) is False
Beispiel #11
0
 async def test_queue_consumer(self):
     task = {
         "target": asynctest.MagicMock(),
         "post": asynctest.CoroutineMock(return_value=True),
         "count": 0
     }
     self.bridge.queue.get = asynctest.CoroutineMock(
         side_effect=[task, Exception("Test")])
     self.bridge.queue.task_done = asynctest.CoroutineMock(
         return_value=True)
     self.bridge._process_action = asynctest.CoroutineMock(
         return_value=None)
     await self.bridge._queue_consumer()
     self.bridge.queue.get.call_count == 2
     self.bridge._process_action.call_count == 1
     self.bridge.queue.task_done.call_count == 1
Beispiel #12
0
async def test_check_zigpy_connection():
    """Test config flow validator."""

    mock_radio = asynctest.MagicMock()
    mock_radio.connect = asynctest.CoroutineMock()
    radio_cls = asynctest.MagicMock(return_value=mock_radio)

    bad_radio = asynctest.MagicMock()
    bad_radio.connect = asynctest.CoroutineMock(side_effect=Exception)
    bad_radio_cls = asynctest.MagicMock(return_value=bad_radio)

    mock_ctrl = asynctest.MagicMock()
    mock_ctrl.startup = asynctest.CoroutineMock()
    mock_ctrl.shutdown = asynctest.CoroutineMock()
    ctrl_cls = asynctest.MagicMock(return_value=mock_ctrl)
    new_radios = {
        mock.sentinel.radio: {
            ZHA_GW_RADIO: radio_cls,
            CONTROLLER: ctrl_cls
        },
        mock.sentinel.bad_radio: {
            ZHA_GW_RADIO: bad_radio_cls,
            CONTROLLER: ctrl_cls
        },
    }

    with mock.patch.dict(
            openpeerpower.components.zha.core.registries.RADIO_TYPES,
            new_radios,
            clear=True):
        assert not await config_flow.check_zigpy_connection(
            mock.sentinel.usb_path, mock.sentinel.unk_radio,
            mock.sentinel.zigbee_db)
        assert mock_radio.connect.call_count == 0
        assert bad_radio.connect.call_count == 0
        assert mock_ctrl.startup.call_count == 0
        assert mock_ctrl.shutdown.call_count == 0

        # unsuccessful radio connect
        assert not await config_flow.check_zigpy_connection(
            mock.sentinel.usb_path, mock.sentinel.bad_radio,
            mock.sentinel.zigbee_db)
        assert mock_radio.connect.call_count == 0
        assert bad_radio.connect.call_count == 1
        assert mock_ctrl.startup.call_count == 0
        assert mock_ctrl.shutdown.call_count == 0

        # successful radio connect
        assert await config_flow.check_zigpy_connection(
            mock.sentinel.usb_path, mock.sentinel.radio,
            mock.sentinel.zigbee_db)
        assert mock_radio.connect.call_count == 1
        assert bad_radio.connect.call_count == 1
        assert mock_ctrl.startup.call_count == 1
        assert mock_ctrl.shutdown.call_count == 1
Beispiel #13
0
    async def test_put_to_queue(self):
        with asynctest.patch("asyncio.ensure_future") as mocked_ensure:
            mocked_ensure.return_value = "test"
            self.bridge._queue_consumer = asynctest.CoroutineMock(
                return_value="test")
            self.bridge.queue = asynctest.MagicMock()
            self.bridge.queue.put = asynctest.CoroutineMock(return_value=None)
            await self.bridge._put_to_queue({"foo": "baz"})
            assert self.bridge._queue_consumer.call_count == 1
            assert self.bridge.queue.put.call_count == 1
            assert self.bridge.queue_task == "test"

            await self.bridge._put_to_queue({"foo": "baz"})
            assert self.bridge._queue_consumer.call_count == 1
            assert self.bridge.queue.put.call_count == 2
            assert self.bridge.queue_task == "test"
Beispiel #14
0
    async def test_connect_to_exceptions(self):
        loop = asynctest.MagicMock()

        loop.create_connection.side_effect = asyncio.TimeoutError
        node_instance, failure = await node.NeoNode.connect_to(socket=object(), loop=loop)
        self.assertIsNone(node_instance)
        self.assertEqual("Timed out", failure[1])

        loop.create_connection.side_effect = OSError("unreachable")
        node_instance, failure = await node.NeoNode.connect_to(socket=object(), loop=loop)
        self.assertIsNone(node_instance)
        self.assertEqual("Failed to connect for reason unreachable", failure[1])

        loop.create_connection.side_effect = asyncio.CancelledError
        node_instance, failure = await node.NeoNode.connect_to(socket=object(), loop=loop)
        self.assertIsNone(node_instance)
        self.assertEqual("Cancelled", failure[1])
Beispiel #15
0
 async def test_get_post(self):
     item = {
         "_id":
         ObjectId(b"012345678901"),
         "updated":
         datetime.strptime("2016-10-19T10:13:43+00:00",
                           "%Y-%m-%dT%H:%M:%S+00:00"),
         "target_doc": {
             "target": "doc"
         }
     }
     coll = asynctest.MagicMock(spec=AsyncIOMotorCollection)
     coll.find_one = asynctest.CoroutineMock(return_value=item)
     self.client._db = {self.table_name: coll}
     res = await self.client.get_post("target", "post")
     assert res["target_doc"] == {'target': 'doc'}
     assert res["updated"] == item["updated"]
Beispiel #16
0
    async def test_get_last_updated(self):
        source = BaseSource()
        source._db_client = asynctest.MagicMock()
        tstamp = datetime.utcnow()
        source._db_client.get_last_updated = asynctest.CoroutineMock(
            return_value=tstamp)
        last_updated = await source.get_last_updated("foo")
        assert last_updated == tstamp
        assert source._db_client.get_last_updated.call_count == 1
        assert source._db_client.get_last_updated.call_args == asynctest.call(
            "foo")

        # no data from storage
        source._db_client.get_last_updated = asynctest.CoroutineMock(
            return_value=None)
        last_updated = await source.get_last_updated("foo")
        assert last_updated is None
Beispiel #17
0
 async def test_is_draining_yes(self):
     fake_response = mock.Mock(
         status=503,
         text=asynctest.CoroutineMock(
             return_value="Service service in down state since 1435694078.778886 "
                          "until 1435694178.780000: Drained by Paasta",
         ),
     )
     fake_task = mock.Mock(host="fake_host", ports=[54321])
     with mock_ClientSession(
         get=mock.Mock(
             return_value=asynctest.MagicMock(
                 __aenter__=asynctest.CoroutineMock(return_value=fake_response),
             ),
         ),
     ):
         assert await self.drain_method.is_draining(fake_task) is True
Beispiel #18
0
    def test_reply(self, patched_reply, patched_learn, patched_user,
                   patched_normalize):
        msg = asynctest.MagicMock()
        msg.content.return_value = "<@221134985560588289> you should play dota!"
        msg.content.split.return_value = [
            "<@!221134985560588289>", "you", "should", "play", "dota!"
        ]
        msg.channel.return_value = "maketotaldestroy"
        msg.author.mention.return_value = "<@42303631157544375>"
        msg.channel.send = asynctest.CoroutineMock()
        patched_user.return_value.id = "221134985560588289"
        patched_reply.return_value = "I should play dota!"
        patched_reply.replace.return_value = "I should play dota!"

        self.loop.run_until_complete(self.our_pybd.on_message(msg))
        patched_learn.assert_called_once_with(patched_normalize.return_value)
        patched_reply.assert_called_once_with(patched_normalize.return_value)
Beispiel #19
0
    def resp_maker(*args, **kwargs):
        actual_response = asynctest.MagicMock(*args, **kwargs)
        async def resp_mock_effect(request):
            nonlocal actual_response

            # The request's content can be read inside of the handler only. We preserve
            # the data into a conventional field, so that they could be asserted later.
            try:
                request.data = await request.json()
            except json.JSONDecodeError:
                request.data = await request.text()

            # Get a response/error as it was intended (via return_value/side_effect).
            response = actual_response()
            return response

        return asynctest.CoroutineMock(side_effect=resp_mock_effect)
Beispiel #20
0
    async def test_handle_unstick_item(self):
        post = asynctest.MagicMock()
        post.is_known = True
        post.target_doc = {"Id": "12345"}
        post.is_sticky = False
        post.get_existing = lambda: {"sticky": "1"}
        self.client._unstick_item = asynctest.CoroutineMock(
            return_value={"foo": "baz"})
        self.client._stick_item = asynctest.CoroutineMock(
            side_effect=Exception)
        res = await self.client._handle_sticky(post)
        assert res == {"foo": "baz"}
        self.client._unstick_item.assert_called_once_with("12345")
        assert self.client._stick_item.call_count == 0

        post.get_existing = lambda: {"sticky": "0"}
        res = await self.client._handle_sticky(post)
        assert res == None
Beispiel #21
0
    async def test_run_emits_a_task_i_done_event_for_each_valid_clock_tick(
        self
    ):
        clock = asynctest.MagicMock()
        clock.__aiter__.return_value = range(3)
        wrapped_task = Mock()
        with patch.multiple(
            self.task_runner,
            clock=clock,
            _wrapped_task=wrapped_task,
            task_is_done_event=Mock(),
            can_dispatch_task=CoroutineMock(side_effect=[True, False, True]),
        ), patch("asyncworker.task_runners.asyncio.ensure_future"):
            await self.task_runner._run()

            self.task_runner.task_is_done_event.clear.assert_has_calls(
                [call(), call()]
            )
Beispiel #22
0
    async def test_filter_new_posts(self):
        source = BaseSource()
        source._db_client = asynctest.MagicMock()
        source._db_client.get_known_posts = asynctest.CoroutineMock(
            return_value=["two", "four", "five"])
        post_ids = ["one", "two", "three", "four", "five", "six"]
        new_ids = await source.filter_new_posts("source_id", post_ids)
        assert new_ids == ["one", "three", "six"]
        source._db_client.get_known_posts.assert_called_once_with(
            "source_id", post_ids)

        # empty list
        source._db_client.get_known_posts = asynctest.CoroutineMock(
            return_value=[])
        new_ids = await source.filter_new_posts("source_id", [])
        assert new_ids == []
        source._db_client.get_known_posts.assert_called_once_with(
            "source_id", [])
Beispiel #23
0
    async def test_insert_post(self):
        params = {"target_id": "target-id",
                  "post_id": "post-id",
                  "source_id": "source-id",
                  "text": "Text",
                  "created": "2016-10-19T10:13:43+00:00",
                  "sticky": True,
                  "updated": "2016-10-19T10:13:43+00:00",
                  "target_doc": {"foo": "doc"}}
        self.client._engine = asynctest.MagicMock()
        self.client._engine.execute = asynctest.CoroutineMock(return_value=True)
        res = await self.client.insert_post(**params)
        assert res is True

        # failing
        self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())
        res = await self.client.insert_post(**params)
        assert res is False
Beispiel #24
0
    def test_async_wait_lowlevel(self) -> None:
        timeout = 1
        on_ready = asynctest.MagicMock()
        timer = test_async_sleep_ext.SystemTimer(io_context=self._io_context,
                                                 seconds=timeout)
        timer.async_wait(on_ready=on_ready)

        time.sleep(timeout * 3)

        on_ready.assert_called_once()

        args, kwags = on_ready.call_args
        self.assertEqual(1, len(args))
        self.assertDictEqual({}, kwags)

        error_code = args[0]
        self.assertTrue(isinstance(error_code, ErrorCode))
        self.assertEqual(0, error_code.value)
Beispiel #25
0
 async def get_application(self):
     """
     Override the get_app method to return your application.
     """
     self.config = {
         "host": "localhost",
         "port": 9990,
         "auth": {
             "user": "******",
             "password": "******"
         }
     }
     self.controller = asynctest.MagicMock(
         spec="livebridge.controller.Controller")
     server = WebApi(config=self.config,
                     controller=self.controller,
                     loop=self.loop)
     return server.app
    async def test_delete(self):
        """
        Case: A DELETE request get executed
        Expected: The correct parameters get given to the request library
        """
        self.Session_mock.return_value.headers = asynctest.MagicMock()
        self.Session_mock.return_value.delete = asynctest.CoroutineMock()

        response = await self.client.delete(url='https://example.com/test',
                                            headers={'some': 'header'},
                                            extra='param')

        self.Session_mock.return_value.delete.assert_called_once_with(
            'https://example.com/test',
            headers={'some': 'header'},
            extra='param')
        self.assertEqual(response,
                         self.Session_mock.return_value.delete.return_value)
Beispiel #27
0
 async def test_run_with_loop(self):
     self.loop.run_until_complete = asynctest.CoroutineMock(
         return_value=True)
     control_file = os.path.join(os.path.dirname(__file__), "files",
                                 "control.yaml")
     db_connector = asynctest.MagicMock()
     db_connector.setup = asynctest.CoroutineMock(return_value=True)
     with asynctest.patch(
             "livebridge.components.get_db_client") as mocked_db_client:
         mocked_db_client.return_value = db_connector
         with asynctest.patch(
                 "livebridge.controller.Controller") as mocked_controller:
             mocked_controller.run = asynctest.CoroutineMock(
                 return_value=True)
             with asynctest.patch("asyncio.ensure_future") as mocked_ensure:
                 mocked_ensure.return_value = True
                 from livebridge.run import main
                 livebridge = main(loop=self.loop, control=control_file)
                 assert type(livebridge) is LiveBridge
    async def test_run_adds_the_new_task_for_each_valid_clock_tick(self):
        clock = asynctest.MagicMock()
        clock.__aiter__.return_value = range(3)
        wrapped_task = Mock()
        with patch.multiple(
                self.task_runner,
                clock=clock,
                _wrapped_task=wrapped_task,
                running_tasks=Mock(spec=set),
                can_dispatch_task=CoroutineMock(
                    side_effect=[True, False, True]),
        ), patch("asyncworker.task_runners.asyncio.ensure_future"
                 ) as ensure_future:
            await self.task_runner._run()

            self.task_runner.running_tasks.add.assert_has_calls([
                call(ensure_future.return_value),
                call(ensure_future.return_value),
            ])
Beispiel #29
0
    async def test_save_control(self):
        data = {"foo": "bar"}
        self.client._engine = asynctest.MagicMock()
        self.client._engine.execute = asynctest.CoroutineMock(return_value=True)
        # update
        self.client.get_control = asynctest.CoroutineMock(return_value=True)
        res = await self.client.save_control(data=data)
        assert res is True
        assert self.client._engine.execute.call_count == 1
        assert str(self.client._engine.execute.call_args[0][0]) == \
            "UPDATE test_control_table SET data=:data, updated=:updated WHERE test_control_table.type = :type_1"

        # insert new one
        self.client.get_control = asynctest.CoroutineMock(return_value=False)
        res = await self.client.save_control(data=data)
        assert res is True
        assert self.client._engine.execute.call_count == 2
        assert str(self.client._engine.execute.call_args[0][0]) == \
            "INSERT INTO test_control_table (type, data, updated) VALUES (:type, :data, :updated)"
Beispiel #30
0
    async def test_setup(self):
        self.client.db_client = asynctest.MagicMock()
        create_resp = {"ResponseMetadata": {"HTTPStatusCode": 200}}
        self.client.db_client.create_table = asynctest.CoroutineMock(return_value=create_resp)
        self.client.db_client.close = asynctest.CoroutineMock(return_value=None)

        # table exists already
        table_resp = {"TableNames": [self.table_name, self.control_table_name]}
        self.client.db_client.list_tables = asynctest.CoroutineMock(return_value=table_resp)
        res = await self.client.setup()
        assert res is False
        assert self.client.db_client.list_tables.call_count == 1
        assert self.client.db_client.create_table.call_count == 0

        # create one table
        table_resp = {"TableNames": [self.table_name]}
        self.client.db_client.list_tables.return_value = table_resp
        res = await self.client.setup()
        assert res is True
        assert self.client.db_client.list_tables.call_count == 2
        assert self.client.db_client.create_table.call_count == 1

        # create second table
        table_resp = {"TableNames": [self.control_table_name]}
        self.client.db_client.list_tables.return_value = table_resp
        res = await self.client.setup()
        assert res is True
        assert self.client.db_client.list_tables.call_count == 3
        assert self.client.db_client.create_table.call_count == 2

        # create both tables
        table_resp = {"TableNames": []}
        self.client.db_client.list_tables.return_value = table_resp
        res = await self.client.setup()
        assert res is True
        assert self.client.db_client.list_tables.call_count == 4
        assert self.client.db_client.create_table.call_count == 4

        # failes with exception
        self.client.db_client.list_tables.side_effect = Exception
        res = await self.client.setup()
        assert res is False