示例#1
0
async def uplink_mock(loop):
    uplink = asynctest.Mock(nibeuplink.Uplink('', '', ''))

    def get_parameter(system_id, parameter_id):
        return PARAMETERS[parameter_id]

    uplink.get_parameter.side_effect = get_parameter
    return uplink
async def mock_database():
    mock_db = MockDatabase()
    wrap = asynctest.Mock(wraps=mock_db, spec=mock_db)
    await wrap.mock_start()
    try:
        yield wrap
    finally:
        await wrap.mock_close()
示例#3
0
    async def test_with_decorator(self, debug_mock, error_mock):
        client = asynctest.Mock(AsyncClient())
        cache = {}

        await cache_users_async(client, cache)

        debug_mock.assert_called()
        error_mock.assert_not_called()
示例#4
0
    async def test_with_context_manager(self):
        client = asynctest.Mock(AsyncClient())
        cache = {}

        with asynctest.patch("logging.debug") as debug_mock:
            await cache_users_async(client, cache)

        debug_mock.assert_called()
示例#5
0
 def test_is_already_sticker_name(self, sticker_set_name, ans):
     sticker = Sticker(self._mock_bot, TEST_USER_NAME, TEST_USER_ID,
                       TEST_CHAT_ID)
     self._mock_bot.getStickerSet = asynctest.Mock(
         side_effect=MockTelepot.mock_get_sticker_set)
     loop = asyncio.get_event_loop()
     actual = loop.run_until_complete(
         sticker.is_already_sticker_name(sticker_set_name))
     assert actual is ans
示例#6
0
 def test_generate_sticker_name(self, sticker_id, file_name, ans):
     self._mock_bot.getMe = asynctest.Mock(
         side_effect=MockTelepot.mock_get_me)
     sticker = Sticker(self._mock_bot, TEST_USER_NAME, TEST_USER_ID,
                       TEST_CHAT_ID, sticker_id)
     loop = asyncio.get_event_loop()
     actual = loop.run_until_complete(
         sticker.generate_sticker_name(file_name=file_name))
     assert actual == ans
示例#7
0
def create_mocked_connection():
    mocked_transaction = create_mocked_transaction()
    mocked_conn = asynctest.create_autospec(asyncpg.connection.Connection)
    mocked_conn.transaction = asynctest.Mock(return_value=mocked_transaction)
    mocked_conn.fetchval = asynctest.CoroutineMock()
    mocked_conn.fetchrow = asynctest.CoroutineMock()
    mocked_conn.fetch = asynctest.CoroutineMock()
    mocked_conn.execute = asynctest.CoroutineMock()
    return mocked_conn
示例#8
0
 def setUp(self):
     self.discord = asynctest.Mock(DiscordService())
     self.discord.on_member_join_callbacks = []
     self.config = {
         "welcome_message": {
             "message": "my message {joined_user}",
             "channel": "my channel"
         }
     }
     self.mock_config_service = MockConfigurationService(self.config)
     self.mock_user_joined = create_mock_user("val")
     self.returned_message = "dsfasf"
     self.discord_mention_service = asynctest.Mock(
         DiscordMentionFactory(None))
     self.discord_mention_service.perform_replacement = MagicMock(
         return_value=self.returned_message)
     WelcomeMessage(self.mock_config_service, self.discord,
                    self.discord_mention_service)
示例#9
0
async def test_monitor_removed_callback_all(uplink_mock):
    monitor = nibeuplink.Monitor(uplink_mock)

    callback_a1 = asynctest.Mock()
    callback_a2 = asynctest.Mock()
    monitor.add_callback(callback_a1)
    monitor.add_callback(callback_a2)

    monitor.add(1, "a")
    monitor.remove(1, "a")

    monitor.del_callback(callback_a1)
    monitor.del_callback(callback_a2)

    await monitor.run_once()

    uplink_mock.get_parameter.assert_not_called()
    callback_a1.assert_not_called()
    callback_a2.assert_not_called()
示例#10
0
async def test_monitor_1(uplink_mock):
    monitor = nibeuplink.Monitor(uplink_mock)

    callback_a = asynctest.Mock()
    monitor.add_callback(callback_a)
    monitor.add(1, "a")

    await monitor.run_once()

    callback_a.assert_called_once_with(1, {"a": PARAMETERS["a"]})
示例#11
0
 def testStartTcpServer(self):
     ''' Test that the modbus tcp asyncio server starts correctly '''
     identity = ModbusDeviceIdentification(info={0x00: 'VendorName'})
     self.loop = asynctest.Mock(self.loop)
     server = yield from StartTcpServer(context=self.context,
                                        loop=self.loop,
                                        identity=identity)
     self.assertEqual(server.control.Identity.VendorName, 'VendorName')
     if PYTHON_VERSION >= (3, 6):
         self.loop.create_server.assert_called_once()
