async def test_synchronize_state_with_terminal_from_time(self):
     """Should synchronize state with terminal from specified time."""
     client.synchronize = AsyncMock()
     with patch('lib.metaApi.metaApiConnection.random_id',
                return_value='synchronizationId'):
         api = MetaApiConnection(client, account, None, MagicMock(),
                                 date('2020-10-07T00:00:00.000Z'))
         await api.history_storage.on_history_order_added(
             1, {'doneTime': date('2020-01-01T00:00:00.000Z')})
         await api.history_storage.on_deal_added(
             1, {'time': date('2020-01-02T00:00:00.000Z')})
         await api.synchronize(1)
         client.synchronize.assert_called_with(
             'accountId', 1, 'synchronizationId',
             date('2020-10-07T00:00:00.000Z'),
             date('2020-10-07T00:00:00.000Z'))
    def test_async_do_actions_raise_execption(self):
        actions = [{
            'name': 'action1'
        }, {
            'name': 'action2',
            'params': {
                'param1': 'foo',
                'param2': 10
            }
        }]
        defined_actions = BaseActions()
        defined_actions.action1 = AsyncMock()

        with self.assertRaises(AssertionError):
            asyncio.get_event_loop().run_until_complete(
                engine.async_do_actions(actions, defined_actions))
Exemple #3
0
async def test_delete_no_key_single_state_key_false(patched_send,
                                                    opsdroid_matrix, caplog):
    patched_send.return_value = nio.RoomGetStateEventResponse({}, "", "", "")
    patched_send.return_value.transport_response = AsyncMock()
    patched_send.return_value.transport_response.status = 404

    db = DatabaseMatrix({"single_state_key": False}, opsdroid=opsdroid_matrix)
    db.should_migrate = False
    caplog.clear()
    data = await db.delete("twim")

    assert data is None

    assert [
        "State event dev.opsdroid.database with state key 'twim' doesn't exist."
    ] == [rec.message for rec in caplog.records]
 async def test_close_position_partially(self):
     """Should close position partially."""
     trade_result = {
         'error': 10009,
         'description': 'TRADE_RETCODE_DONE',
         'orderId': 46870472
     }
     client.trade = AsyncMock(return_value=trade_result)
     actual = await api.close_position_partially('46870472', 0.9)
     assert actual == trade_result
     client.trade.assert_called_with(
         'accountId', {
             'actionType': 'POSITION_PARTIAL',
             'positionId': '46870472',
             'volume': 0.9
         })
Exemple #5
0
async def test_on_login_as_guest_button(prompt, mocker):
    # Setup
    prompt.network_client.login_as_guest = AsyncMock()
    mock_dialog = mocker.patch("PySide2.QtWidgets.QInputDialog").return_value
    mock_execute_dialog = mocker.patch(
        "randovania.gui.lib.async_dialog.execute_dialog",
        new_callable=AsyncMock,
        return_value=mock_dialog.Accepted)

    # Run
    await prompt.on_login_as_guest_button()

    # Assert
    mock_execute_dialog.assert_awaited_once_with(mock_dialog)
    prompt.network_client.login_as_guest.assert_awaited_once_with(
        mock_dialog.textValue.return_value)
async def test_get_no_key_single_state_key(patched_send, opsdroid_matrix):
    patched_send.return_value = nio.RoomGetStateEventResponse(
        {"wibble": "wobble"}, "", "", "")
    patched_send.return_value.transport_response = AsyncMock()
    patched_send.return_value.transport_response.status = 200

    db = DatabaseMatrix({
        "should_encrypt": False,
        "single_state_key": True
    },
                        opsdroid=opsdroid_matrix)
    db.should_migrate = False

    data = await db.get("twim")

    assert data is None
Exemple #7
0
async def test_find_missing_remote_pickups_pending_location(
        connector: EchoesRemoteConnector):
    # Setup
    executor = AsyncMock()
    inventory = {
        connector.game.resource_database.multiworld_magic_item:
        InventoryItem(5, 15)
    }

    # Run
    patches, has_message = await connector.find_missing_remote_pickups(
        executor, inventory, [], False)

    # Assert
    assert patches == []
    assert not has_message
Exemple #8
0
async def test_get_inventory_valid(connector: EchoesRemoteConnector):
    # Setup
    executor = AsyncMock()
    executor.perform_memory_operations.side_effect = lambda ops: {
        op: struct.pack(">II", item.max_capacity, item.max_capacity)
        for op, item in zip(ops, connector.game.resource_database.item)
    }

    # Run
    inventory = await connector.get_inventory(executor)

    # Assert
    assert inventory == {
        item: InventoryItem(item.max_capacity, item.max_capacity)
        for item in connector.game.resource_database.item
    }
