def test_install(self, remote_cls, installation_cls, transaction_cls):
        """Test flatpak installation is working."""
        progress = Mock()
        flatpak = FlatpakManager(sysroot="remote/path", callback=progress)

        self._setup_flatpak_objects(remote_cls, installation_cls,
                                    transaction_cls)
        flatpak.initialize_with_system_path()

        self._installation.list_remote_refs_sync.return_value = [
            RefMock("app/org.space.coolapp/x86_64/stable"),
            RefMock("app/com.prop.notcoolapp/i386/f36"),
            RefMock("runtime/org.space.coolruntime/x86_64/stable"),
            RefMock("runtime/com.prop.notcoolruntime/i386/f36"),
        ]

        flatpak.install_all()
        assert self._transaction.mock_calls == [
            call.connect("new_operation", flatpak._operation_started_callback),
            call.connect("operation_done",
                         flatpak._operation_stopped_callback),
            call.connect("operation_error", flatpak._operation_error_callback),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             "app/org.space.coolapp/x86_64/stable", None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             "app/com.prop.notcoolapp/i386/f36", None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             "runtime/org.space.coolruntime/x86_64/stable",
                             None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             "runtime/com.prop.notcoolruntime/i386/f36", None),
            call.run()
        ]

        assert progress.mock_calls == []
Exemple #2
0
async def test_notify(hass, client):
    """Test sending a message."""
    await setup_webostv(hass)
    assert hass.services.has_service(NOTIFY_DOMAIN, TV_NAME)

    await hass.services.async_call(
        NOTIFY_DOMAIN,
        TV_NAME,
        {
            ATTR_MESSAGE: MESSAGE,
            CONF_SERVICE_DATA: {
                CONF_ICON: ICON_PATH,
            },
        },
        blocking=True,
    )
    assert client.mock_calls[0] == call.connect()
    assert client.connect.call_count == 1
    client.send_message.assert_called_with(MESSAGE, icon_path=ICON_PATH)

    await hass.services.async_call(
        NOTIFY_DOMAIN,
        TV_NAME,
        {
            ATTR_MESSAGE: MESSAGE,
            CONF_SERVICE_DATA: {
                "OTHER_DATA": "not_used",
            },
        },
        blocking=True,
    )
    assert client.mock_calls[0] == call.connect()
    assert client.connect.call_count == 1
    client.send_message.assert_called_with(MESSAGE, icon_path=None)
 def test_post_load_auxiliary_data(self):
     with cast(BinaryIO, (DATA_DIR / 'saml_response.xml').open('rb')) as f:
         saml_request_xml = f.read()
     self.cache_mock.get_and_remove.return_value = "{}"
     response = self.client.post(self.url, {'SAMLResponse': b64encode(saml_request_xml).decode('ascii'),
                                            'RelayState': 'relay123'})
     self.assertEqual(response.status_code, 200)
     self.maxDiff = None
     self.assertSequenceEqual(self.client_mock.mock_calls[:4], [
         call.connect('test.example.net', 1234),
         call.get_cache('aux-cache'),
         call.get_cache().get_and_remove('aux-test-saml-request-id'),
         call.connect('test.example.net', 1234)])
