Beispiel #1
0
async def test_getInstaclustrMetrics_bad_requests(capfd):
    with patch('aiohttp.ClientSession.get') as mocked_get:
        ## Bad request - HTTP Status code
        code, content_type = 400, 'application/json'
        mocked_get.return_value.__aenter__.side_effect = [
            MagicMock(status=code, headers={'Content-Type': content_type})
        ]
        response = await instaclustr.getInstaclustrMetrics(
            'dummy_cluster_id', ['list', 'of', 'metrics'], {
                "ic_user_name": 'user',
                "ic_api_key": 'key'
            })
        captured = capfd.readouterr()
        assert mocked_get.call_count == 1  # Call count increments for mock object
        assert response is None
        assert 'Missing metrics data from instaclustr - HTTP response code: {0}; HTTP Header Content-Type: {1}'.format(
            code, content_type) in captured.out

        ## Bad request - Content-Type
        code, content_type = 200, 'text/html'
        mocked_get.return_value.__aenter__.side_effect = [
            MagicMock(status=code, headers={'Content-Type': content_type})
        ]
        response = await instaclustr.getInstaclustrMetrics(
            'dummy_cluster_id', ['list', 'of', 'metrics'], {
                "ic_user_name": 'user',
                "ic_api_key": 'key'
            })
        captured = capfd.readouterr()
        assert mocked_get.call_count == 2  # Call count increments for mock object
        assert response is None
        assert 'Missing metrics data from instaclustr - HTTP response code: {0}; HTTP Header Content-Type: {1}'.format(
            code, content_type) in captured.out
Beispiel #2
0
class TestUnixConnectionManager:
    def test_instantiates(self):
        conn_man = UnixConnectionManager(PATH)

        assert 'conn_man' in locals()
        assert conn_man.path is PATH

    def test_instantiates_with_loop(self, event_loop):
        conn_man = UnixConnectionManager(PATH, event_loop)

        assert conn_man.path is PATH
        assert conn_man.loop is event_loop

    def test_repr(self):
        conn_man = UnixConnectionManager(PATH)

        assert repr(conn_man) == 'UnixConnectionManager(path={})'.format(
            repr(PATH))

    @patch('asyncio.open_unix_connection',
           return_value=(MagicMock(spec=asyncio.StreamReader),
                         MagicMock(spec=asyncio.StreamWriter)))
    @pytest.mark.asyncio
    async def test_new_connection(self, *args):
        conn = UnixConnectionManager(PATH)

        async with conn.new_connection() as conn:
            assert isinstance(conn, UnixConnection)
Beispiel #3
0
    async def setUp(self):
        self.signal_handler = SSE()

        handler1 = Mock(return_value=CoroutineMock())
        handler2 = Mock(return_value=CoroutineMock())
        handler3 = Mock(return_value=CoroutineMock())

        self.routes_registry = RoutesRegistry(
            {
                handler1: {
                    "type": RouteTypes.SSE,
                    "routes": ["Xablau"],
                    "options": {},
                    "default_options": {},
                },
                handler2: {
                    "type": RouteTypes.SSE,
                    "routes": ["Xena", "sse"],
                    "options": MagicMock(),
                    "default_options": {},
                },
                handler3: {
                    "type": RouteTypes.AMQP_RABBITMQ,
                    "routes": ["invalid route"],
                    "options": MagicMock(),
                    "default_options": {},
                },
            }
        )
Beispiel #4
0
 def test_post(self, ensure_future_mock: MagicMock):
     response = self.fetch(
         "/api/v1/email",
         method="POST",
         body=json.dumps({
             "jobs": [
                 {
                     "id": 13,
                     "email": "*****@*****.**"
                 },
                 {
                     "id": 14,
                     "email": "*****@*****.**"
                 },
             ],
             "template":
             "Hello!",
             "subject":
             "Hi!",
         }),
     )
     self.assertEqual(response.code, 202)
     ensure_future_mock.assert_called_once_with(
         self.email_service.send_emails.return_value)
     self.email_service.send_emails.assert_called_once_with(
         jobs=[{
             "id": 13,
             "email": "*****@*****.**"
         }, {
             "id": 14,
             "email": "*****@*****.**"
         }],
         template="Hello!",
         subject="Hi!",
     )
 def setUp(self):
     self.mock_config = MockConfigurationService(
         {"my_service": {
             "command_keyword": "!roles"
         }})
     self.mock_discord_service = MagicMock()
     self.mock_discord_service.create_listener_for_bot_command = MagicMock()