示例#12
0
def mock_merge_strategy(mocker):
    # A little unspoken assumption that merger only uses these methods.
    class S:
        async def track_stream():
            pass

        def finalize():
            pass

    return asynctest.Mock(spec=S)
示例#13
0
def binance():
    b = asynctest.Mock(Binance)
    b.name = 'binance'
    b.side = 'taker'
    b.min_total_order_value = {
        'ETH': Decimal('0.011'),  # 0.01
        'BTC': Decimal('0.00011'),  # 0.0001
        'USDT': Decimal('11'),  # 1mm_bot/strategy/test/test_cross_market.py0
    }
    return b
示例#14
0
    async def test_persist_blocks(self):

        fake_block1 = asynctest.MagicMock()
        fake_block1.index = 1
        fake_block2 = asynctest.MagicMock()
        fake_block2.index = 2

        # inserting out of order on purpose to also validate sorting
        self.syncmgr.block_cache = [fake_block2, fake_block1]

        mocked_result = asynctest.Mock()
        with asynctest.patch.object(self.syncmgr.ledger,
                                    'persist',
                                    side_effect=mocked_result):
            await self.syncmgr.persist_blocks()

        # test that we persisted the blocks in order
        mocked_result.assert_has_calls([
            asynctest.mock.call(fake_block1),
            asynctest.mock.call(fake_block2)
        ],
                                       any_order=False)

        # now test with an exception happening during persist
        self.syncmgr.block_cache = [fake_block2, fake_block1]
        with self.assertLogs(network_logger, 'DEBUG') as log_context:
            with asynctest.patch.object(self.syncmgr.ledger,
                                        'persist',
                                        side_effect=Exception):
                await self.syncmgr.persist_blocks()
        self.assertIn(
            "Unexpected exception happened while processing the block cache",
            log_context.output[0])
        self.assertFalse(self.syncmgr._is_persisting_blocks)

        # test that we don't persist if we're starting to shutdown
        self.syncmgr.shutting_down = True
        mocked_result = asynctest.Mock()
        with asynctest.patch.object(self.syncmgr.ledger,
                                    'persist',
                                    side_effect=mocked_result):
            await self.syncmgr.persist_blocks()
        mocked_result.assert_not_called()
    def setUp(self):
        self.discord = asynctest.Mock(DiscordService())

        self.discord_mention_factory = DiscordMentionFactory(self.discord)

        matching_channel = MagicMock()
        type(matching_channel).mention = PropertyMock(return_value="<channelVal>")
        self.discord.get_channel = MagicMock(return_value=matching_channel)

        self.message_template = "Please see us in {channel:the-channel}"
示例#16
0
async def test_empty_chunk():
    async def iter_chunked(n: int):
        yield b''

    content = asynctest.Mock(iter_chunked=iter_chunked)
    lines = []
    async for line in _iter_jsonlines(content):
        lines.append(line)

    assert lines == []
示例#17
0
    async def test_result_with_wrapped_object(self):
        stub = StubClient()
        mock = asynctest.Mock(stub, wraps=stub)
        cache = {}

        stub.add_user(StubClient.User(1, "a.dmin"))
        cache_users(mock, cache)

        mock.get_users.assert_called()
        self.assertEqual(stub.users_to_return, mock.get_users())
示例#18
0
async def test_one_chunk_empty_lines():
    async def iter_chunked(n: int):
        yield b'\n\nhello\n\nworld\n\n'

    content = asynctest.Mock(iter_chunked=iter_chunked)
    lines = []
    async for line in _iter_jsonlines(content):
        lines.append(line)

    assert lines == [b'hello', b'world']
示例#19
0
async def test_one_chunk_one_line():
    async def iter_chunked(n: int):
        yield b'hello'

    content = asynctest.Mock(iter_chunked=iter_chunked)
    lines = []
    async for line in _iter_jsonlines(content):
        lines.append(line)

    assert lines == [b'hello']
示例#20
0
 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()
示例#21
0
    async def test_put_uses_the_default_vhost_if_none_is_provided(self):
        connection_a = asynctest.Mock(virtual_host=settings.AMQP_DEFAULT_VHOST,
                                      spec=JsonQueue)
        connection_b = asynctest.Mock(virtual_host="b", spec=JsonQueue)

        self.rabbitmq_connection.register(connection_a)
        self.rabbitmq_connection.register(connection_b)

        await self.rabbitmq_connection.put(data=self.body,
                                           routing_key=self.routing_key,
                                           exchange=self.exchange)

        connection_b.put.assert_not_awaited()
        connection_a.put.assert_awaited_once_with(
            data=self.body,
            routing_key=self.routing_key,
            exchange=self.exchange,
            serialized_data=None,
        )