Exemple #4
0
    def test_install(self, remote_cls, installation_cls, transaction_cls):
        """Test flatpak installation is working."""
        flatpak = FlatpakManager("remote/path")

        self._setup_flatpak_objects(remote_cls, installation_cls,
                                    transaction_cls)

        flatpak.initialize_with_system_path()

        mock_ref_list = [
            RefMock(name="org.space.coolapp",
                    kind=RefKind.APP,
                    arch="x86_64",
                    branch="stable"),
            RefMock(name="com.prop.notcoolapp",
                    kind=RefKind.APP,
                    arch="i386",
                    branch="f36"),
            RefMock(name="org.space.coolruntime",
                    kind=RefKind.RUNTIME,
                    arch="x86_64",
                    branch="stable"),
            RefMock(name="com.prop.notcoolruntime",
                    kind=RefKind.RUNTIME,
                    arch="i386",
                    branch="f36")
        ]

        self._installation.list_remote_refs_sync.return_value = mock_ref_list

        flatpak.install_all()

        expected_calls = [
            call.connect("new_operation", flatpak._operation_started_callback),
            call.connect("operation_done",
                         flatpak._operation_stopped_callback),
            call.connect("operation_error", flatpak._operation_error_callback),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             mock_ref_list[0].format_ref(), None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             mock_ref_list[1].format_ref(), None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             mock_ref_list[2].format_ref(), None),
            call.add_install(FlatpakManager.LOCAL_REMOTE_NAME,
                             mock_ref_list[3].format_ref(), None),
            call.run()
        ]

        assert self._transaction.mock_calls == expected_calls
Exemple #5
0
    def test_split_on_semicolon(self, oracle: MagicMock):
        self.adapter.acquire_connection('test_semicolon')

        query1 = "SELECT * FROM DUAL"
        query2 = "SELECT 'TEST' FROM DUAL"
        multi_query = f'{query1};\n{query2}'

        oracle.connect.assert_not_called()
        self.adapter.execute(multi_query)
        oracle.assert_has_calls(
            [
                call.connect().cursor().execute(query1),
                call.connect().cursor().execute(query2)
            ],
            any_order=True
        )
Exemple #6
0
 def test_pop_light_response_not_found(self):
     self.cache_mock.get_and_remove.return_value = None
     self.assertIsNone(self.storage.pop_light_response('abc'))
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache(self.RESPONSE_CACHE_NAME),
         call.get_cache().get_and_remove('abc')
     ])
Exemple #7
0
 def test_put_without_prefix(self):
     storage = AuxiliaryIgniteStorage(self.HOST, self.PORT, self.CACHE_NAME,
                                      33)
     storage.put('abc', {"foo": True})
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache(self.CACHE_NAME),
         call.get_cache().put('abc', '{"foo": true}')
     ])
Exemple #8
0
 def test_get_cache_single_client_created(self):
     storage = AuxiliaryIgniteStorage(self.HOST, self.PORT, self.CACHE_NAME,
                                      33, self.PREFIX)
     self.assertIs(storage.get_cache("cache1"), self.cache_mock)
     self.assertIs(storage.get_cache("cache2"), self.cache_mock)
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache("cache1"),
         call.get_cache("cache2")
     ])
Exemple #9
0
 def test_get_cache_single_client_created(self):
     self.assertIs(self.storage.get_cache(self.REQUEST_CACHE_NAME),
                   self.cache_mock)
     self.assertIs(self.storage.get_cache(self.RESPONSE_CACHE_NAME),
                   self.cache_mock)
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache(self.REQUEST_CACHE_NAME),
         call.get_cache(self.RESPONSE_CACHE_NAME)
     ])
Exemple #10
0
 def test_pop_without_prefix(self):
     self.cache_mock.get_and_remove.return_value = '{"foo": true}'
     storage = AuxiliaryIgniteStorage(self.HOST, self.PORT, self.CACHE_NAME,
                                      33)
     self.assertEqual(storage.pop('abc'), {"foo": True})
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache(self.CACHE_NAME),
         call.get_cache().get_and_remove('abc')
     ])
Exemple #11
0
 def test_pop_not_found(self):
     self.cache_mock.get_and_remove.return_value = None
     storage = AuxiliaryIgniteStorage(self.HOST, self.PORT, self.CACHE_NAME,
                                      33, self.PREFIX)
     self.assertIsNone(storage.pop('abc'))
     self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
     self.assertEqual(self.client_mock.mock_calls, [
         call.connect(self.HOST, self.PORT),
         call.get_cache(self.CACHE_NAME),
         call.get_cache().get_and_remove('test-prefix-abc')
     ])
