def test_after_map(self):
     mock = Mock()
     self.rasa_plugin.after_map(mock)
     calls = [
         call.connect("databot_user_message", "/databot/user/message", controller="ckanext.rasa.controller:RasaPluginController", action="send_user_message"),
         call.connect("data_bot", "/databot",controller="ckanext.rasa.controller:RasaPluginController", action="databot_index")
         ]
     self.assertEqual(mock.mock_calls, calls)
Example #2
0
 def test_close(self, mysql_mock, db_, cursor_mock):
     db_.close()
     calls = [
         call.connect(host='localhost',
                      user='******',
                      password='******',
                      database='default'),
         call.connect().cursor(),
         call.connect().cursor().close(),
         call.connect().close()
     ]
     assert mysql_mock.mock_calls == calls
Example #3
0
 def test_init(self, mysql_mock):
     MySQLHelper(host='127.0.0.1',
                 user='******',
                 password='******',
                 database='test_db',
                 pooled=False)
     assert mysql_mock.mock_calls == [
         call.connect(host='127.0.0.1',
                      user='******',
                      password='******',
                      database='test_db'),
         call.connect().cursor()
     ]
Example #4
0
 def test_init_none_pghelper(self, postgresql_mock):
     PostgreSQLHelper(host=None,
                      user='******',
                      password='******',
                      database='test_db',
                      pooled=False)
     assert postgresql_mock.mock_calls == [
         call.connect(host='localhost',
                      user='******',
                      password='******',
                      database='test_db'),
         call.connect().cursor()
     ]
Example #5
0
    def install_test(self, remote_cls, installation_cls, transaction_cls):
        """Test flatpak installation is working."""
        flatpak = FlatpakPayload("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(FlatpakPayload.LOCAL_REMOTE_NAME,
                             mock_ref_list[0].format_ref(), None),
            call.add_install(FlatpakPayload.LOCAL_REMOTE_NAME,
                             mock_ref_list[1].format_ref(), None),
            call.add_install(FlatpakPayload.LOCAL_REMOTE_NAME,
                             mock_ref_list[2].format_ref(), None),
            call.add_install(FlatpakPayload.LOCAL_REMOTE_NAME,
                             mock_ref_list[3].format_ref(), None),
            call.run()
        ]

        self.assertEqual(self._transaction.mock_calls, expected_calls)
Example #6
0
 def test_init_extra_args_no_pool(self, mysql_mock):
     MySQLHelper(host='127.0.0.1',
                 user='******',
                 password='******',
                 database='test_db',
                 pooled=False,
                 database_args={"ssl_ca": "file"})
     assert mysql_mock.mock_calls == [
         call.connect(host='127.0.0.1',
                      user='******',
                      password='******',
                      database='test_db',
                      ssl_ca="file"),
         call.connect().cursor()
     ]
Example #7
0
 def test_make_socket(self, sender):
     with patch('socket.socket'):
         sock = sender._make_socket()
         assert sock.mock_calls == [
             call.settimeout(sender.timeout),
             call.connect((sender.host, sender.port))
         ]
Example #8
0
def test_conn_cached_closed(instance, sshclient):
    instance.config['host'] = 'localhost'
    instance.config['fingerprint'] = 'foo'
    first_client = MagicMock()
    first_client.get_transport.return_value = None
    second_client = MagicMock()
    sshclient.side_effect = [first_client, second_client]
    conn = instance.conn
    assert len(first_client.method_calls) == 3
    assert [x[0] for x in first_client.method_calls] == [
        'set_missing_host_key_policy',
        'connect',
        'save_host_keys']
    conn1 = instance.conn
    assert conn1 is not conn
    assert conn1 is not first_client
    assert conn1 is second_client
    assert len(first_client.method_calls) == 4
    assert [x[0] for x in first_client.method_calls] == [
        'set_missing_host_key_policy',
        'connect',
        'save_host_keys',
        'get_transport']
    assert len(second_client.method_calls) == 3
    assert second_client.method_calls[0][0] == 'set_missing_host_key_policy'
    assert second_client.method_calls[1] == call.connect('localhost', username='******', key_filename=None, password=None, sock=None, port=22)
    assert second_client.method_calls[2] == call.save_host_keys(instance.master.known_hosts)
Example #9
0
 def test_after_map(self):
     mock = Mock()
     self.rasa_plugin.after_map(mock)
     calls = [
         call.connect(
             "databot_user_message",
             "/databot/user/message",
             controller="ckanext.rasa.controller:RasaPluginController",
             action="send_user_message"),
         call.connect(
             "data_bot",
             "/databot",
             controller="ckanext.rasa.controller:RasaPluginController",
             action="databot_index")
     ]
     self.assertEqual(mock.mock_calls, calls)
Example #10
0
 def test_make_socket(self, sender):
     with patch('socket.socket'):
         sock = sender._make_socket()
         assert sock.mock_calls == [
             call.settimeout(sender.timeout),
             call.connect((sender.host, sender.port))
         ]