Beispiel #6
0
async def test_media_attributes_are_fetched(hass):
    """Test that media attributes are fetched."""
    mock_entity_id = await setup_mock_component(hass)
    mock_func = "{}{}".format(
        "homeassistant.components.ps4.media_player.",
        "pyps4.Ps4Async.async_get_ps_store_data",
    )

    # Mock result from fetching data.
    mock_result = MagicMock()
    mock_result.name = MOCK_TITLE_NAME
    mock_result.cover_art = MOCK_TITLE_ART_URL
    mock_result.game_type = "game"

    with patch(mock_func, return_value=mock_result) as mock_fetch:
        await mock_ddp_response(hass, MOCK_STATUS_PLAYING)

    mock_state = hass.states.get(mock_entity_id)
    mock_attrs = dict(mock_state.attributes)

    assert len(mock_fetch.mock_calls) == 1

    assert mock_state.state == STATE_PLAYING
    assert len(mock_attrs.get(ATTR_INPUT_SOURCE_LIST)) == 1
    assert mock_attrs.get(ATTR_INPUT_SOURCE_LIST)[0] == MOCK_TITLE_NAME
    assert mock_attrs.get(ATTR_MEDIA_CONTENT_ID) == MOCK_TITLE_ID
    assert mock_attrs.get(ATTR_MEDIA_TITLE) == MOCK_TITLE_NAME
    assert mock_attrs.get(ATTR_MEDIA_CONTENT_TYPE) == MOCK_TITLE_TYPE
Beispiel #7
0
def test_loading_games_returns_dict(hass):
    """Test that loading games always returns a dict."""
    with patch("homeassistant.components.ps4.load_json",
               side_effect=HomeAssistantError), patch(
                   "homeassistant.components.ps4.save_json",
                   side_effect=MagicMock()), patch("os.path.isfile",
                                                   return_value=True):
        mock_games = ps4.load_games(hass)

    assert isinstance(mock_games, dict)
    assert not mock_games

    with patch("homeassistant.components.ps4.load_json",
               return_value="Some String"), patch(
                   "homeassistant.components.ps4.save_json",
                   side_effect=MagicMock()), patch("os.path.isfile",
                                                   return_value=True):
        mock_games = ps4.load_games(hass)

    assert isinstance(mock_games, dict)
    assert not mock_games

    with patch("homeassistant.components.ps4.load_json",
               return_value=[]), patch(
                   "homeassistant.components.ps4.save_json",
                   side_effect=MagicMock()), patch("os.path.isfile",
                                                   return_value=True):
        mock_games = ps4.load_games(hass)

    assert isinstance(mock_games, dict)
    assert not mock_games
Beispiel #8
0
 async def test_receive_with_timeout(self):
     message = Message(MessageType.WEBSOCKET_INACTIVE)
     data = message.to_json()
     websocket = AsyncMock()
     websocket.recv = CoroutineMock()
     websocket.recv.return_value = data
     assert await receive(websocket, timeout_sec=3) == message
async def test_vnf_package_ids_token_valid():
    v = VnfDetector()
    mocked_get_auth_token = CoroutineMock()
    mocked_get_auth_token.return_value = "dummy"
    v._token = mocked_get_auth_token.return_value
    v._get_and_set_authentication_token = mocked_get_auth_token

    assert "dummy" == await v._get_and_set_authentication_token(None)
    resp = CoroutineMock()

    first_get_response = MagicMock()
    first_get_response.__aenter__.return_value = resp
    g = asyncio.Future()
    resp.json.return_value = g
    g.set_result([{"_id": 1}, {"_id": 2}])

    context_manager = MagicMock(side_effect=[
        first_get_response,
    ])

    mocked_session = MagicMock()
    mocked_session.get = context_manager

    resp.status = 200
    pkg_ids = await v.get_vnf_package_ids(mocked_session)
    assert pkg_ids == [1, 2]
    assert mocked_get_auth_token.await_count == 1
Beispiel #10
0
 def __init__(self):
     self.conn = FakeRedisConn()
     self.transaction = MagicMock()
     self.release = CoroutineMock()
     self.conn.multi_exec = MagicMock(return_value=self.transaction)
     self.conn.multi_exec.return_value.execute = CoroutineMock()
     self.clear = CoroutineMock()
