def test_dates(self):
        """examples/dates.py"""
        try:
            import examples.dates as example
        except Exception as err:
            self.fail(err)
        output = example.main(tests.get_mysql_config())
        exp = ['  1 | 1977-06-14 | 1977-06-14 21:10:00 | 21:10:00 |',
               '  2 |       None |                None |  0:00:00 |',
               '  3 |       None |                None |  0:00:00 |']
        self.assertEqual(output, exp)

        example.DATA.append(('0000-00-00', None, '00:00:00'),)
        self.assertRaises(mysql.connector.errors.IntegrityError,
                          example.main, tests.get_mysql_config())
    def test_connect(self):
        """Interface exports the connect()-function"""
        self.assertTrue(inspect.isfunction(myconn.connect),
                        "Module does not export the connect()-function")
        cnx = myconn.connect(use_pure=True, **tests.get_mysql_config())
        self.assertTrue(isinstance(cnx, myconn.connection.MySQLConnection),
                        "connect() not returning by default pure "
                        "MySQLConnection object")

        if tests.MYSQL_CAPI:
            # By default use_pure=False
            cnx = myconn.connect(**tests.get_mysql_config())
            self.assertTrue(isinstance(cnx,
                                       myconn.connection_cext.CMySQLConnection),
                            "The connect()-method returns incorrect instance")
Beispiel #3
0
    def setUp(self):
        config = tests.get_mysql_config()
        config['raw'] = True
        config['buffered'] = True

        self.connection = connection.MySQLConnection(**config)
        self.cur = self.connection.cursor()
    def test_add_connection(self):
        cnxpool = pooling.MySQLConnectionPool(pool_name='test')
        self.assertRaises(errors.PoolError, cnxpool.add_connection)

        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_size=2, pool_name='test')
        cnxpool.set_config(**dbconfig)

        cnxpool.add_connection()
        pcnx = pooling.PooledMySQLConnection(
            cnxpool,
            cnxpool._cnx_queue.get(block=False))
        self.assertTrue(isinstance(pcnx._cnx, MySQLConnection))
        self.assertEqual(cnxpool, pcnx._cnx_pool)
        self.assertEqual(cnxpool._config_version,
                         pcnx._cnx._pool_config_version)

        cnx = pcnx._cnx
        pcnx.close()
        # We should get the same connectoin back
        self.assertEqual(cnx, cnxpool._cnx_queue.get(block=False))
        cnxpool.add_connection(cnx)

        # reach max connections
        cnxpool.add_connection()
        self.assertRaises(errors.PoolError, cnxpool.add_connection)

        # fail connecting
        cnxpool._remove_connections()
        cnxpool._cnx_config['port'] = 9999999
        cnxpool._cnx_config['unix_socket'] = '/ham/spam/foobar.socket'
        self.assertRaises(errors.InterfaceError, cnxpool.add_connection)

        self.assertRaises(errors.PoolError, cnxpool.add_connection, cnx=str)
    def test___init__(self):
        dbconfig = tests.get_mysql_config()
        self.assertRaises(errors.PoolError, pooling.MySQLConnectionPool)

        self.assertRaises(AttributeError, pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=-1)
        self.assertRaises(AttributeError, pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=0)
        self.assertRaises(AttributeError, pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=(pooling.CNX_POOL_MAXSIZE + 1))

        cnxpool = pooling.MySQLConnectionPool(pool_name='test')
        self.assertEqual(5, cnxpool._pool_size)
        self.assertEqual('test', cnxpool._pool_name)
        self.assertEqual({}, cnxpool._cnx_config)
        self.assertTrue(isinstance(cnxpool._cnx_queue, Queue))
        self.assertTrue(isinstance(cnxpool._config_version, uuid.UUID))

        cnxpool = pooling.MySQLConnectionPool(pool_size=10, pool_name='test')
        self.assertEqual(10, cnxpool._pool_size)

        cnxpool = pooling.MySQLConnectionPool(pool_size=10, **dbconfig)
        self.assertEqual(dbconfig, cnxpool._cnx_config,
                         "Connection configuration not saved correctly")
        self.assertEqual(10, cnxpool._cnx_queue.qsize())
        self.assertTrue(isinstance(cnxpool._config_version, uuid.UUID))
    def test_get_connection(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_size=2, pool_name='test')

        self.assertRaises(errors.PoolError, cnxpool.get_connection)

        cnxpool = pooling.MySQLConnectionPool(pool_size=1, **dbconfig)

        # Get connection from pool
        pcnx = cnxpool.get_connection()
        self.assertTrue(isinstance(pcnx, pooling.PooledMySQLConnection))
        self.assertRaises(errors.PoolError, cnxpool.get_connection)
        self.assertEqual(pcnx._cnx._pool_config_version,
                         cnxpool._config_version)
        prev_config_version = pcnx._pool_config_version
        prev_thread_id = pcnx.connection_id
        pcnx.close()

        # Change configuration
        config_version = cnxpool._config_version
        cnxpool.set_config(autocommit=True)
        self.assertNotEqual(config_version, cnxpool._config_version)

        pcnx = cnxpool.get_connection()
        self.assertNotEqual(
            pcnx._cnx._pool_config_version, prev_config_version)
        self.assertNotEqual(prev_thread_id, pcnx.connection_id)
        self.assertEqual(1, pcnx.autocommit)
        pcnx.close()
 def test_connect(self):
     """Interface exports the connect()-function"""
     self.assertTrue(inspect.isfunction(myconn.connect),
                     "Module does not export the connect()-function")
     cnx = myconn.connect(**tests.get_mysql_config())
     self.assertTrue(isinstance(cnx, myconn.connection.MySQLConnection),
                     "The connect()-method returns incorrect instance")