Example #11
0
def test_conn(instance, sshclient):
    instance.config['host'] = 'localhost'
    instance.config['fingerprint'] = 'foo'
    conn = instance.conn
    assert len(conn.method_calls) == 3
    assert conn.method_calls[0][0] == 'set_missing_host_key_policy'
    assert conn.method_calls[1] == call.connect('localhost', username='******', key_filename=None, password=None, sock=None, port=22)
    assert conn.method_calls[2] == call.save_host_keys(instance.master.known_hosts)
    def test_insert_item(self):

        self.q.insertItem(user_id=1, prj_id=2, priority=10, data="mydata")

        # Check the db call of the item insert
        insert_call = call.connect().execute(
            'insert into `test` (user_id, prj_id, priority, data) '
            'values(%s, %s, %s, %s)', [1, 2, 10, '"mydata"'])
        self.assertIn(insert_call, self.db_engine_mock.mock_calls)

        # Check the item existence and values in the in-memory queue
        priority, timestamp, item = heapq.heappop(self.q.pqueue._heap)
        self.assertEqual(-10, priority)
        self.assertEqual(item.getCreationTime(), timestamp)
        self.assertEqual(1, item.user_id)
        self.assertEqual(2, item.prj_id)
        self.assertEqual(10, item.priority)
        self.assertEqual(0, item.retry_count)
        self.assertIsNone(item.data)  # TODO(vincent): should it be "mydata"?
Example #13
0
    def test_connect_signal_function(self):
        self.disconnect_signals()
        f = FileFieldAutoDelete('file_field')
        f(self.get_model())
        self.assertEqual(len(models.signals.post_delete.receivers), 1)
        self.assertIs(models.signals.post_delete.receivers[0][1], f.get_signal_function())
        self.restore_signals()

        self.disconnect_signals()
        mock = MagicMock()
        f = FileFieldAutoDelete('file_field', signal=mock)
        m = self.get_model()
        f(m)
        self.assertEqual(len(mock.mock_calls), 1)
        self.assertEqual(mock.mock_calls[0],
                         call.connect(
                             f.get_signal_function(),
                             weak=False,
                             dispatch_uid='post_delete_Model_delete_file_field',
                             sender=m
                         ))
        self.restore_signals()
Example #14
0
def test__send__FullMessages(sock_mock):
    # The test assume that the socket is always correctly connected when
    # fileno is queried
    sock_mock().fileno.return_value = 11

    message = 'ACommandWithParameters:#P1#P2;'
    msg_reply = 'ACommandWithParameters:done;'
    sock_mock().send.return_value = len(message)
    sock_mock().recv.return_value = msg_reply.encode()

    sock_conn = SocketConnector(host='127.0.0.3', port=10006)
    reply = sock_conn.__send__(message)

    assert reply == msg_reply
    sock_calls = [
        call.connect(('127.0.0.3', 10006)),
        call.send(message.encode()),
        # call.shutdown(socket.SHUT_WR),
        call.recv(1024),
        call.fileno(),  # This from is_connected()
        call.close()
    ]
    sock_mock().assert_has_calls(sock_calls)
Example #15
0
    def test_connect(self):
        self._subject.connect()

        assert_that(self._subject._connector.mock_calls,
                    equal_to([call.connect()]))
Example #16
0
    def test_connect(self):
        self._subject.connect()

        assert_that(self._subject._sock.mock_calls,
                    equal_to([call.connect((self._subject._ip, 4998))]))