Beispiel #11
0
def test_poll_repository(mocker, WORKERS):
    mocker.patch('jenkins_epo.tasks.WORKERS', WORKERS)
    REPOSITORIES = mocker.patch('jenkins_epo.tasks.REPOSITORIES', MagicMock())
    REPOSITORIES.__getitem__.side_effect = KeyError('pouet')

    Repository = mocker.patch('jenkins_epo.tasks.Repository')
    from jenkins_epo.tasks import RepositoryPollerTask

    Repository.from_name = CoroutineMock(return_value=MagicMock())
    repo = Repository.from_name.return_value
    repo.__str__.return_value = 'owner/repo'

    task = RepositoryPollerTask('owner/repo', Mock)
    assert str(task)

    yield from task()

    assert WORKERS.enqueue.mock_calls
    assert Repository.from_name.mock_calls
    assert REPOSITORIES.__setitem__.mock_calls

    Repository.from_name.reset_mock()
    REPOSITORIES.__getitem__.side_effect = None
    yield from task()
    assert not Repository.from_name.mock_calls
Beispiel #12
0
 def __init__(self):
     client = CoroutineMock()
     client.SET_IF_NOT_EXIST = self.SET_IF_NOT_EXIST
     self.client = client
     self.transaction = MagicMock()
     self.client.multi_exec = MagicMock(return_value=self.transaction)
     self.client.multi_exec.return_value.execute = CoroutineMock()
Beispiel #13
0
async def test_turn_off_request(control_response: MagicMock) -> None:
    """Unit test-cases for /switcher/turn_off request.

    Args:
      control_response: fixture of mocked
        ``SwitcherV2ControlResponseMSG`` object.
    """
    with patch(
            "request_handlers.SwitcherV2Api.control_device",
            return_value=control_response,
    ):
        async with ClientSession() as session:
            async with session.post(URL_TURN_OFF) as response:
                assert response.status == 200
                body = await response.json()
                assert body[consts.KEY_SUCCESSFUL]

            control_response.successful = False
            async with session.post(URL_TURN_OFF) as response:
                assert response.status == 200
                body = await response.json()
                assert not body[consts.KEY_SUCCESSFUL]
                assert consts.KEY_MESSAGE not in body

            control_response.msg_type = ResponseMessageType.STATE
            async with session.post(URL_TURN_OFF) as response:
                assert response.status == 200
                body = await response.json()
                assert not body[consts.KEY_SUCCESSFUL]
                assert consts.KEY_MESSAGE in body
Beispiel #14
0
    def test_send_membership(self):
        account = Account("test_salt", "H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr",
                          "test_account", [], [], [],
                          self.identities_registry)
        account_identity = MagicMock(autospec='sakia.core.registry.Identity')
        account_identity.selfcert = CoroutineMock(return_value=SelfCertification(2, "meta_brouzouf",
                                            "H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr", "test_account", 1000000000, ""))
        community = MagicMock(autospec='sakia.core.Community')
        community.blockUID = CoroutineMock(return_value=BlockUID(3102, "0000C5336F0B64BFB87FF4BC858AE25726B88175"))
        self.identities_registry.future_find = CoroutineMock(return_value=account_identity)
        community.bma_access = MagicMock(autospec='sakia.core.net.api.bma.access.BmaAccess')
        response = Mock()
        response.json = CoroutineMock(return_value={
  "signature": "H41/8OGV2W4CLKbE35kk5t1HJQsb3jEM0/QGLUf80CwJvGZf3HvVCcNtHPUFoUBKEDQO9mPK3KJkqOoxHpqHCw==",
  "membership": {
    "version": 2,
    "currency": "beta_brouzouf",
    "issuer": "HsLShAtzXTVxeUtQd7yi5Z5Zh4zNvbu8sTEZ53nfKcqY",
    "membership": "IN",
    "sigDate": 1390739944,
    "uid": "superman63"
  }
})
        response.status = 200
        community.bma_access.broadcast = CoroutineMock(return_value=[response])
        async def exec_test():
            result = await account.send_membership("test_password", community, "IN")
            self.assertTrue(result)

        self.lp.run_until_complete(exec_test())