Exemple #12
0
    def test_connect(self):
        self.assertEqual([
            call.getaddrinfo('hal', 6600, self._socket_api.AF_UNSPEC,
                             self._socket_api.SOCK_STREAM),
            call.socket(sentinel.family, sentinel.socket_type, sentinel.proto),
        ], self._socket_api.method_calls)

        self.assertEqual([
            call.connect(sentinel.socket_address),
            call.makefile(mode='r', encoding='utf-8'),
            call.makefile(mode='w', encoding='utf-8'),
        ], self._socket_object.method_calls)
    def test_post_remember_country_codes(self):
        request = LightRequest(**LIGHT_REQUEST_DICT)
        self.cache_mock.get_and_remove.return_value = dump_xml(request.export_xml()).decode('utf-8')

        token, encoded = self.get_token()
        response = self.client.post(self.url, {'test_token': encoded})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            self.client_mock.mock_calls,
            [
                call.connect('test.example.net', 1234),
                call.get_cache('test-proxy-service-request-cache'),
                call.get_cache().get_and_remove('request-token-id'),
                call.connect('test.example.net', 1234),
                call.get_cache('aux-cache'),
                call.get_cache().put(
                    'aux-test-light-request-id',
                    '{"citizen_country": "CA", "origin_country": "CA"}'
                ),
            ]
        )
Exemple #14
0
    def test_complex_semicolon_split(self, oracle: MagicMock):
        self.adapter.acquire_connection('test_semicolon')

        query1 = "--SELECT * FROM DUAL;SELECT 'A' FROM DUAL WHERE 1 = 0;;;"
        query2 = "SELECT 'TEST' FROM DUAL"
        query3 = "SELECT 'A' FROM DUAL"
        query4 = "UNION ALL SELECT 'B' FROM DUAL"

        first_query = f'{query1};\n{query2}'
        second_query = f'{query3} {query4}'
        multi_query = f'{first_query};\n{second_query}'

        oracle.connect.assert_not_called()
        self.adapter.execute(multi_query)
        oracle.assert_has_calls(
            [
                call.connect().cursor().execute(first_query),
                call.connect().cursor().execute(second_query)
            ],
            any_order=True
        )
    def test_post_remember_name_id_format(self):
        request = LightRequest(**LIGHT_REQUEST_DICT)
        self.cache_mock.get_and_remove.return_value = dump_xml(request.export_xml()).decode('utf-8')

        token, encoded = self.get_token()
        response = self.client.post(self.url, {'test_token': encoded})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            self.client_mock.mock_calls,
            [
                call.connect('test.example.net', 1234),
                call.get_cache('test-proxy-service-request-cache'),
                call.get_cache().get_and_remove('request-token-id'),
                call.connect('test.example.net', 1234),
                call.get_cache('aux-cache'),
                call.get_cache().put(
                    'aux-test-light-request-id',
                    '{"name_id_format": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"}'
                ),
            ]
        )
Exemple #16
0
    def test_put_light_response(self):
        with cast(TextIO, (DATA_DIR / 'light_response.xml').open('r')) as f:
            data = f.read()

        response = LightResponse.load_xml(parse_xml(data))
        self.storage.put_light_response('abc', response)
        self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
        self.assertEqual(self.client_mock.mock_calls, [
            call.connect(self.HOST, self.PORT),
            call.get_cache(self.RESPONSE_CACHE_NAME),
            call.get_cache().put('abc', data)
        ])