Exemple #9
0
async def test_session_self_update(client: NetworkClient):
    client._emit_without_result = AsyncMock()
    client._current_game_session_meta = MagicMock()
    client._current_game_session_meta.id = 1234

    inventory: Inventory = {
        ItemResourceInfo("None", "None", 1, frozendict({"item_id": 0})):
        InventoryItem(1, 1)
    }

    await client.session_self_update(inventory, GameConnectionStatus.InGame,
                                     MemoryExecutorChoice.DOLPHIN)

    client._emit_without_result.assert_awaited_once_with(
        "game_session_self_update",
        (1234, b'\x01None\x00\x01\x01', "In-game (Dolphin)"))
Exemple #10
0
async def test_get_inventory(backend):
    # Setup
    backend._get_player_state_address = AsyncMock(return_value=0)
    backend.dolphin.read_word.side_effect = [
        item.index
        for item in backend.game.resource_database.item
    ]

    # Run
    inventory = await backend.get_inventory()

    # Assert
    assert inventory == {
        item: item.index
        for item in backend.game.resource_database.item
    }
    async def test_should_destroy_subscribe_process_on_cancel(self):
        subscribe = AsyncMock()

        async def delay_subscribe(account_id, instance_index):
            await subscribe()
            await asyncio.sleep(0.4)
            return

        client.subscribe = delay_subscribe
        asyncio.create_task(manager.subscribe('accountId'))
        await asyncio.sleep(0.05)
        manager.cancel_subscribe('accountId:0')
        await asyncio.sleep(0.05)
        asyncio.create_task(manager.subscribe('accountId'))
        await asyncio.sleep(0.05)
        assert subscribe.call_count == 2
Exemple #12
0
async def test_subscribe_single(app, client, m_influx, values_result):
    m_influx.query = AsyncMock(return_value=values_result)
    async with client.get('/sse/values',
                          params=urlencode(
                              {
                                  'measurement': 'm',
                                  'end': '2018-10-10T12:00:00.000+02:00',
                                  'approx_points': 0
                              },
                              doseq=True)) as resp:
        assert await resp.content.read(6) == b'data: '
        expected = values_result['results'][0]['series'][0]
        expected_json = json.dumps(expected)
        resp_values = await resp.content.read(len(expected_json))
        actual = json.loads(resp_values.decode())
        assert actual == expected
 async def test_maintain_sync(self):
     """Should maintain synchronization if connection has failed."""
     with patch('lib.metaApi.metaApiConnection.random_id',
                return_value='synchronizationId'):
         client.synchronize = AsyncMock(
             side_effect=[Exception('test error'), None])
         api = MetaApiConnection(client, account, None, MagicMock())
         await api.history_storage.on_history_order_added(
             1, {'doneTime': date('2020-01-01T00:00:00.000Z')})
         await api.history_storage.on_deal_added(
             1, {'time': date('2020-01-02T00:00:00.000Z')})
         await api.on_connected(1, 1)
         client.synchronize.assert_called_with(
             'accountId', 1, 'synchronizationId',
             date('2020-01-01T00:00:00.000Z'),
             date('2020-01-02T00:00:00.000Z'))
 async def test_correct_error_when_bad_channel_is_called(self):
     context = AsyncMock(commands.context.Context)
     context.channel = Mock(discord.TextChannel)
     context.channel.id = 4
     context.channel.mention = "test_mention"
     context.guild = Mock(discord.Guild)
     context.guild.id = 5
     context.send = AsyncMock(return_value=Mock(discord.Message))
     with self.assertRaises(commands.BadArgument):
         await self.logger.log(self, context, "Join", "test")
     self.assertFalse(context.send.called)
 async def test_log_command(self):
     context = AsyncMock(commands.context.Context)
     context.channel = Mock(discord.TextChannel)
     context.channel.id = 4
     context.channel.mention = "test_mention"
     context.guild = Mock(discord.Guild)
     context.guild.id = 5
     context.send = AsyncMock(return_value=Mock(discord.Message))
     await self.logger.log(self, context, "Join", "here")
     self.assertTrue(context.send.called)
     self.assertTrue(self.db.set_log_channel.called)