Beispiel #8
0
    def test__handle_result(self):
        """MySQLCursor object _handle_result()-method"""
        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.connection.cursor()

        self.assertRaises(errors.InterfaceError, self.cur._handle_result, None)
        self.assertRaises(errors.InterfaceError, self.cur._handle_result,
                          'spam')
        self.assertRaises(errors.InterfaceError, self.cur._handle_result,
                          {'spam': 5})

        cases = [
            {'affected_rows': 99999,
                'insert_id': 10,
                'warning_count': 100,
                'server_status': 8,
             },
            {'eof': {'status_flag': 0, 'warning_count': 0},
                'columns': [('1', 8, None, None, None, None, 0, 129)]
             },
        ]
        self.cur._handle_result(cases[0])
        self.assertEqual(cases[0]['affected_rows'], self.cur.rowcount)
        self.assertFalse(self.cur._connection.unread_result)
        self.assertFalse(self.cur._have_unread_result())

        self.cur._handle_result(cases[1])
        self.assertEqual(cases[1]['columns'], self.cur.description)
        self.assertTrue(self.cur._connection.unread_result)
        self.assertTrue(self.cur._have_unread_result())
 def setUp(self):
     self.table_name = 'Bug21449996'
     cnx = mysql.connector.connect(**tests.get_mysql_config())
     cnx.cmd_query("DROP TABLE IF EXISTS %s" % self.table_name)
     cnx.cmd_query("CREATE TABLE {0} (c1 BLOB) DEFAULT CHARSET=latin1"
                   "".format(self.table_name))
     cnx.close()
Beispiel #10
0
    def test_fetchall(self):
        """MySQLCursor object fetchall()-method"""
        self.check_method(self.cur, 'fetchall')

        self.assertRaises(errors.InterfaceError, self.cur.fetchall)

        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        tbl = 'myconnpy_fetch'
        self._test_execute_setup(self.connection, tbl)
        stmt_insert = (
            "INSERT INTO {table} (col1,col2) "
            "VALUES (%s,%s)".format(table=tbl))
        stmt_select = (
            "SELECT col1,col2 FROM {table} "
            "ORDER BY col1 ASC".format(table=tbl))

        self.cur = self.connection.cursor()
        self.cur.execute("SELECT * FROM {table}".format(table=tbl))
        self.assertEqual([], self.cur.fetchall(),
                         "fetchall() with empty result should return []")
        nrrows = 10
        data = [(i, str(i * 100)) for i in range(0, nrrows)]
        self.cur.executemany(stmt_insert, data)
        self.cur.execute(stmt_select)
        self.assertTrue(tests.cmp_result(data, self.cur.fetchall()),
                        "Fetching all rows failed.")
        self.assertEqual(None, self.cur.fetchone())
        self._test_execute_cleanup(self.connection, tbl)
        self.cur.close()
    def test__process_params(self):
        """MySQLCursor object _process_params()-method"""
        self.check_method(self.cur, '_process_params')

        self.assertRaises(
            errors.ProgrammingError, self.cur._process_params, 'foo')
        self.assertRaises(errors.ProgrammingError, self.cur._process_params, ())

        st_now = time.localtime()
        data = (
            None,
            int(128),
            int(1281288),
            float(3.14),
            Decimal('3.14'),
            r'back\slash',
            'newline\n',
            'return\r',
            "'single'",
            '"double"',
            'windows\032',
            "Strings are sexy",
            '\u82b1',
            datetime.datetime(2008, 5, 7, 20, 0o1, 23),
            datetime.date(2008, 5, 7),
            datetime.time(20, 0o3, 23),
            st_now,
            datetime.timedelta(hours=40, minutes=30, seconds=12),
        )
        exp = (
            b'NULL',
            b'128',
            b'1281288',
            b'3.14',
            b"'3.14'",
            b"'back\\\\slash'",
            b"'newline\\n'",
            b"'return\\r'",
            b"'\\'single\\''",
            b'\'\\"double\\"\'',
            b"'windows\\\x1a'",
            b"'Strings are sexy'",
            b"'\xe8\x8a\xb1'",
            b"'2008-05-07 20:01:23'",
            b"'2008-05-07'",
            b"'20:03:23'",
            b"'" + time.strftime('%Y-%m-%d %H:%M:%S', st_now).encode('ascii')
            + b"'",
            b"'40:30:12'",
        )

        self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.cnx.cursor()
        self.assertEqual((), self.cur._process_params(()),
                         "_process_params() should return a tuple")
        res = self.cur._process_params(data)
        for (i, exped) in enumerate(exp):
            self.assertEqual(exped, res[i])
        self.cur.close()
Beispiel #12
0
 def setUp(self):
     config = tests.get_mysql_config()
     self.cnx = connection.MySQLConnection(**config)
     self.cur = self.cnx.cursor()
     self.table = "⽃⽄⽅⽆⽇⽈⽉⽊"
     self.cur.execute("DROP TABLE IF EXISTS {0}".format(self.table))
     self.cur.execute("CREATE TABLE {0} (c1 VARCHAR(100)) "
                      "CHARACTER SET 'utf8'".format(self.table))
Beispiel #13
0
 def setUp(self):
     dbconfig = tests.get_mysql_config()
     self.conn = mysql.connector.connect(**dbconfig)
     self.cnx = DatabaseWrapper(settings.DATABASES['default'])
     self.cur = self.cnx.cursor()
     self.tbl = "BugOra20106629"
     self.cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl), ())
     self.cur.execute("CREATE TABLE {0}(col1 TEXT, col2 BLOB)".format(self.tbl), ())