Exemple #17
0
    def test_pop_light_response_found(self):
        with cast(BinaryIO, (DATA_DIR / 'light_response.xml').open('rb')) as f:
            data = f.read()

        self.cache_mock.get_and_remove.return_value = data.decode('utf-8')
        self.assertEqual(LightResponse.load_xml(parse_xml(data)),
                         self.storage.pop_light_response('abc'))
        self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=33)])
        self.assertEqual(self.client_mock.mock_calls, [
            call.connect(self.HOST, self.PORT),
            call.get_cache(self.RESPONSE_CACHE_NAME),
            call.get_cache().get_and_remove('abc')
        ])
    def test_add_cbs_code(self, mock_datastore):
        mock_datastore.return_value.query.return_value = [
            pd.Series(["1234", "BU03630001", "Centrum"])
        ]
        enricher = GebiedenEnricher("app", "gebieden", "buurten")

        enricher._add_cbs_code(self.entities[0], CBS_CODES_BUURT, 'buurt')

        mock_datastore.has_calls(
            [call.connect(), call.query(''),
             call.disconnect()])
        # Expect cbs codes buurt
        self.assertEqual('BU03630001', self.entities[0]['cbs_code'])
Exemple #19
0
 def test_connect_fail(self):
     psycopg2_mock = Mock()
     psycopg2_mock.OperationalError = psycopg2.OperationalError
     psycopg2_mock.connect.side_effect = psycopg2.OperationalError()
     with patch.multiple('pgsqldoc.pgsqldoc',
                         psycopg2=psycopg2_mock,
                         output=DEFAULT) as mock:
         with self.assertRaises(psycopg2.OperationalError):
             Preprocessor._connect(self.preprocessor, self.options)
         psycopg2_mock.assert_has_calls([call.connect(self.connect_string)])
         self.assertTrue(mock['output'].called)
         self.assertIsNone(self.preprocessor._con)
         # logger was called 2 times: first 'Trying to connect'
         # second 'Failed to connect'
         self.assertEqual(self.preprocessor.logger.debug.call_count, 2)
    def test_post_load_auxiliary_data(self):
        self.maxDiff = None
        light_response = self.get_light_response()
        self.cache_mock.get_and_remove.side_effect = [
            dump_xml(light_response.export_xml()).decode('utf-8'),
            "{}",
        ]

        token, encoded = self.get_token()
        response = self.client.post(self.url, {'test_response_token': encoded})
        self.assertEqual(response.status_code, 200)
        self.maxDiff = None
        self.assertSequenceEqual(self.client_mock.mock_calls[-3:], [
            call.connect('test.example.net', 1234),
            call.get_cache('aux-cache'),
            call.get_cache().get_and_remove('aux-test-saml-request-id')
        ])
    def test_get_light_request_success(self):
        orig_light_request = LightRequest(**LIGHT_REQUEST_DICT)
        self.cache_mock.get_and_remove.return_value = dump_xml(orig_light_request.export_xml()).decode('utf-8')
        token, encoded = self.get_token()

        view = ProxyServiceRequestView()
        view.request = self.factory.post(self.url, {'test_token': encoded})
        view.light_token = token
        view.storage = IgniteStorage('test.example.net', 1234, 'test-proxy-service-request-cache', '')

        light_request = view.get_light_request()
        self.assertEqual(light_request, orig_light_request)
        self.maxDiff = None
        self.assertEqual(self.client_mock.mock_calls,
                         [call.connect('test.example.net', 1234),
                          call.get_cache('test-proxy-service-request-cache'),
                          call.get_cache().get_and_remove('request-token-id')])