Beispiel #15
0
async def test_first_time_call(app_context):
    """Test first time call. No entry in the store yet.
    """
    request = MagicMock(return_value={"headers": MagicMock()})
    with patch("decorators.rate_limit.request", request) as mock_request:
        mock_request.headers.__getitem__.return_value = "abc"
        with patch("decorators.rate_limit.RedisStore",
                   MagicMock()) as mock_redis:
            # Mock no record in redis
            mock_redis_get = (mock_redis.return_value.__aenter__.return_value.
                              get) = CoroutineMock(side_effect=[None])

            mock_redis_set = (mock_redis.return_value.__aenter__.return_value.
                              set) = CoroutineMock()
            mock_redis_incr = (mock_redis.return_value.__aenter__.return_value.
                               mock_redis_incr) = CoroutineMock()

            mock_endpoint_func = CoroutineMock(side_effect=[200])

            wrapped = rate_limit(1, 5)(mock_endpoint_func)
            result = await wrapped()

            assert mock_redis.call_count == 1
            assert mock_redis_get.call_count == 1
            assert mock_redis_set.call_count == 1
            assert mock_redis_incr.call_count == 0
            assert mock_endpoint_func.call_count == 1
            assert result == 200
Beispiel #16
0
async def test_get_nlu_data(Faker: asynctest.MagicMock, load_data: asynctest.MagicMock) -> None:
    faker_ = Faker()
    faker_.name.return_value = "Nikola Tesla"
    training_data = TrainingData(
        training_examples=[
            Message.build("hello", "intent_test"),
            Message.build("hello @name", "intent_test"),
            Message.build("hello"),
        ]
    )
    load_data.return_value = training_data

    importer = PlaceholderImporter()
    importer.config = {"importers": [{"name": "rasam.PlaceholderImporter"}]}
    importer._nlu_files = ["test"]
    new_training_data = await importer.get_nlu_data()

    faker_.seed_instance.assert_called_once_with(importer.DEFAULT_FAKE_DATA_COUNT)
    load_data.assert_called_once_with("test", "en")
    message: Message
    expected_messages = [
        Message.build("hello", "intent_test"),
        Message.build("hello Nikola Tesla", "intent_test"),
        Message.build("hello"),
    ]
    for message, expected in zip(new_training_data.training_examples, expected_messages):
        assert message.get("intent") == expected.get("intent")
        assert message.get("text") == expected.get("text")
    def setUp(self) -> None:
        pub_key = "a04f30a45aae413d0ca0f219b4dcb7049857bc3f91a6351288cce603a2c9646294a02b987bf6586b370b2c22d74662355677007a14238bb037aedf41c2d08866"
        opts = gateway_helpers.get_gateway_opts(8000, pub_key=pub_key)

        node_ssl_service = MockNodeSSLService(EthGatewayNode.NODE_TYPE,
                                              MagicMock())
        self.node = EthGatewayNode(opts, node_ssl_service)
        self.relay_1 = MockNode(
            helpers.get_common_opts(8000, region="us-east-1"))
        self.relay_connection_1 = helpers.create_connection(
            EthRelayConnection,
            self.node,
            node_opts=self.relay_1.opts,
            file_no=1,
            ip="1.2.3.4")

        self.relay_2 = MockNode(
            helpers.get_common_opts(8001, region="eu-west-1"))
        self.relay_connection_2 = helpers.create_connection(
            EthRelayConnection,
            self.node,
            node_opts=self.relay_2.opts,
            file_no=1,
            ip="1.2.3.5")
        self.node.broadcast = MagicMock()
        self.node.has_active_blockchain_peer = MagicMock(return_value=True)
Beispiel #18
0
def _create_mocked_owm(is_api_online: bool):
    mocked_owm = MagicMock()
    mocked_owm.is_API_online.return_value = is_api_online

    weather = MagicMock()
    weather.get_temperature.return_value.get.return_value = 10
    weather.get_pressure.return_value.get.return_value = 10
    weather.get_humidity.return_value = 10
    weather.get_wind.return_value.get.return_value = 0
    weather.get_clouds.return_value = "clouds"
    weather.get_rain.return_value = []
    weather.get_snow.return_value = 3
    weather.get_detailed_status.return_value = "status"
    weather.get_weather_code.return_value = 803

    mocked_owm.weather_at_coords.return_value.get_weather.return_value = weather

    one_day_forecast = MagicMock()
    one_day_forecast.get_reference_time.return_value = 10
    one_day_forecast.get_temperature.return_value.get.return_value = 10
    one_day_forecast.get_rain.return_value.get.return_value = 0
    one_day_forecast.get_snow.return_value.get.return_value = 0
    one_day_forecast.get_wind.return_value.get.return_value = 0
    one_day_forecast.get_weather_code.return_value = 803

    mocked_owm.three_hours_forecast_at_coords.return_value.get_forecast.return_value.get_weathers.return_value = [
        one_day_forecast
    ]

    return mocked_owm