Beispiel #14
0
    def test_ssl_cipher_in_option_file(self):
        config = tests.get_mysql_config()
        config['ssl_ca'] = TEST_SSL['ca']
        config['use_pure'] = False

        cnx = mysql.connector.connect(**config)
        cnx.cmd_query("SHOW STATUS LIKE 'Ssl_cipher'")
        self.assertNotEqual(cnx.get_row()[1], '')  # Ssl_cipher must have a value
Beispiel #15
0
    def test_use_unicode(self):
        """lp:499410 Disabling unicode does not work"""
        config = tests.get_mysql_config()
        config['use_unicode'] = False
        cnx = connection.MySQLConnection(**config)

        self.assertEqual(False, cnx._use_unicode)
        cnx.close()
    def test__process_params_dict(self):
        """MySQLCursor object _process_params_dict()-method"""
        self.check_method(self.cur, '_process_params')

        self.assertRaises(
            errors.ProgrammingError, self.cur._process_params, 'foo')
        self.assertRaises(errors.ProgrammingError, self.cur._process_params, ())

        st_now = time.localtime()
        data = {
            'a': None,
            'b': int(128),
            'c': int(1281288),
            'd': float(3.14),
            'e': Decimal('3.14'),
            'f': 'back\slash',  # pylint: disable=W1401
            'g': 'newline\n',
            'h': 'return\r',
            'i': "'single'",
            'j': '"double"',
            'k': 'windows\032',
            'l': str("Strings are sexy"),
            'm': '\u82b1',
            'n': datetime.datetime(2008, 5, 7, 20, 0o1, 23),
            'o': datetime.date(2008, 5, 7),
            'p': datetime.time(20, 0o3, 23),
            'q': st_now,
            'r': datetime.timedelta(hours=40, minutes=30, seconds=12),
        }
        exp = {
            b'%(a)s': b'NULL',
            b'%(b)s': b'128',
            b'%(c)s': b'1281288',
            b'%(d)s': b'3.14',
            b'%(e)s': b"'3.14'",
            b'%(f)s': b"'back\\\\slash'",
            b'%(g)s': b"'newline\\n'",
            b'%(h)s': b"'return\\r'",
            b'%(i)s': b"'\\'single\\''",
            b'%(j)s': b'\'\\"double\\"\'',
            b'%(k)s': b"'windows\\\x1a'",
            b'%(l)s': b"'Strings are sexy'",
            b'%(m)s': b"'\xe8\x8a\xb1'",
            b'%(n)s': b"'2008-05-07 20:01:23'",
            b'%(o)s': b"'2008-05-07'",
            b'%(p)s': b"'20:03:23'",
            b'%(q)s': b"'" +
            time.strftime('%Y-%m-%d %H:%M:%S', st_now).encode('ascii')
            + b"'",
            b'%(r)s': b"'40:30:12'",
        }

        self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.cnx.cursor()
        self.assertEqual({}, self.cur._process_params_dict({}),
                         "_process_params_dict() should return a dict")
        self.assertEqual(exp, self.cur._process_params_dict(data))
        self.cur.close()
Beispiel #17
0
 def test_column_names(self):
     self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
     self.cur = self.cnx.cursor()
     stmt = "SELECT NOW() as now, 'The time' as label, 123 FROM dual"
     exp = (u'now', u'label', u'123')
     self.cur.execute(stmt)
     self.cur.fetchone()
     self.assertEqual(exp, self.cur.column_names)
     self.cur.close()
    def test_open_connection__ipv4(self):
        """Open a connection using TCP"""
        try:
            self.cnx.open_connection()
        except errors.Error as err:
            self.fail(str(err))

        config = tests.get_mysql_config()
        self._host = config['host']
        self._port = config['port']

        cases = [
            # Address, Expected Family, Should Raise, Force IPv6
            (tests.get_mysql_config()['host'], socket.AF_INET, False, False),
            ]

        for case in cases:
            self._test_open_connection(*case)
Beispiel #19
0
    def test__set_connection(self):
        """MySQLCursor object _set_connection()-method"""
        self.check_method(self.cur, '_set_connection')

        self.assertRaises(errors.InterfaceError,
                          self.cur._set_connection, 'foo')
        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur._set_connection(self.connection)
        self.cur.close()
    def test_executemany(self):
        """MySQLCursor object executemany()-method"""
        self.check_method(self.cur, 'executemany')

        self.assertEqual(None, self.cur.executemany(None, []))

        config = tests.get_mysql_config()
        config['get_warnings'] = True
        self.cnx = connection.MySQLConnection(**config)
        self.cur = self.cnx.cursor()
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          'foo', None)
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          'foo', 'foo')
        self.assertEqual(None, self.cur.executemany('foo', []))
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          'foo', ['foo'])
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          'SELECT %s', [('foo',), 'foo'])
        self.assertRaises(errors.InterfaceError,
                          self.cur.executemany,
                          "INSERT INTO t1 1 %s", [(1,), (2,)])

        self.cur.executemany("SELECT SHA1(%s)", [('foo',), ('bar',)])
        self.assertEqual(None, self.cur.fetchone())
        self.cur.close()

        tbl = 'myconnpy_cursor'
        self._test_execute_setup(self.cnx, tbl)
        stmt_insert = "INSERT INTO {0} (col1,col2) VALUES (%s,%s)".format(tbl)
        stmt_select = "SELECT col1,col2 FROM {0} ORDER BY col1".format(tbl)

        self.cur = self.cnx.cursor()

        res = self.cur.executemany(stmt_insert, [(1, 100), (2, 200), (3, 300)])
        self.assertEqual(3, self.cur.rowcount)

        res = self.cur.executemany("SELECT %s", [('f',), ('o',), ('o',)])
        self.assertEqual(3, self.cur.rowcount)

        data = [{'id': 2}, {'id': 3}]
        stmt = "SELECT * FROM {0} WHERE col1 <= %(id)s".format(tbl)
        self.cur.executemany(stmt, data)
        self.assertEqual(5, self.cur.rowcount)

        self.cur.execute(stmt_select)
        self.assertEqual([(1, '100'), (2, '200'), (3, '300')],
                         self.cur.fetchall(), "Multi insert test failed")

        data = [{'id': 2}, {'id': 3}]
        stmt = "DELETE FROM {0} WHERE col1 = %(id)s".format(tbl)
        self.cur.executemany(stmt, data)
        self.assertEqual(2, self.cur.rowcount)

        self._test_execute_cleanup(self.cnx, tbl)
        self.cur.close()
 def test_connect(self):
     dbconfig = tests.get_mysql_config()
     cnx = mysql.connector.connect(pool_size=1, pool_name='ham', **dbconfig)
     exp = cnx.connection_id
     cnx.close()
     self.assertEqual(
         exp,
         mysql.connector._get_pooled_connection(
             pool_name='ham').connection_id
     )
    def test_next(self):
        """MySQLCursor object next()-method"""
        self.check_method(self.cur, 'next')

        self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = cursor.MySQLCursor(self.cnx)
        self.assertRaises(StopIteration, self.cur.__next__)
        self.cur.execute("SELECT BINARY 'ham'")
        exp = (b'ham',)
        self.assertEqual(exp, next(self.cur))
        self.cur.close()