Exemple #22
0
async def test_notify_not_connected(hass, client, monkeypatch):
    """Test sending a message when client is not connected."""
    await setup_webostv(hass)
    assert hass.services.has_service(NOTIFY_DOMAIN, TV_NAME)

    monkeypatch.setattr(client, "is_connected", Mock(return_value=False))
    await hass.services.async_call(
        NOTIFY_DOMAIN,
        TV_NAME,
        {
            ATTR_MESSAGE: MESSAGE,
            CONF_SERVICE_DATA: {
                CONF_ICON: ICON_PATH,
            },
        },
        blocking=True,
    )
    assert client.mock_calls[0] == call.connect()
    assert client.connect.call_count == 2
    client.send_message.assert_called_with(MESSAGE, icon_path=ICON_PATH)
    def test_get_light_response_success(self):
        orig_light_response = self.get_light_response()
        self.cache_mock.get_and_remove.return_value = dump_xml(
            orig_light_response.export_xml()).decode('utf-8')
        token, encoded = self.get_token()

        view = ConnectorResponseView()
        view.request = self.factory.post(self.url, {'test_token': encoded})
        view.light_token = token
        view.storage = IgniteStorage('test.example.net', 1234, '',
                                     'test-connector-response-cache')

        light_response = view.get_light_response()
        self.assertEqual(light_response, orig_light_response)
        self.maxDiff = None
        self.assertEqual(self.client_mock.mock_calls, [
            call.connect('test.example.net', 1234),
            call.get_cache('test-connector-response-cache'),
            call.get_cache().get_and_remove('response-token-id')
        ])
    def test_post_success(self, uuid_mock: MagicMock):
        with cast(BinaryIO, (DATA_DIR / 'saml_response.xml').open('rb')) as f:
            saml_request_xml = f.read()

        response = self.client.post(self.url, {'SAMLResponse': b64encode(saml_request_xml).decode('ascii'),
                                               'RelayState': 'relay123'})

        # Context
        self.assertIn('token', response.context)
        self.assertEqual(response.context['token_parameter'], 'test_token')
        self.assertEqual(response.context['eidas_url'], 'https://test.example.net/SpecificProxyServiceResponse')
        self.assertEqual(response.context['error'], None)

        # Token
        encoded_token = response.context['token']
        token = LightToken.decode(encoded_token, 'sha256', 'response-token-secret')
        self.assertEqual(token.id, 'T0uuid4')
        self.assertEqual(token.issuer, 'response-token-issuer')
        self.assertEqual(token.created, datetime(2017, 12, 11, 14, 12, 5))

        # Storing light response
        light_response_data = LIGHT_RESPONSE_DICT.copy()
        light_response_data.update({
            'status': Status(**light_response_data['status']),
            'id': 'test-saml-response-id',  # Preserved
            'in_response_to_id': 'test-saml-request-id',  # Preserved
            'issuer': 'https://test.example.net/node-proxy-service-response',  # Replaced
        })
        light_response = LightResponse(**light_response_data)
        self.assertEqual(self.client_class_mock.mock_calls, [call(timeout=66)])
        self.assertEqual(self.client_mock.mock_calls,
                         [call.connect('test.example.net', 1234),
                          call.get_cache('test-proxy-service-response-cache'),
                          call.get_cache().put('T0uuid4', dump_xml(light_response.export_xml()).decode('utf-8'))])

        # Rendering
        self.assertContains(response, 'Redirect to eIDAS Node is in progress')
        self.assertContains(response,
                            '<form class="auto-submit" action="https://test.example.net/SpecificProxyServiceResponse"')
        self.assertContains(response, '<input type="hidden" name="test_token" value="{}"'.format(encoded_token))
        self.assertNotIn(b'An error occurred', response.content)
Exemple #25
0
def test_amqp_failure(srv, caplog):
    module = load_module_by_name("mqttwarn.services.amqp")

    exchange, routing_key = ["name_of_exchange", "my_routing_key"]
    item = Item(
        config={"uri": "amqp://*****:*****@localhost:5672/"},
        target="test",
        addrs=[exchange, routing_key],
        message="⚽ Notification message ⚽",
    )

    with caplog.at_level(logging.DEBUG):

        mock_connection = mock.MagicMock()

        # Make the call to `basic_publish` raise an exception.
        def error(*args, **kwargs):
            raise Exception("something failed")

        mock_connection.basic_publish = error

        with mock.patch("puka.Client",
                        side_effect=[mock_connection],
                        create=True) as mock_client:

            outcome = module.plugin(srv, item)

            assert mock_client.mock_calls == [
                mock.call("amqp://*****:*****@localhost:5672/"),
            ]
            assert mock_connection.mock_calls == [
                call.connect(),
                call.wait(mock.ANY),
            ]

            assert outcome is False
            assert ("AMQP publish to test [name_of_exchange/my_routing_key]"
                    in caplog.text)
            assert (
                "Error on AMQP publish to test [name_of_exchange/my_routing_key]: something failed"
                in caplog.text)