Beispiel #19
0
async def test_get_with_retries(mock_sleep):
    getfcn = CoroutineMock()
    getfcn.side_effect = [
        aiohttp.ClientResponseError(MagicMock(), MagicMock())] * 4 + ['hi']
    res = await nwp.get_with_retries(getfcn, retries=5)
    assert res == 'hi'
    assert getfcn.await_count == 5
    def setUp(self):
        TestAnnouncementBase.setUp(self)

        self.mock_role = create_mock_role(12345, "MyRole")

        self.member_thumbs_up1 = create_mock_user()
        self.member_thumbs_up2 = create_mock_user()
        self.member_shrug_1 = create_mock_user()
        self.member_shrug_2 = create_mock_user()

        mock_reaction_1 = create_mock_reaction(
            "👍", members=[self.member_thumbs_up1, self.member_thumbs_up2])
        mock_reaction_2 = create_mock_reaction(
            "🤷", members=[self.member_shrug_1, self.member_shrug_2])

        self.mock_message_to_edit = create_mock_message(
            "the message",
            "the chan",
            reactions=[mock_reaction_1, mock_reaction_2])

        add_reaction_mock = MagicMock(return_value=Future())
        add_reaction_mock.return_value.set_result(None)
        type(self.mock_message_to_edit).add_reaction = add_reaction_mock

        remove_reaction_mock = MagicMock(return_value=Future())
        remove_reaction_mock.return_value.set_result(None)
        type(self.mock_message_to_edit).remove_reaction = remove_reaction_mock

        self.mock_discord_service.get_matching_message = MagicMock(
            return_value=Future())
        self.mock_discord_service.get_matching_message.return_value.set_result(
            self.mock_message_to_edit)
Beispiel #21
0
async def test_special_kwargs_added(fn):
    fn = MagicMock(fn)
    cause = MagicMock(
        body={'metadata': {
            'uid': 'uid',
            'name': 'name',
            'namespace': 'ns'
        }})
    await invoke(fn, cause=cause)

    assert fn.called
    assert fn.call_count == 1

    assert len(fn.call_args[1]) >= 2
    assert fn.call_args[1]['cause'] is cause
    assert fn.call_args[1]['event'] is cause.event
    assert fn.call_args[1]['body'] is cause.body
    assert fn.call_args[1]['spec'] is cause.body['spec']
    assert fn.call_args[1]['meta'] is cause.body['metadata']
    assert fn.call_args[1]['status'] is cause.body['status']
    assert fn.call_args[1]['diff'] is cause.diff
    assert fn.call_args[1]['old'] is cause.old
    assert fn.call_args[1]['new'] is cause.new
    assert fn.call_args[1]['patch'] is cause.patch
    assert fn.call_args[1]['logger'] is cause.logger
    assert fn.call_args[1]['uid'] is cause.body['metadata']['uid']
    assert fn.call_args[1]['name'] is cause.body['metadata']['name']
    assert fn.call_args[1]['namespace'] is cause.body['metadata']['namespace']
Beispiel #22
0
    def test_ensure_connection(self):
        mock = MagicMock(foo=MagicMock(), _db=None)

        ensure_connection(mock.foo)(mock)

        mock.connect.assert_called_once()
        mock.foo.assert_called_once()
Beispiel #23
0
def _get_mock_tado_api(getMe=None):
    mock_tado = MagicMock()
    if isinstance(getMe, Exception):
        type(mock_tado).getMe = MagicMock(side_effect=getMe)
    else:
        type(mock_tado).getMe = MagicMock(return_value=getMe)
    return mock_tado