Exemple #16
0
async def test_last_values_sse(app, client, m_influx, last_values_result):
    m_influx.query = AsyncMock(return_value=last_values_result)
    signal = features.get(app, sse.ShutdownAlert).shutdown_signal

    expected = [
        {
            'field': 'val1',
            'time': 1556527890131178000,
            'value': 0,
        },
        {
            'field': 'val2',
            'time': 1556527890131178000,
            'value': 100,
        },
        {
            'field': 'val_none',
            'time': None,
            'value': None,
        },
    ]
    expected_len = len(json.dumps(expected))
    prefix_len = len('data: ')

    async with client.get('/sse/last_values',
                          params=urlencode(
                              {
                                  'measurement': 'sparkey',
                                  'fields': ['val1', 'val2', 'val_none']
                              },
                              doseq=True)) as resp:
        resp_values = []

        while len(resp_values) < 3:
            read_val = (await
                        resp.content.read(prefix_len + expected_len)).decode()
            # Skip new line characters
            if read_val.rstrip():
                resp_values.append(json.loads(read_val[prefix_len:]))

        assert resp_values == [expected, expected, expected]

        signal.set()
        await asyncio.sleep(0.1)

    assert resp.status == 200
 async def test_retrieve_latest_tick(self):
     """Should retrieve latest tick."""
     tick = {
         'symbol': 'AUDNZD',
         'time': '2020-04-07T03:45:00.000Z',
         'brokerTime': '2020-04-07 06:45:00.000',
         'bid': 1.05297,
         'ask': 1.05309,
         'last': 0.5298,
         'volume': 0.13,
         'side': 'buy'
     }
     client.get_tick = AsyncMock(return_value=tick)
     actual = await api.get_tick('AUDNZD')
     tick['time'] = date(tick['time'])
     assert actual == tick
     client.get_tick.assert_called_with('accountId', 'AUDNZD')
Exemple #18
0
async def test_copy_permalink_is_admin(window, mocker):
    mock_set_clipboard: MagicMock = mocker.patch(
        "randovania.gui.lib.common_qt_lib.set_clipboard")
    execute_dialog = mocker.patch(
        "randovania.gui.lib.async_dialog.execute_dialog",
        new_callable=AsyncMock)
    window._admin_global_action = AsyncMock(return_value="<permalink>")

    # Run
    await window.copy_permalink()

    # Assert
    window._admin_global_action.assert_awaited_once_with(
        SessionAdminGlobalAction.REQUEST_PERMALINK, None)
    execute_dialog.assert_awaited_once()
    assert execute_dialog.call_args.args[0].textValue() == "<permalink>"
    mock_set_clipboard.assert_called_once_with("<permalink>")
Exemple #19
0
def test_process_command_success_no_proc(payment, loop, db):
    store = StorableFactory(db)

    my_addr = LibraAddress.from_bytes("lbr", b'B' * 16)
    other_addr = LibraAddress.from_bytes("lbr", b'A' * 16)
    bcm = TestBusinessContext(my_addr)
    processor = PaymentProcessor(bcm, store, loop)

    net = AsyncMock(Aionet)
    processor.set_network(net)

    cmd = PaymentCommand(payment)
    cmd.set_origin(my_addr)

    # No obligation means no processing
    coro = processor.process_command_success_async(other_addr, cmd, seq=10)
    _ = loop.run_until_complete(coro)
Exemple #20
0
async def test_finish_session(window, accept, mocker):
    mock_warning = mocker.patch("randovania.gui.lib.async_dialog.warning",
                                new_callable=AsyncMock)
    mock_warning.return_value = QtWidgets.QMessageBox.Yes if accept else QtWidgets.QMessageBox.No

    window.network_client.session_admin_global = AsyncMock()

    # Run
    await window.finish_session()

    # Assert
    mock_warning.assert_awaited_once()
    if accept:
        window.network_client.session_admin_global.assert_awaited_once_with(
            SessionAdminGlobalAction.FINISH_SESSION, None)
    else:
        window.network_client.session_admin_global.assert_not_awaited()
def test_vasp_simple(json_request, vasp, other_addr, loop):
    vasp.pp.loop = loop
    net = AsyncMock(Aionet)
    vasp.pp.set_network(net)

    key = vasp.info_context.get_my_compliance_signature_key(other_addr)
    signed_json_request = asyncio.run(key.sign_message(json.dumps(json_request)))
    response = asyncio.run(vasp.process_request(other_addr, signed_json_request))
    assert response
    assert response.type is CommandResponseObject

    assert len(vasp.pp.futs) == 1
    for fut in vasp.pp.futs:
        vasp.pp.loop.run_until_complete(fut)
        fut.result()

    assert len(net.method_calls) == 2