示例#22
0
def mock_connection_factory(monkeypatch):
    """Mock the create functions for serial and TCP Asyncio connections."""
    from dsmr_parser.clients.protocol import DSMRProtocol
    transport = asynctest.Mock(spec=asyncio.Transport)
    protocol = asynctest.Mock(spec=DSMRProtocol)

    @asyncio.coroutine
    def connection_factory(*args, **kwargs):
        """Return mocked out Asyncio classes."""
        return (transport, protocol)

    connection_factory = Mock(wraps=connection_factory)

    # apply the mock to both connection factories
    monkeypatch.setattr('dsmr_parser.clients.protocol.create_dsmr_reader',
                        connection_factory)
    monkeypatch.setattr('dsmr_parser.clients.protocol.create_tcp_dsmr_reader',
                        connection_factory)

    return connection_factory, transport, protocol
示例#23
0
    async def test_update_item(self):
        self.target._login = asynctest.CoroutineMock(return_value=True)
        self.target._save_item = asynctest.CoroutineMock(
            return_value={"one": "two"})
        self.target._build_post_data = asynctest.Mock(
            return_value='{"foo": "baz"}')
        self.target._patch = asynctest.CoroutineMock(
            return_value={"res": "true"})
        res = await self.target.update_item(asynctest.Mock(content=[1, 2, 3]))
        assert type(res) == TargetResponse
        assert res.data == {"res": "true"}
        assert self.target._login.call_count == 1
        assert self.target._build_post_data.call_count == 1
        assert self.target._save_item.call_count == 3
        assert self.target._patch.call_count == 1

        # no id at target found
        self.target.get_id_at_target = asynctest.Mock(return_value=None)
        with self.assertRaises(InvalidTargetResource):
            await self.target.update_item(asynctest.Mock(content=[1, 2, 3]))
示例#24
0
async def test_empty_content():
    async def iter_chunked(n: int):
        if False:  # to make this function a generator
            yield b''

    content = asynctest.Mock(iter_chunked=iter_chunked)
    lines = []
    async for line in _iter_jsonlines(content):
        lines.append(line)

    assert lines == []
示例#25
0
 async def stream_from_queue() -> asynctest.CoroutineMock:
     """ Stream a list of integers from a mock queue, and return the a CoroutineMock holding the results. """
     in_q = asynctest.Mock(asyncio.Queue)
     q_input = [0, 1, 2]
     in_q.get.side_effect = q_input
     asend = asynctest.CoroutineMock()
     src = AsyncStreamFromFixedQueue(in_q, len(q_input))
     src.start()
     await aioreact.subscribe(src,
                              aioreact.AsyncAnonymousObserver(asend))
     return asend
    def setUp(self):
        self.discord = asynctest.Mock(DiscordService())

        self.discord_mention_factory = DiscordMentionFactory(self.discord)

        self.mock_joining_user = create_mock_user("<val>")

        matching_role = MagicMock()
        type(matching_role).mention = PropertyMock(return_value="<rolestr>")
        self.discord.get_matching_role = MagicMock(return_value=matching_role)
        
        self.message_template = "Please message a {role:Recruiter}!"
def mock_database_queries():
    class Q:
        async def get_teams_in_game():
            pass

        async def get_game_stats():
            pass

        async def get_mod_versions():
            pass

    return asynctest.Mock(spec=Q)
示例#28
0
async def test_few_chunks_split():
    async def iter_chunked(n: int):
        yield b'\n\nhell'
        yield b'o\n\nwor'
        yield b'ld\n\n'

    content = asynctest.Mock(iter_chunked=iter_chunked)
    lines = []
    async for line in _iter_jsonlines(content):
        lines.append(line)

    assert lines == [b'hello', b'world']
示例#29
0
    async def test_put_uses_the_right_connection_for_a_given_vhost(self):
        connection_a = asynctest.Mock(virtual_host="a", spec=JsonQueue)
        connection_b = asynctest.Mock(virtual_host="b", spec=JsonQueue)

        self.rabbitmq_connection.register(connection_a)
        self.rabbitmq_connection.register(connection_b)

        await self.rabbitmq_connection.put(
            serialized_data=self.body,
            routing_key=self.routing_key,
            exchange=self.exchange,
            vhost="a",
        )

        connection_b.put.assert_not_awaited()
        connection_a.put.assert_awaited_once_with(
            data=None,
            routing_key=self.routing_key,
            exchange=self.exchange,
            serialized_data=self.body,
        )
示例#30
0
    async def setUp(self):
        self.task = CoroutineMock()
        self.app = asynctest.Mock(spec=App)
        self.seconds = 10
        self.max_concurrency = 2

        self.task_runner = ScheduledTaskRunner(
            seconds=self.seconds,
            task=self.task,
            app=self.app,
            max_concurrency=self.max_concurrency,
        )