Exemple #26
0
async def test_icon_not_found(hass, caplog, client, monkeypatch):
    """Test notify icon not found error."""
    await setup_webostv(hass)
    assert hass.services.has_service(NOTIFY_DOMAIN, TV_NAME)

    monkeypatch.setattr(client, "send_message",
                        Mock(side_effect=FileNotFoundError))
    await hass.services.async_call(
        NOTIFY_DOMAIN,
        TV_NAME,
        {
            ATTR_MESSAGE: MESSAGE,
            CONF_SERVICE_DATA: {
                CONF_ICON: ICON_PATH,
            },
        },
        blocking=True,
    )
    assert client.mock_calls[0] == call.connect()
    assert client.connect.call_count == 1
    client.send_message.assert_called_with(MESSAGE, icon_path=ICON_PATH)
    assert f"Icon {ICON_PATH} not found" in caplog.text
Exemple #27
0
async def test_connection_errors(hass, caplog, client, monkeypatch,
                                 side_effect, error):
    """Test connection errors scenarios."""
    await setup_webostv(hass)
    assert hass.services.has_service("notify", TV_NAME)

    monkeypatch.setattr(client, "is_connected", Mock(return_value=False))
    monkeypatch.setattr(client, "connect", Mock(side_effect=side_effect))
    await hass.services.async_call(
        NOTIFY_DOMAIN,
        TV_NAME,
        {
            ATTR_MESSAGE: MESSAGE,
            CONF_SERVICE_DATA: {
                CONF_ICON: ICON_PATH,
            },
        },
        blocking=True,
    )
    assert client.mock_calls[0] == call.connect()
    assert client.connect.call_count == 1
    client.send_message.assert_not_called()
    assert error in caplog.text
    def test_post_remember_country_codes(self, uuid_mock):
        self.maxDiff = None
        saml_request_xml, saml_request_encoded = self.load_saml_request(
            signed=True)
        light_request = LightRequest(**LIGHT_REQUEST_DICT)
        light_request.issuer = 'https://example.net/EidasNode/ConnectorMetadata'
        self.cache_mock.get_and_remove.return_value = dump_xml(
            light_request.export_xml()).decode('utf-8')

        response = self.client.post(
            self.url, {
                'SAMLRequest': saml_request_encoded,
                'RelayState': 'relay123',
                'country_param': 'ca'
            })
        self.assertEqual(response.status_code, 200)
        self.assertSequenceEqual(self.client_mock.mock_calls[-3:], [
            call.connect('test.example.net', 1234),
            call.get_cache('aux-cache'),
            call.get_cache().put(
                'aux-test-saml-request-id',
                '{"citizen_country": "CA", "origin_country": "CA"}'),
        ])
  def test_active_ssh_session(self):
    ssh = MagicMock()
    credentials = {
      'username': '******',
      'hostname': 'host',
      'port': 1234,
      'pkey': 'key',
    }

    self.assertEqual(
      first=ssh,
      second=active_ssh_session(ssh=ssh, credentials=credentials),
      msg='Returns the ssh object passed'
    )
    self.assertIn(
      member=call.connect(
        username=credentials['username'],
        hostname=credentials['hostname'],
        port=credentials['port'],
        pkey=credentials['pkey']
      ),
      container=ssh.mock_calls,
      msg='Connects the ssh object using the ssh credentials passed'
    )
Exemple #30
0
 def test_connect_success(self):
     with patch('pgsqldoc.pgsqldoc.psycopg2') as mock:
         Preprocessor._connect(self.preprocessor, self.options)
         mock.assert_has_calls([call.connect(self.connect_string)])
         self.assertIsNotNone(self.preprocessor._con)