Beispiel #24
0
async def test_next_time_call(app_context):
    """Test a call within a good rate limit.
    """
    request = MagicMock(return_value={"headers": MagicMock()})
    with patch("decorators.rate_limit.request", request) as mock_request:
        mock_request.headers.__getitem__.return_value = "abc"
        with patch("decorators.rate_limit.RedisStore",
                   MagicMock()) as mock_redis:
            # Mock a record in redis with a current counter set to 1
            mock_redis_get = (mock_redis.return_value.__aenter__.return_value.
                              get) = CoroutineMock(side_effect=[1])

            mock_redis_set = (mock_redis.return_value.__aenter__.return_value.
                              set) = CoroutineMock()
            mock_redis_incr = (mock_redis.return_value.__aenter__.return_value.
                               incr) = CoroutineMock()

            mock_endpoint_func = CoroutineMock(side_effect=[200])

            wrapped = rate_limit(2, 5)(mock_endpoint_func)

            result = await wrapped()

            assert mock_redis.call_count == 1
            assert mock_redis_get.call_count == 1
            assert mock_redis_set.call_count == 0
            assert mock_redis_incr.call_count == 1
            assert mock_endpoint_func.call_count == 1
            assert result == 200
Beispiel #25
0
def client(client_class):
    client = AsyncMock()
    client_class.return_value = client

    if sys.version_info[:2] < (3, 8):
        client.read_gatt_char = CoroutineMock()
        client.write_gatt_char = CoroutineMock()

    connected = False

    async def is_connected():
        nonlocal connected
        return connected

    async def connect():
        nonlocal connected
        connected = True

    async def disconnect():
        nonlocal connected
        connected = False

    client.is_connected.side_effect = is_connected
    client.connect.side_effect = connect
    client.disconnect.side_effect = disconnect

    yield client
Beispiel #26
0
 async def test_post_item(self):
     api_res = {"_type" : "Tik::Model::Event", "local_id":"xyz"}
     self.client._post =  asynctest.CoroutineMock(return_value=api_res)
     post = MagicMock()
     post.images = []
     post.content = "Test"
     resp = await self.client.post_item(post)
     assert resp == api_res
Beispiel #27
0
 def setUp(self):
     config = module.Config(api_endpoint="core.irma")
     self.api = module.AAPI(config, loop=self.loop)
     self.api.ssl = "ssl"
     self.resp = MagicMock()
     self.api.session = MagicMock()
     self.api.session.get.return_value.__aenter__.return_value = self.resp
     self.api.session.post.return_value.__aenter__.return_value = self.resp
Beispiel #28
0
def withings_api_fixture() -> WithingsApi:
    """Provide withings api."""
    withings_api = WithingsApi.__new__(WithingsApi)
    withings_api.user_get_device = MagicMock()
    withings_api.measure_get_meas = MagicMock()
    withings_api.sleep_get = MagicMock()
    withings_api.sleep_get_summary = MagicMock()
    return withings_api
Beispiel #29
0
 async def test_update_item_failin(self):
     self.client.get_id_at_target = lambda x: None
     post = MagicMock()
     post.images = []
     post.content = "Test, mit Ü."
     post.target_doc = {"ts": 456}
     res = await self.client.update_item(post)
     assert res == False
Beispiel #30
0
    async def test_disconnect(self):
        mock_ws = MagicMock()
        mock_disconnect = CoroutineMock()
        mock_ws.disconnect = mock_disconnect
        self._client._ws = mock_ws

        await self._client.disconnect()

        mock_disconnect.assert_awaited_once()
Beispiel #31
0
def create_mock_message(msg_content, channel_name):
    mock_message = MagicMock()
    type(mock_message).content = PropertyMock(return_value=msg_content)

    mock_channel = MagicMock()
    type(mock_channel).name = PropertyMock(return_value=channel_name)
    type(mock_message).channel = PropertyMock(return_value=mock_channel)

    return mock_message
Beispiel #32
0
def mock_nessclient():
    """Mock the nessclient Client constructor.

    Replaces nessclient.Client with a Mock which always returns the same
    MagicMock() instance.
    """
    _mock_instance = MagicMock(MockClient())
    _mock_factory = MagicMock()
    _mock_factory.return_value = _mock_instance

    with MockDependency('nessclient'), \
        patch('nessclient.Client', new=_mock_factory, create=True), \
            patch('nessclient.ArmingState', new=MockArmingState):
        yield _mock_instance