Example #17
0
class TestMySQLHelper:
    @fixture
    def mysql_mock(self, mocker):
        return mocker.patch('nova_api.persistence'
                            '.mysql_helper.mysql.connector')

    @fixture
    def raise_exception(self):
        def side_effect_func(*args, **kwargs):
            raise mysql.connector.Error(errno=1146,
                                        sqlstate='42S02',
                                        msg="Table 'test.spam' doesn't exist")

        return side_effect_func

    @fixture
    def db_(self, mysql_mock):
        return MySQLHelper(pooled=False)

    @fixture
    def cursor_mock(self, mysql_mock):
        cursor_mock = mysql_mock.connect.return_value.cursor.return_value
        cursor_mock.rowcount = 1
        cursor_mock.lastrowid = 1
        return cursor_mock

    def test_init(self, mysql_mock):
        MySQLHelper(host='127.0.0.1',
                    user='******',
                    password='******',
                    database='test_db',
                    pooled=False)
        assert mysql_mock.mock_calls == [
            call.connect(host='127.0.0.1',
                         user='******',
                         password='******',
                         database='test_db'),
            call.connect().cursor()
        ]

    def test_init_extra_args_no_pool(self, mysql_mock):
        MySQLHelper(host='127.0.0.1',
                    user='******',
                    password='******',
                    database='test_db',
                    pooled=False,
                    database_args={"ssl_ca": "file"})
        assert mysql_mock.mock_calls == [
            call.connect(host='127.0.0.1',
                         user='******',
                         password='******',
                         database='test_db',
                         ssl_ca="file"),
            call.connect().cursor()
        ]

    def test_init_pooled(self, mocker):
        pool_mock = mocker.patch("nova_api.persistence.mysql_helper.MySQLPool")
        MySQLHelper(host='127.0.0.1',
                    user='******',
                    password='******',
                    database='test_db',
                    pooled=True)
        assert pool_mock.mock_calls == [
            call.get_instance(host='127.0.0.1',
                              user='******',
                              password='******',
                              database='test_db',
                              database_args={}),
            call.get_instance().get_connection(),
            call.get_instance().get_connection().cursor()
        ]

    def test_init_pooled_extra_args(self, mocker):
        pool_mock = mocker.patch("nova_api.persistence.mysql_helper.MySQLPool")
        MySQLHelper(host='127.0.0.1',
                    user='******',
                    password='******',
                    database='test_db',
                    pooled=True,
                    database_args={"ssl_ca": "file"})
        assert pool_mock.mock_calls == [
            call.get_instance(host='127.0.0.1',
                              user='******',
                              password='******',
                              database='test_db',
                              database_args={"ssl_ca": "file"}),
            call.get_instance().get_connection(),
            call.get_instance().get_connection().cursor()
        ]

    def test_init_none(self, mysql_mock):
        MySQLHelper(host=None,
                    user='******',
                    password='******',
                    database='test_db',
                    pooled=False)
        assert mysql_mock.mock_calls == [
            call.connect(host='localhost',
                         user='******',
                         password='******',
                         database='test_db'),
            call.connect().cursor()
        ]

    @mark.parametrize(
        "query, params, calls",
        [("SELECT * FROM teste;", None,
          [call.connect().cursor().execute("SELECT * FROM teste;")]),
         ("SELECT * FROM teste WHERE id=%s;", [1], [
             call.connect().cursor().execute(
                 "SELECT * FROM teste WHERE id=%s;", [1])
         ]),
         ("INSERT INTO t (a) VALUES (%s);", [1], [
             call.connect().cursor().execute("INSERT INTO t (a) VALUES (%s);",
                                             [1]),
             call.connect().commit()
         ]),
         ("DELETE FROM t;", [1], [
             call.connect().cursor().execute("DELETE FROM t;", [1]),
             call.connect().commit()
         ]),
         ("UPDATE t SET a=%s;", [1], [
             call.connect().cursor().execute("UPDATE t SET a=%s;", [1]),
             call.connect().commit()
         ])])
    def test_query(self, mysql_mock, cursor_mock, query, params, calls, db_):
        row_count, last_id = db_.query(query, params)
        assert ([call_
                 for call_ in calls if call_ in mysql_mock.mock_calls] == calls
                and row_count == 1 and last_id == 1)

    @mark.parametrize("results, returned", [([], None),
                                            ([[1, 2, 3]], [[1, 2, 3]])])
    def test_get_results(self, mysql_mock, cursor_mock, results, returned,
                         db_):
        cursor_mock.fetchall.return_value = results
        assert db_.get_results() == returned

    def test_close(self, mysql_mock, db_, cursor_mock):
        db_.close()
        calls = [
            call.connect(host='localhost',
                         user='******',
                         password='******',
                         database='default'),
            call.connect().cursor(),
            call.connect().cursor().close(),
            call.connect().close()
        ]
        assert mysql_mock.mock_calls == calls

    @mark.parametrize("exception_type", [ValueError, InterfaceError])
    def test_fail_init(self, mysql_mock, exception_type):
        def raise_exception(*args, **kwargs):
            raise exception_type()

        mysql_mock.connect.side_effect = raise_exception

        with raises(ConnectionError):
            db_ = MySQLHelper(pooled=False)

    @mark.parametrize("exception_type", [InterfaceError, DatabaseError, Error])
    def test_fail_query(self, mysql_mock, db_, exception_type):
        def raise_exception(*args, **kwargs):
            raise exception_type()

        cursor_mock = mysql_mock.connect.return_value.cursor.return_value
        cursor_mock.execute.side_effect = raise_exception

        with raises(RuntimeError):
            db_.query("SELECT * FROM table")

    @mark.parametrize("exception_type", [InterfaceError, DatabaseError, Error])
    def test_fail_get_results(self, mysql_mock, db_, exception_type):
        def raise_exception(*args, **kwargs):
            raise exception_type()

        cursor_mock = mysql_mock.connect.return_value.cursor.return_value
        cursor_mock.fetchall.side_effect = raise_exception

        with raises(RuntimeError):
            db_.get_results()

    @mark.parametrize("cls, type_", [(bool, "TINYINT(1)"),
                                     (datetime, "DATETIME"),
                                     (str, "VARCHAR(100)"), (int, "INT"),
                                     (float, "DECIMAL"), (date, "DATE"),
                                     (TestEntity, "CHAR(32)")])
    def test_predict_db_type(self, cls, type_, mysql_mock):
        helper = MySQLHelper(pooled=False)
        assert helper.predict_db_type(cls) == type_