Exemple #22
0
def test_logic_protocol_check(payment_sender_init, loop):
    # Test the protocol given a sequence of commands.

    store = StorableFactory({})

    my_addr = LibraAddress.from_bytes(b'B' * 16)
    other_addr = LibraAddress.from_bytes(b'A' * 16)
    bcm = TestBusinessContext(my_addr)
    processor = PaymentProcessor(bcm, store, loop)

    net = AsyncMock(Aionet)
    processor.set_network(net)

    cmd = PaymentCommand(payment_sender_init)
    cmd.set_origin(other_addr)

    processor.check_command(my_addr, other_addr, cmd)
 async def test_modify_position(self):
     """Should modify position."""
     trade_result = {
         'error': 10009,
         'description': 'TRADE_RETCODE_DONE',
         'orderId': 46870472
     }
     client.trade = AsyncMock(return_value=trade_result)
     actual = await api.modify_position('46870472', 2.0, 0.9)
     assert actual == trade_result
     client.trade.assert_called_with(
         'accountId', {
             'actionType': 'POSITION_MODIFY',
             'positionId': '46870472',
             'stopLoss': 2.0,
             'takeProfit': 0.9
         })
Exemple #24
0
 def test_assert_called_but_not_awaited(self):
     mock = AsyncMock(AsyncClass)
     with assertNeverAwaited(self):
         mock.async_method()
     self.assertTrue(iscoroutinefunction(mock.async_method))
     mock.async_method.assert_called()
     mock.async_method.assert_called_once()
     mock.async_method.assert_called_once_with()
     with self.assertRaises(AssertionError):
         mock.assert_awaited()
     with self.assertRaises(AssertionError):
         mock.async_method.assert_awaited()
Exemple #25
0
async def test_handle_balance_update_from_order(backtesting_trader):
    config, exchange_manager, trader = backtesting_trader
    portfolio_manager = exchange_manager.exchange_personal_data.portfolio_manager

    trader.simulate = False
    order = BuyMarketOrder(trader)

    if os.getenv('CYTHON_IGNORE'):
        return

    with patch.object(portfolio_manager, '_refresh_real_trader_portfolio',
                      new=AsyncMock()) as _refresh_real_trader_portfolio_mock, \
        patch.object(portfolio_manager, '_refresh_simulated_trader_portfolio_from_order',
                     new=Mock()) as _refresh_simulated_trader_portfolio_from_order_mock:
        _refresh_real_trader_portfolio_mock.assert_not_called()
        await portfolio_manager.handle_balance_update_from_order(order, True)
        _refresh_real_trader_portfolio_mock.assert_called_once()
        _refresh_simulated_trader_portfolio_from_order_mock.assert_not_called()
        _refresh_real_trader_portfolio_mock.reset_mock()
        await portfolio_manager.handle_balance_update_from_order(order, False)
        _refresh_real_trader_portfolio_mock.assert_not_called()
        _refresh_simulated_trader_portfolio_from_order_mock.assert_called_once(
        )

    trader.simulate = True
    with patch.object(
            portfolio_manager,
            '_refresh_simulated_trader_portfolio_from_order',
            new=Mock()) as _refresh_simulated_trader_portfolio_from_order_mock:
        _refresh_simulated_trader_portfolio_from_order_mock.assert_not_called()
        await portfolio_manager.handle_balance_update_from_order(order, True)
        _refresh_simulated_trader_portfolio_from_order_mock.assert_called_once(
        )
        _refresh_simulated_trader_portfolio_from_order_mock.reset_mock()
        # ensure no side effect with require_exchange_update param
        await portfolio_manager.handle_balance_update_from_order(order, False)
        _refresh_simulated_trader_portfolio_from_order_mock.assert_called_once(
        )

    trader.is_enabled = False
    trader.simulate = False
    assert not await portfolio_manager.handle_balance_update_from_order(
        order, True)
    assert not await portfolio_manager.handle_balance_update_from_order(
        order, False)