Beispiel #33
0
    def test_send_certification(self):
        cert_signal_sent = False
        def check_certification_accepted():
            nonlocal cert_signal_sent
            cert_signal_sent = True

        account = Account("test_salt", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ",
                          "test_account", [], [], [],
                          self.identities_registry)
        account.certification_accepted.connect(check_certification_accepted)
        account_identity = MagicMock(autospec='sakia.core.registry.Identity')
        account_identity.selfcert = CoroutineMock(return_value=SelfCertification(2, "meta_brouzouf",
                                            "H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr", "test_account",
                                            BlockUID(1000, "49E2A1D1131F1496FAD6EDAE794A9ADBFA8844029675E3732D3B027ABB780243"),
                                            "82o1sNCh1bLpUXU6nacbK48HBcA9Eu2sPkL1/3c2GtDPxBUZd2U2sb7DxwJ54n6ce9G0Oy7nd1hCxN3fS0oADw=="))

        certified = MagicMock(autospec='sakia.core.registry.Identity')
        certified.uid = "john"
        certified.pubkey = "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ"
        certified.sigdate = 1441130831
        certified.selfcert = CoroutineMock(return_value=SelfCertification(2, "meta_brouzouf",
                                            "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "john",
                                            BlockUID(1200, "49E2A1D1131F1496FAD6EDAE794A9ADBFA8844029675E3732D3B027ABB780243"),
                                            "82o1sNCh1bLpUXU6nacbK48HBcA9Eu2sPkL1/3c2GtDPxBUZd2U2sb7DxwJ54n6ce9G0Oy7nd1hCxN3fS0oADw=="))

        community = MagicMock(autospec='sakia.core.Community')
        community.blockUID = CoroutineMock(return_value=BlockUID(3102, "49E2A1D1131F1496FAD6EDAE794A9ADBFA8844029675E3732D3B027ABB780243"))
        self.identities_registry.future_find = CoroutineMock(side_effect=lambda pubkey, community :account_identity \
                        if pubkey == "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ" else certified)
        community.bma_access = MagicMock(autospec='sakia.core.net.api.bma.access.BmaAccess')
        response = Mock()
        response.json = CoroutineMock(return_value={})
        response.status = 200
        community.bma_access.broadcast = CoroutineMock(return_value=[response])
        async def exec_test():
            result = await account.certify("test_password", community, "")
            self.assertTrue(result)

        self.lp.run_until_complete(exec_test())
        self.assertTrue(cert_signal_sent)
Beispiel #34
0
    def test_send_certification(self):
        cert_signal_sent = False
        def check_certification_accepted():
            nonlocal cert_signal_sent
            cert_signal_sent = True

        account = Account("test_salt", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ",
                          "test_account", [], [], [],
                          self.identities_registry)
        account.certification_accepted.connect(check_certification_accepted)
        account_identity = MagicMock(autospec='sakia.core.registry.Identity')
        account_identity.selfcert = CoroutineMock(return_value=SelfCertification(1, "meta_brouzouf",
                                            "H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr", "test_account", 1000000000, ""))

        certified = MagicMock(autospec='sakia.core.registry.Identity')
        certified.uid = "john"
        certified.pubkey = "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ"
        certified.sigdate = 1441130831
        certified.selfcert = CoroutineMock(return_value=SelfCertification(1, "meta_brouzouf",
                                            "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "john", 1441130831, ""))

        community = MagicMock(autospec='sakia.core.Community')
        community.blockid = CoroutineMock(return_value=BlockId(3102, "0000C5336F0B64BFB87FF4BC858AE25726B88175"))
        self.identities_registry.future_find = CoroutineMock(side_effect=lambda pubkey, community :account_identity \
                        if pubkey == "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ" else certified)
        community.bma_access = MagicMock(autospec='sakia.core.net.api.bma.access.BmaAccess')
        response = Mock()
        response.json = CoroutineMock(return_value={})
        response.status = 200
        community.bma_access.broadcast = CoroutineMock(return_value=[response])
        async def exec_test():
            result = await account.certify("test_password", community, "")
            self.assertTrue(result)

        self.lp.run_until_complete(exec_test())
        self.assertTrue(cert_signal_sent)
def head():
    head = MagicMock(name='HEAD')
    head.__lt__ = lambda a, b: id(a) < id(b)
    return head