Beispiel #23
0
 def test_raise_on_warning(self):
     self.connection = connection.MySQLConnection(**tests.get_mysql_config())
     self.connection.raise_on_warnings = True
     self.cur = self.connection.cursor()
     try:
         self.cur.execute("SELECT 'a' + 'b'")
         self.cur.fetchall()
     except errors.Error:
         pass
     else:
         self.fail("Did not get exception while raising warnings.")
Beispiel #24
0
    def test_next(self):
        """MySQLCursor object next()-method"""
        self.check_method(self.cur, 'next')

        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = cursor.MySQLCursor(self.connection)
        self.assertRaises(StopIteration, self.cur.next)
        self.cur.execute("SELECT SHA1('myconnpy')")
        exp = (u'c5e24647dbb63447682164d81b34fe493a83610b',)
        self.assertEqual(exp, self.cur.next())
        self.cur.close()
    def test__remove_connections(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(
            pool_size=2, pool_name='test', **dbconfig)
        pcnx = cnxpool.get_connection()
        self.assertEqual(1, cnxpool._remove_connections())
        pcnx.close()
        self.assertEqual(1, cnxpool._remove_connections())
        self.assertEqual(0, cnxpool._remove_connections())

        self.assertRaises(errors.PoolError, cnxpool.get_connection)
    def setUp(self):
        self.tbl = 'Bug21449207'
        cnx = mysql.connector.connect(**tests.get_mysql_config())
        cnx.cmd_query("DROP TABLE IF EXISTS %s" % self.tbl)

        create_table = (
            "CREATE TABLE {0} ("
            "id INT PRIMARY KEY, "
            "a LONGTEXT "
            ") ENGINE=Innodb DEFAULT CHARSET utf8".format(self.tbl))
        cnx.cmd_query(create_table)
        cnx.close()
Beispiel #27
0
 def test_raise_on_warning(self):
     config = tests.get_mysql_config()
     config['buffered'] = True
     config['raise_on_warnings'] = True
     self.connection = connection.MySQLConnection(**config)
     self.cur = self.connection.cursor()
     try:
         self.cur.execute("SELECT 'a' + 'b'")
     except errors.Error:
         pass
     else:
         self.fail("Did not get exception while raising warnings.")
Beispiel #28
0
 def test_unicode_credentials(self):
     config = tests.get_mysql_config()
     for user, password in self._credentials:
         config['user'] = user
         config['password'] = password
         config['database'] = None
         try:
             cnx = connection.MySQLConnection(**config)
         except (UnicodeDecodeError, errors.InterfaceError):
             self.fail('Failed using unicode username or password')
         else:
             cnx.close()
    def test___init__(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_size=1, **dbconfig)
        self.assertRaises(TypeError, pooling.PooledMySQLConnection)
        cnx = MySQLConnection(**dbconfig)
        pcnx = pooling.PooledMySQLConnection(cnxpool, cnx)
        self.assertEqual(cnxpool, pcnx._cnx_pool)
        self.assertEqual(cnx, pcnx._cnx)

        self.assertRaises(AttributeError, pooling.PooledMySQLConnection,
                          None, None)
        self.assertRaises(AttributeError, pooling.PooledMySQLConnection,
                          cnxpool, None)
Beispiel #30
0
    def test_fetchone(self):
        """MySQLCursor object fetchone()-method"""
        self.check_method(self.cur, 'fetchone')

        self.assertEqual(None, self.cur.fetchone())

        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.connection.cursor()
        self.cur.execute("SELECT SHA1('myconnpy')")
        exp = (u'c5e24647dbb63447682164d81b34fe493a83610b',)
        self.assertEqual(exp, self.cur.fetchone())
        self.assertEqual(None, self.cur.fetchone())
        self.cur.close()
Beispiel #31
0
    def test_close(self):
        dbconfig = tests.get_mysql_config()
        if tests.MYSQL_VERSION < (5, 7):
            dbconfig["client_flags"] = [-ClientFlag.CONNECT_ARGS]
        cnxpool = pooling.MySQLConnectionPool(pool_size=1, **dbconfig)

        cnxpool._original_cnx = None

        def dummy_add_connection(self, cnx=None):
            self._original_cnx = cnx
        cnxpool.add_connection = dummy_add_connection.__get__(
            cnxpool, pooling.MySQLConnectionPool)
        if tests.MYSQL_VERSION < (5, 7):
            dbconfig["client_flags"] = [-ClientFlag.CONNECT_ARGS]
        pcnx = pooling.PooledMySQLConnection(cnxpool,
                                             MySQLConnection(**dbconfig))

        cnx = pcnx._cnx
        pcnx.close()
        self.assertEqual(cnx, cnxpool._original_cnx)
Beispiel #32
0
    def test__handle_noresultset(self):
        """MySQLCursor object _handle_noresultset()-method"""
        self.check_method(self.cur, '_handle_noresultset')

        self.assertRaises(errors.ProgrammingError,
                          self.cur._handle_noresultset, None)
        data = {
            'affected_rows': 1,
            'insert_id': 10,
            'warning_count': 100,
            'server_status': 8,
        }
        self.connection = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.connection.cursor()
        self.cur._handle_noresultset(data)
        self.assertEqual(data['affected_rows'], self.cur.rowcount)
        self.assertEqual(data['insert_id'], self.cur._last_insert_id)
        self.assertEqual(data['warning_count'], self.cur._warning_count)

        self.cur.close()
Beispiel #33
0
    def test_connect(self):
        dbconfig = tests.get_mysql_config()
        myconn._CONNECTION_POOLS.update({'spam': 'ham'})
        self.assertRaises(errors.InterfaceError,
                          myconn.connect,
                          pool_name='spam')

        myconn._CONNECTION_POOLS = {}

        myconn.connect(pool_name='ham', **dbconfig)
        self.assertTrue('ham' in myconn._CONNECTION_POOLS)
        cnxpool = myconn._CONNECTION_POOLS['ham']
        self.assertTrue(isinstance(cnxpool, pooling.MySQLConnectionPool))
        self.assertEqual('ham', cnxpool.pool_name)

        myconn.connect(pool_size=5, **dbconfig)
        pool_name = pooling.generate_pool_name(**dbconfig)
        self.assertTrue(pool_name in myconn._CONNECTION_POOLS)

        myconn._CONNECTION_POOLS = {}
Beispiel #34
0
    def test___getattr__(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_size=1, pool_name='test')
        cnx = MySQLConnection(**dbconfig)
        pcnx = pooling.PooledMySQLConnection(cnxpool, cnx)

        exp_attrs = {
            '_connection_timeout': dbconfig['connection_timeout'],
            '_database': dbconfig['database'],
            '_host': dbconfig['host'],
            '_password': dbconfig['password'],
            '_port': dbconfig['port'],
            '_unix_socket': dbconfig['unix_socket']
        }
        for attr, value in exp_attrs.items():
            self.assertEqual(
                value, getattr(pcnx, attr),
                "Attribute {0} of reference connection not correct".format(
                    attr))

        self.assertEqual(pcnx.connect, cnx.connect)
Beispiel #35
0
    def test___init__(self):
        dbconfig = tests.get_mysql_config()
        self.assertRaises(errors.PoolError, pooling.MySQLConnectionPool)

        self.assertRaises(AttributeError,
                          pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=-1)
        self.assertRaises(AttributeError,
                          pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=0)
        self.assertRaises(AttributeError,
                          pooling.MySQLConnectionPool,
                          pool_name='test',
                          pool_size=(pooling.CNX_POOL_MAXSIZE + 1))

        cnxpool = pooling.MySQLConnectionPool(pool_name='test')
        self.assertEqual(5, cnxpool._pool_size)
        self.assertEqual('test', cnxpool._pool_name)
        self.assertEqual({}, cnxpool._cnx_config)
        self.assertTrue(isinstance(cnxpool._cnx_queue, Queue))
        self.assertTrue(isinstance(cnxpool._config_version, uuid.UUID))
        self.assertTrue(True, cnxpool._reset_session)

        cnxpool = pooling.MySQLConnectionPool(pool_size=10, pool_name='test')
        self.assertEqual(10, cnxpool._pool_size)

        cnxpool = pooling.MySQLConnectionPool(pool_size=10, **dbconfig)
        self.assertEqual(dbconfig, cnxpool._cnx_config,
                         "Connection configuration not saved correctly")
        self.assertEqual(10, cnxpool._cnx_queue.qsize())
        self.assertTrue(isinstance(cnxpool._config_version, uuid.UUID))

        cnxpool = pooling.MySQLConnectionPool(pool_size=1,
                                              pool_name='test',
                                              pool_reset_session=False)
        self.assertFalse(cnxpool._reset_session)
Beispiel #36
0
    def test_callproc(self):
        """MySQLCursor object callproc()-method"""
        self.check_method(self.cur, 'callproc')

        self.assertRaises(ValueError, self.cur.callproc, None)
        self.assertRaises(ValueError, self.cur.callproc, 'sp1', None)

        config = tests.get_mysql_config()
        config['get_warnings'] = True
        self.cnx = connection.MySQLConnection(**config)
        self._test_callproc_setup(self.cnx)
        self.cur = self.cnx.cursor()

        exp = (5, 4, 20)
        result = self.cur.callproc('myconnpy_sp_1', (exp[0], exp[1], 0))
        self.assertEqual([], self.cur._stored_results)
        self.assertEqual(exp, result)

        exp = (6, 5, 30)
        result = self.cur.callproc('myconnpy_sp_2', (exp[0], exp[1], 0))
        self.assertTrue(isinstance(self.cur._stored_results, list))
        self.assertEqual(exp, result)

        exp_results = [
            ('abc',),
            ('def',)
        ]
        for result, exp in zip(self.cur.stored_results(),
                               iter(exp_results)):
            self.assertEqual(exp, result.fetchone())

        exp = ('ham', 'spam', 'hamspam')
        result = self.cur.callproc('myconnpy_sp_3', (exp[0], exp[1], 0))
        self.assertTrue(isinstance(self.cur._stored_results, list))
        self.assertEqual(exp, result)

        self._test_callproc_cleanup(self.cnx)
        self.cur.close()
Beispiel #37
0
    def test_set_config(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_name='test')

        # No configuration changes
        config_version = cnxpool._config_version
        cnxpool.set_config()
        self.assertEqual(config_version, cnxpool._config_version)
        self.assertEqual({}, cnxpool._cnx_config)

        # Valid configuration changes
        config_version = cnxpool._config_version
        cnxpool.set_config(**dbconfig)
        self.assertEqual(dbconfig, cnxpool._cnx_config)
        self.assertNotEqual(config_version, cnxpool._config_version)

        # Invalid configuration changes
        config_version = cnxpool._config_version
        wrong_dbconfig = dbconfig.copy()
        wrong_dbconfig['spam'] = 'ham'
        self.assertRaises(errors.PoolError, cnxpool.set_config,
                          **wrong_dbconfig)
        self.assertEqual(dbconfig, cnxpool._cnx_config)
        self.assertEqual(config_version, cnxpool._config_version)
Beispiel #38
0
    def test__handle_result(self):
        """MySQLCursor object _handle_result()-method"""
        self.connection = connection.MySQLConnection(
            **tests.get_mysql_config())
        self.cur = self.connection.cursor()

        self.assertRaises(errors.InterfaceError, self.cur._handle_result, None)
        self.assertRaises(errors.InterfaceError, self.cur._handle_result,
                          'spam')
        self.assertRaises(errors.InterfaceError, self.cur._handle_result,
                          {'spam': 5})

        cases = [
            {
                'affected_rows': 99999,
                'insert_id': 10,
                'warning_count': 100,
                'server_status': 8,
            },
            {
                'eof': {
                    'status_flag': 0,
                    'warning_count': 0
                },
                'columns': [('1', 8, None, None, None, None, 0, 129)]
            },
        ]
        self.cur._handle_result(cases[0])
        self.assertEqual(cases[0]['affected_rows'], self.cur.rowcount)
        self.assertFalse(self.cur._connection.unread_result)
        self.assertFalse(self.cur._have_unread_result())

        self.cur._handle_result(cases[1])
        self.assertEqual(cases[1]['columns'], self.cur.description)
        self.assertTrue(self.cur._connection.unread_result)
        self.assertTrue(self.cur._have_unread_result())
Beispiel #39
0
    def test_add_connection(self):
        cnxpool = pooling.MySQLConnectionPool(pool_name='test')
        self.assertRaises(errors.PoolError, cnxpool.add_connection)

        dbconfig = tests.get_mysql_config()
        if tests.MYSQL_VERSION < (5, 7):
            dbconfig["client_flags"] = [-ClientFlag.CONNECT_ARGS]
        cnxpool = pooling.MySQLConnectionPool(pool_size=2, pool_name='test')
        cnxpool.set_config(**dbconfig)

        cnxpool.add_connection()
        pcnx = pooling.PooledMySQLConnection(
            cnxpool,
            cnxpool._cnx_queue.get(block=False))
        self.assertTrue(isinstance(pcnx._cnx, MYSQL_CNX_CLASS))
        self.assertEqual(cnxpool, pcnx._cnx_pool)
        self.assertEqual(cnxpool._config_version,
                         pcnx._cnx._pool_config_version)

        cnx = pcnx._cnx
        pcnx.close()
        # We should get the same connection back
        self.assertEqual(cnx, cnxpool._cnx_queue.get(block=False))
        cnxpool.add_connection(cnx)

        # reach max connections
        cnxpool.add_connection()
        self.assertRaises(errors.PoolError, cnxpool.add_connection)

        # fail connecting
        cnxpool._remove_connections()
        cnxpool._cnx_config['port'] = 9999999
        cnxpool._cnx_config['unix_socket'] = '/ham/spam/foobar.socket'
        self.assertRaises(errors.Error, cnxpool.add_connection)

        self.assertRaises(errors.PoolError, cnxpool.add_connection, cnx=str)
Beispiel #40
0
    def test_fetchmany(self):
        """MySQLCursor object fetchmany()-method"""
        self.check_method(self.cur, 'fetchmany')

        self.assertEqual([], self.cur.fetchmany())

        self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
        tbl = 'myconnpy_fetch'
        self._test_execute_setup(self.cnx, tbl)
        stmt_insert = (
            "INSERT INTO {table} (col1,col2) "
            "VALUES (%s,%s)".format(table=tbl))
        stmt_select = (
            "SELECT col1,col2 FROM {table} "
            "ORDER BY col1 DESC".format(table=tbl))

        self.cur = self.cnx.cursor()
        nrrows = 10
        data = [(i, str(i * 100)) for i in range(0, nrrows)]
        self.cur.executemany(stmt_insert, data)
        self.cur.execute(stmt_select)
        exp = [(9, '900'), (8, '800'), (7, '700'), (6, '600')]
        rows = self.cur.fetchmany(4)
        self.assertTrue(tests.cmp_result(exp, rows),
                        "Fetching first 4 rows test failed.")
        exp = [(5, '500'), (4, '400'), (3, '300')]
        rows = self.cur.fetchmany(3)
        self.assertTrue(tests.cmp_result(exp, rows),
                        "Fetching next 3 rows test failed.")
        exp = [(2, '200'), (1, '100'), (0, '0')]
        rows = self.cur.fetchmany(3)
        self.assertTrue(tests.cmp_result(exp, rows),
                        "Fetching next 3 rows test failed.")
        self.assertEqual([], self.cur.fetchmany())
        self._test_execute_cleanup(self.cnx, tbl)
        self.cur.close()
Beispiel #41
0
 def test_connect_cext_error(self):
     config = tests.get_mysql_config()
     config["use_pure"] = False
     config["pool_size"] = 1
     config["pool_name"] = 'ham'
     self.assertRaises(ImportError, mysql.connector.connect, **config)
Beispiel #42
0
 def tearDown(self):
     cnx = mysql.connector.connect(**tests.get_mysql_config())
     cur = cnx.cursor()
     cur.execute("DROP TABLE IF EXISTS {0}".format(self.table))
     cur.execute("DROP PROCEDURE IF EXISTS {0}".format(self.proc))
Beispiel #43
0
 def test_unicode_database(self):
     config = tests.get_mysql_config()
     config['database'] = 'データベース'
     self.assertRaises(errors.DatabaseError, connection.MySQLConnection,
                       **config)
# Load 3rd party _after_ loading tests
try:
    from django.conf import settings
except ImportError:
    DJANGO_AVAILABLE = False
else:
    DJANGO_AVAILABLE = True

# Have to setup Django before loading anything else
if DJANGO_AVAILABLE:
    try:
        settings.configure()
    except RuntimeError as exc:
        if not 'already configured' in str(exc):
            raise
    DBCONFIG = tests.get_mysql_config()

    settings.DATABASES = {
        'default': {
            'ENGINE': 'mysql.connector.django',
            'NAME': DBCONFIG['database'],
            'USER': '******',
            'PASSWORD': '',
            'HOST': DBCONFIG['host'],
            'PORT': DBCONFIG['port'],
            'TEST_CHARSET': 'utf8',
            'TEST_COLLATION': 'utf8_general_ci',
            'CONN_MAX_AGE': 0,
            'AUTOCOMMIT': True,
        },
    }
Beispiel #45
0
    def test_config(self):
        dbconfig = tests.get_mysql_config()
        cnxpool = pooling.MySQLConnectionPool(pool_size=1, **dbconfig)
        cnx = cnxpool.get_connection()

        self.assertRaises(errors.PoolError, cnx.config, user='******')
Beispiel #46
0
    def setUp(self):
        config = tests.get_mysql_config()
        config['raw'] = True

        self.cnx = connection.MySQLConnection(**config)
        self.cur = self.cnx.cursor()
Beispiel #47
0
    def test__process_params_dict(self):
        """MySQLCursor object _process_params_dict()-method"""
        self.check_method(self.cur, '_process_params')

        self.assertRaises(errors.ProgrammingError, self.cur._process_params,
                          'foo')
        self.assertRaises(errors.ProgrammingError, self.cur._process_params,
                          ())

        st_now = time.localtime()
        data = {
            'a': None,
            'b': int(128),
            'c': int(1281288),
            'd': float(3.14),
            'e': Decimal('3.14'),
            'f': 'back\slash',  # pylint: disable=W1401
            'g': 'newline\n',
            'h': 'return\r',
            'i': "'single'",
            'j': '"double"',
            'k': 'windows\032',
            'l': str("Strings are sexy"),
            'm': '\u82b1',
            'n': datetime.datetime(2008, 5, 7, 20, 0o1, 23),
            'o': datetime.date(2008, 5, 7),
            'p': datetime.time(20, 0o3, 23),
            'q': st_now,
            'r': datetime.timedelta(hours=40, minutes=30, seconds=12),
        }
        exp = {
            b'%(a)s':
            b'NULL',
            b'%(b)s':
            b'128',
            b'%(c)s':
            b'1281288',
            b'%(d)s':
            b'3.14',
            b'%(e)s':
            b"'3.14'",
            b'%(f)s':
            b"'back\\\\slash'",
            b'%(g)s':
            b"'newline\\n'",
            b'%(h)s':
            b"'return\\r'",
            b'%(i)s':
            b"'\\'single\\''",
            b'%(j)s':
            b'\'\\"double\\"\'',
            b'%(k)s':
            b"'windows\\\x1a'",
            b'%(l)s':
            b"'Strings are sexy'",
            b'%(m)s':
            b"'\xe8\x8a\xb1'",
            b'%(n)s':
            b"'2008-05-07 20:01:23'",
            b'%(o)s':
            b"'2008-05-07'",
            b'%(p)s':
            b"'20:03:23'",
            b'%(q)s':
            b"'" + time.strftime('%Y-%m-%d %H:%M:%S', st_now).encode('ascii') +
            b"'",
            b'%(r)s':
            b"'40:30:12'",
        }

        self.cnx = connection.MySQLConnection(**tests.get_mysql_config())
        self.cur = self.cnx.cursor()
        self.assertEqual({}, self.cur._process_params_dict({}),
                         "_process_params_dict() should return a dict")
        self.assertEqual(exp, self.cur._process_params_dict(data))
        self.cur.close()
Beispiel #48
0
 def setUp(self):
     config = tests.get_mysql_config()
     self._unix_socket = config['unix_socket']
     self.cnx = network.MySQLUnixSocket(unix_socket=config['unix_socket'])
Beispiel #49
0
    def setUp(self):
        config = tests.get_mysql_config()
        self.cnx = CMySQLConnection(**config)

        self.pcnx = MySQLConnection(**config)
Beispiel #50
0
 def setUp(self):
     config = tests.get_mysql_config()
     self.cnx = CMySQLConnection(**config)
     self.cur = self.cnx.cursor(prepared=True)
     self.cur.execute(self.create_table_stmt.format(self.tbl))
Beispiel #51
0
 def setUp(self):
     config = tests.get_mysql_config()
     self._host = config['host']
     self._port = config['port']
     self.cnx = network.BaseMySQLSocket()
Beispiel #52
0
 def setUp(self):
     config = tests.get_mysql_config()
     self._host = config['host']
     self._port = config['port']
     self.cnx = network.MySQLTCPSocket(host=self._host, port=self._port)
Beispiel #53
0
 def setUp(self):
     config = tests.get_mysql_config()
     self.cnx = mysql.connector.connect(**config)
 def setUp(self):
     self.config = tests.get_mysql_config()
     self.config['use_pure'] = True
     self.cnx = mysql.connector.connect(**self.config)
Beispiel #55
0
 def setUp(self):
     self.config = tests.get_mysql_config()
     cnx = connection.MySQLConnection(**self.config)
     self.drop_tables(cnx)
Beispiel #56
0
 def tearDown(self):
     cnx = mysql.connector.connect(**tests.get_mysql_config())
     cnx.cmd_query("DROP TABLE IF EXISTS %s" % self.table_name)
     cnx.close()
Beispiel #57
0
    def test_executemany(self):
        """MySQLCursor object executemany()-method"""
        self.check_method(self.cur, 'executemany')

        self.assertEqual(None, self.cur.executemany(None, []))

        config = tests.get_mysql_config()
        config['get_warnings'] = True
        self.cnx = connection.MySQLConnection(**config)
        self.cur = self.cnx.cursor()
        self.assertRaises(errors.ProgrammingError, self.cur.executemany, 'foo',
                          None)
        self.assertRaises(errors.ProgrammingError, self.cur.executemany, 'foo',
                          'foo')
        self.assertEqual(None, self.cur.executemany('foo', []))
        self.assertRaises(errors.ProgrammingError, self.cur.executemany, 'foo',
                          ['foo'])
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          'SELECT %s', [('foo', ), 'foo'])
        self.assertRaises(errors.ProgrammingError, self.cur.executemany,
                          "INSERT INTO t1 1 %s", [(1, ), (2, )])

        self.cur.executemany("SELECT SHA1(%s)", [('foo', ), ('bar', )])
        self.assertEqual(None, self.cur.fetchone())
        self.cur.close()

        tbl = 'myconnpy_cursor'
        self._test_execute_setup(self.cnx, tbl)
        stmt_insert = "INSERT INTO {0} (col1,col2) VALUES (%s,%s)".format(tbl)
        stmt_select = "SELECT col1,col2 FROM {0} ORDER BY col1".format(tbl)

        self.cur = self.cnx.cursor()

        res = self.cur.executemany(stmt_insert, [(1, 100), (2, 200), (3, 300)])
        self.assertEqual(3, self.cur.rowcount)

        res = self.cur.executemany("SELECT %s", [('f', ), ('o', ), ('o', )])
        self.assertEqual(3, self.cur.rowcount)

        data = [{'id': 2}, {'id': 3}]
        stmt = "SELECT * FROM {0} WHERE col1 <= %(id)s".format(tbl)
        self.cur.executemany(stmt, data)
        self.assertEqual(5, self.cur.rowcount)

        self.cur.execute(stmt_select)
        self.assertEqual([(1, '100'), (2, '200'), (3, '300')],
                         self.cur.fetchall(), "Multi insert test failed")

        data = [{'id': 2}, {'id': 3}]
        stmt = "DELETE FROM {0} WHERE col1 = %(id)s".format(tbl)
        self.cur.executemany(stmt, data)
        self.assertEqual(2, self.cur.rowcount)

        stmt = "TRUNCATE TABLE {0}".format(tbl)
        self.cur.execute(stmt)

        stmt = (
            "/*comment*/INSERT/*comment*/INTO/*comment*/{0}(col1,col2)VALUES"
            "/*comment*/(%s,%s/*comment*/)/*comment()*/ON DUPLICATE KEY UPDATE"
            " col1 = VALUES(col1)").format(tbl)

        self.cur.executemany(stmt, [(4, 100), (5, 200), (6, 300)])
        self.assertEqual(3, self.cur.rowcount)

        self.cur.execute(stmt_select)
        self.assertEqual([(4, '100'), (5, '200'), (6, '300')],
                         self.cur.fetchall(), "Multi insert test failed")

        stmt = "TRUNCATE TABLE {0}".format(tbl)
        self.cur.execute(stmt)

        stmt = (
            "INSERT INTO/*comment*/{0}(col1,col2)VALUES"
            "/*comment*/(%s,'/*100*/')/*comment()*/ON DUPLICATE KEY UPDATE "
            "col1 = VALUES(col1)").format(tbl)

        self.cur.executemany(stmt, [(4, ), (5, )])
        self.assertEqual(2, self.cur.rowcount)

        self.cur.execute(stmt_select)
        self.assertEqual([(4, '/*100*/'), (5, '/*100*/')], self.cur.fetchall(),
                         "Multi insert test failed")
        self._test_execute_cleanup(self.cnx, tbl)
        self.cur.close()
Beispiel #58
0
 def db_connect(self):
     return myconn.connect(**tests.get_mysql_config())
Beispiel #59
0
 def setUp(self):
     config = tests.get_mysql_config()
     config['raw'] = True
     config['buffered'] = True
     self.cnx = connection.MySQLConnection(**config)
 def setUp(self):
     dbconfig = tests.get_mysql_config()
     self.conn = mysql.connector.connect(**dbconfig)
     self.cnx = DatabaseWrapper(settings.DATABASES['default'])
     self.dbo = DatabaseOperations(self.cnx)