Exemple #26
0
    async def run_stress_test_without_exceptions(
            self,
            required_not_neutral_evaluation_ratio=0.75,
            reset_eval_to_none_before_each_eval=True,
            time_limit_seconds=15,
            skip_long_time_frames=False):
        try:
            await self.initialize()
            start_time = timer()
            with patch.object(self.evaluator, 'get_exchange_symbol_data', new=self._mocked_get_exchange_symbol_data), \
                    patch.object(self.evaluator, 'evaluation_completed', new=AsyncMock()):
                for symbol in self.data_bank.data_importer.symbols:
                    self.data_bank.default_symbol = symbol
                    self.data_bank.standard_mode(
                        self.ENOUGH_DATA_STARTING_POINT)
                    for time_frame, current_time_frame_data in self.data_bank.origin_ohlcv_by_symbol[
                            symbol].items():
                        if TimeFramesMinutes[time_frame] > TimeFramesMinutes[TimeFrames.THREE_DAYS] and \
                                skip_long_time_frames:
                            continue
                        self.time_frame = time_frame
                        # start with 0 data data frame and goes onwards until the end of the data
                        not_neutral_evaluation_count = 0
                        total_candles_count = len(current_time_frame_data)
                        start_point = self.ENOUGH_DATA_STARTING_POINT + 1
                        if total_candles_count > start_point:
                            for _ in range(start_point, total_candles_count):
                                if reset_eval_to_none_before_each_eval:
                                    # force None value if possible to make sure eval_note is set during eval_impl()
                                    self.evaluator.eval_note = None
                                await self._increment_bank_data_and_call_evaluator(
                                )

                                assert self.evaluator.eval_note is not None
                                if self.evaluator.eval_note != START_PENDING_EVAL_NOTE:
                                    assert not isnan(self.evaluator.eval_note)
                                if self.evaluator.eval_note != START_PENDING_EVAL_NOTE:
                                    not_neutral_evaluation_count += 1

                            assert not_neutral_evaluation_count / (total_candles_count - start_point) >= \
                                required_not_neutral_evaluation_ratio
            process_time = timer() - start_time
            assert process_time <= time_limit_seconds
        finally:
            await self.data_bank.stop()
async def test_get_inventory_invalid_amount(connector: EchoesRemoteConnector):
    # Setup
    custom_inventory = {"Darkburst": InventoryItem(1, 0)}

    executor = AsyncMock()
    executor.perform_memory_operations.side_effect = lambda ops: {
        op: struct.pack(
            ">II",
            *custom_inventory.get(
                item.short_name,
                InventoryItem(item.max_capacity, item.max_capacity)))
        for op, item in zip(ops, connector.game.resource_database.item)
    }

    # Run
    msg = "Received InventoryItem(amount=1, capacity=0) for Darkburst, which is an invalid state."
    with pytest.raises(MemoryOperationException, match=re.escape(msg)):
        await connector.get_inventory(executor)
    async def test_reload_provisioning_profile(self):
        """Should reload provisioning profile."""

        client.get_provisioning_profile = AsyncMock(side_effect=[{'_id': 'id', 'name': 'name',
                                                                  'version': 4, 'status': 'new',
                                                                  'brokerTimezone': 'EET',
                                                                  'brokerDSTSwitchTimezone': 'EET'},
                                                                 {'_id': 'id', 'name': 'name',
                                                                  'version': 4, 'status': 'active',
                                                                  'brokerTimezone': 'EET',
                                                                  'brokerDSTSwitchTimezone': 'EET'
                                                                  }
                                                                 ])
        profile = await api.get_provisioning_profile('id')
        await profile.reload()
        assert profile.status == 'active'
        client.get_provisioning_profile.assert_called_with('id')
        assert client.get_provisioning_profile.call_count == 2
 async def test_retrieve_account_information(self):
     """Should retrieve account information."""
     account_information = {
         'broker': 'True ECN Trading Ltd',
         'currency': 'USD',
         'server': 'ICMarketsSC-Demo',
         'balance': 7319.9,
         'equity': 7306.649913200001,
         'margin': 184.1,
         'freeMargin': 7120.22,
         'leverage': 100,
         'marginLevel': 3967.58283542
     }
     client.get_account_information = AsyncMock(
         return_value=account_information)
     actual = await api.get_account_information()
     assert actual == account_information
     client.get_account_information.assert_called_with('accountId')
Exemple #30
0
async def test_change_password(window, mocker):
    def set_text_value(dialog: QtWidgets.QInputDialog):
        dialog.setTextValue("magoo")
        return QtWidgets.QDialog.Accepted

    execute_dialog = mocker.patch(
        "randovania.gui.lib.async_dialog.execute_dialog",
        new_callable=AsyncMock,
        side_effect=set_text_value)
    window._admin_global_action = AsyncMock()

    # Run
    await window.change_password()

    # Assert
    execute_dialog.assert_awaited_once()
    window._admin_global_action.assert_awaited_once_with(
        SessionAdminGlobalAction.CHANGE_PASSWORD, "magoo")