1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
|
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Incur., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Testing the C Extension MySQL C API
"""
import logging
import os
import re
import unittest
import tests
from mysql.connector.constants import ServerFlag, ClientFlag
try:
from _mysql_connector import MySQL, MySQLError, MySQLInterfaceError
except ImportError:
CEXT_MYSQL_AVAILABLE = False
else:
CEXT_MYSQL_AVAILABLE = True
LOGGER = logging.getLogger(tests.LOGGER_NAME)
def get_variables(cnx, pattern=None, variables=None, global_vars=False):
"""Get session or global system variables
We use the MySQL connection cnx to query the INFORMATION_SCHEMA
table SESSION_VARIABLES or, when global_vars is True, the table
GLOBAL_VARIABLES.
:param cnx: Valid MySQL connection
:param pattern: Pattern to use (used for LIKE)
:param variables: Variables to query for
:return: Dictionary containing variables with values or empty dict
:rtype : dict
"""
format_vars = {
'where_clause': '',
'where': '',
}
ver = cnx.get_server_version()
if ver >= (5, 7, 6):
table_global_vars = 'global_variables'
table_session_vars = 'session_variables'
format_vars['schema'] = 'performance_schema'
else:
table_global_vars = 'GLOBAL_VARIABLES'
table_session_vars = 'SESSION_VARIABLES'
format_vars['schema'] = 'INFORMATION_SCHEMA'
if global_vars is True:
format_vars['table'] = table_global_vars
else:
format_vars['table'] = table_session_vars
query = "SELECT * FROM {schema}.{table} {where} {where_clause}"
where = []
if pattern:
where.append('VARIABLE_NAME LIKE "{0}"'.format(pattern))
if variables:
where.append('VARIABLE_NAME IN ({0})'.format(
','.join([ "'{0}'".format(name) for name in variables ])
))
if where:
format_vars['where'] = 'WHERE'
format_vars['where_clause'] = ' OR '.join(where)
cnx.query(query.format(**format_vars))
result = {}
row = cnx.fetch_row()
while row:
result[row[0].lower()] = row[1]
row = cnx.fetch_row()
cnx.free_result()
return result
def fetch_rows(cnx, query=None):
"""Execute query and fetch first result set
This function will use connection cnx and execute the query. All
rows are then returned as a list of tuples.
:param cnx: Valid MySQL connection
:param query: SQL statement to execute
:return: List of tuples
:rtype: list
"""
rows = []
if query:
cnx.query(query)
if cnx.have_result_set:
row = cnx.fetch_row()
while row:
rows.append(row)
row = cnx.fetch_row()
if cnx.next_result():
raise Exception("fetch_rows does not work with multi results")
cnx.free_result()
return rows
@unittest.skipIf(CEXT_MYSQL_AVAILABLE == False, "C Extension not available")
class CExtMySQLTests(tests.MySQLConnectorTests):
"""Test the MySQL class in the C Extension"""
def setUp(self):
self.config = tests.get_mysql_config()
connect_args = [
"host", "user", "password", "database",
"port", "unix_socket", "client_flags"
]
self.connect_kwargs = {}
for key, value in self.config.items():
if key in connect_args:
self.connect_kwargs[key] = value
if 'client_flags' not in self.connect_kwargs:
self.connect_kwargs['client_flags'] = ClientFlag.get_default()
def test___init__(self):
cmy = MySQL()
self.assertEqual(False, cmy.buffered())
self.assertEqual(False, cmy.raw())
cmy = MySQL(buffered=True, raw=True)
self.assertEqual(True, cmy.buffered())
self.assertEqual(True, cmy.raw())
exp = 'gbk'
cmy = MySQL(charset_name=exp)
cmy.connect(**self.connect_kwargs)
self.assertEqual(exp, cmy.character_set_name())
def test_buffered(self):
cmy = MySQL()
self.assertEqual(False, cmy.buffered())
cmy.buffered(True)
self.assertEqual(True, cmy.buffered())
cmy.buffered(False)
self.assertEqual(False, cmy.buffered())
self.assertRaises(TypeError, cmy.buffered, 'a')
def test_raw(self):
cmy = MySQL()
self.assertEqual(False, cmy.raw())
cmy.raw(True)
self.assertEqual(True, cmy.raw())
cmy.raw(False)
self.assertEqual(False, cmy.raw())
self.assertRaises(TypeError, cmy.raw, 'a')
def test_connected(self):
config = self.connect_kwargs.copy()
cmy = MySQL()
self.assertFalse(cmy.connected())
cmy.connect(**config)
self.assertTrue(cmy.connected())
cmy.close()
self.assertFalse(cmy.connected())
def test_connect(self):
config = self.connect_kwargs.copy()
cmy = MySQL()
self.assertFalse(cmy.ping())
# Using Unix Socket
cmy.connect(**config)
self.assertTrue(cmy.ping())
# Using TCP
config['unix_socket'] = None
cmy.connect(**config)
self.assertTrue(cmy.ping())
self.assertEqual(None, cmy.close())
self.assertFalse(cmy.ping())
self.assertEqual(None, cmy.close())
def test_close(self):
"""
MySQL_close() is being tested in test_connected
Unless something needs to be tested additionally, leave this
test case as placeholder.
"""
pass
def test_ping(self):
"""
MySQL_ping() is being tested in test_connected
Unless something needs to be tested additionally, leave this
test case as placeholder.
"""
pass
def test_escape_string(self):
cases = [
('new\nline', b'new\\nline'),
('carriage\rreturn', b'carriage\\rreturn'),
('control\x1aZ', b'control\\ZZ'),
("single'quote", b"single\\'quote"),
('double"quote', b'double\\"quote'),
('back\slash', b'back\\\\slash'),
('nul\0char', b'nul\\0char'),
(u"Kangxi⽃\0⽇", b'Kangxi\xe2\xbd\x83\\0\xe2\xbd\x87'),
(b'bytes\0ob\'j\n"ct\x1a', b'bytes\\0ob\\\'j\\n\\"ct\\Z'),
]
cmy = MySQL()
cmy.connect(**self.connect_kwargs)
unicode_string = u"Kangxi⽃\0⽇"
self.assertRaises(UnicodeEncodeError, cmy.escape_string, unicode_string)
cmy.set_character_set("UTF8")
for value, exp in cases:
self.assertEqual(exp, cmy.escape_string(value))
self.assertRaises(TypeError, cmy.escape_string, 1234);
def test_get_character_set_info(self):
cmy = MySQL()
self.assertRaises(MySQLInterfaceError, cmy.get_character_set_info)
cmy.connect(**self.connect_kwargs)
# We go by the default of MySQL, which is latin1/swedish_ci
exp = {'comment': '', 'name': 'latin1_swedish_ci',
'csname': 'latin1', 'mbmaxlen': 1, 'number': 8, 'mbminlen': 1}
result = cmy.get_character_set_info()
# make 'comment' deterministic
result['comment'] = ''
self.assertEqual(exp, result)
cmy.query("SET NAMES utf8")
cmy.set_character_set('utf8')
exp = {'comment': '', 'name': 'utf8_general_ci',
'csname': 'utf8', 'mbmaxlen': 3, 'number': 33, 'mbminlen': 1}
result = cmy.get_character_set_info()
# make 'comment' deterministic
result['comment'] = ''
self.assertEqual(exp, result)
def test_get_proto_info(self):
cmy = MySQL()
self.assertRaises(MySQLInterfaceError, cmy.get_proto_info)
cmy.connect(**self.connect_kwargs)
self.assertEqual(10, cmy.get_proto_info())
def test_get_server_info(self):
cmy = MySQL()
self.assertRaises(MySQLInterfaceError, cmy.get_server_info)
cmy.connect(**self.connect_kwargs)
version = cmy.get_server_version()
info = cmy.get_server_info()
self.assertIsInstance(info, str)
self.assertTrue(info.startswith('.'.join([str(v) for v in version])))
def test_get_server_version(self):
cmy = MySQL()
self.assertRaises(MySQLInterfaceError, cmy.get_server_version)
cmy.connect(**self.connect_kwargs)
version = cmy.get_server_version()
self.assertIsInstance(version, tuple)
self.assertEqual(3, len(version))
self.assertTrue(all([isinstance(v, int) and v > 0 for v in version]))
self.assertTrue(3 < version[0] < 7)
self.assertTrue(0 < version[1] < 20)
self.assertTrue(0 < version[2] < 99)
def test_thread_id(self):
cmy = MySQL()
self.assertRaises(MySQLInterfaceError, cmy.thread_id)
cmy.connect(**self.connect_kwargs)
if tests.PY2:
self.assertIsInstance(cmy.thread_id(), long)
else:
self.assertIsInstance(cmy.thread_id(), int)
self.assertGreater(cmy.thread_id(), 0)
thread_id = cmy.thread_id()
cmy.close()
self.assertRaises(MySQLError, cmy.thread_id)
def test_select_db(self):
cmy = MySQL(buffered=True)
cmy.connect(**self.connect_kwargs)
cmy.select_db('mysql')
cmy.query("SELECT DATABASE()")
self.assertEqual(b'mysql', cmy.fetch_row()[0])
cmy.free_result()
cmy.select_db('myconnpy')
cmy.query("SELECT DATABASE()")
self.assertEqual(b'myconnpy', cmy.fetch_row()[0])
cmy.free_result()
def test_affected_rows(self):
cmy = MySQL(buffered=True)
cmy.connect(**self.connect_kwargs)
table = "affected_rows"
cmy.select_db('myconnpy')
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
cmy.query("CREATE TABLE {0} (c1 INT, c2 INT)".format(table))
cmy.query("INSERT INTO {0} (c1, c2) VALUES "
"(1, 10), (2, 20), (3, 30)".format(table))
self.assertEqual(3, cmy.affected_rows())
cmy.query("UPDATE {0} SET c2 = c2 + 1 WHERE c1 < 3".format(table))
self.assertEqual(2, cmy.affected_rows())
cmy.query("DELETE FROM {0} WHERE c1 IN (1, 2, 3)".format(table))
self.assertEqual(3, cmy.affected_rows())
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
def test_field_count(self):
cmy = MySQL(buffered=True)
cmy.connect(**self.connect_kwargs)
table = "field_count"
cmy.select_db('myconnpy')
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
cmy.query("CREATE TABLE {0} (c1 INT, c2 INT, c3 INT)".format(table))
cmy.query("SELECT * FROM {0}".format(table))
self.assertEqual(3, cmy.field_count())
cmy.free_result()
cmy.query("INSERT INTO {0} (c1, c2, c3) VALUES "
"(1, 10, 100)".format(table))
cmy.commit()
cmy.query("SELECT * FROM {0}".format(table))
self.assertEqual(3, cmy.field_count())
cmy.free_result()
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
def test_autocommit(self):
cmy1 = MySQL(buffered=True)
cmy1.connect(**self.connect_kwargs)
cmy2 = MySQL(buffered=True)
cmy2.connect(**self.connect_kwargs)
self.assertRaises(ValueError, cmy1.autocommit, 'ham')
self.assertRaises(ValueError, cmy1.autocommit, 1)
self.assertRaises(ValueError, cmy1.autocommit, None)
table = "autocommit_test"
# For the test we start off by making sure the autocommit is off
# for both sessions
cmy1.query("SELECT @@global.autocommit")
if cmy1.fetch_row()[0] != 1:
cmy1.query("SET @@session.autocommit = 0")
cmy2.query("SET @@session.autocommit = 0")
cmy1.query("DROP TABLE IF EXISTS {0}".format(table))
cmy1.query("CREATE TABLE {0} (c1 INT)".format(table))
# Turn AUTOCOMMIT on
cmy1.autocommit(True)
cmy1.query("INSERT INTO {0} (c1) VALUES "
"(1), (2), (3)".format(table))
cmy2.query("SELECT * FROM {0}".format(table))
self.assertEqual(3, cmy2.num_rows())
rows = fetch_rows(cmy2)
# Turn AUTOCOMMIT off
cmy1.autocommit(False)
cmy1.query("INSERT INTO {0} (c1) VALUES "
"(4), (5), (6)".format(table))
cmy2.query("SELECT * FROM {0} WHERE c1 > 3".format(table))
self.assertEqual([], fetch_rows(cmy2))
cmy1.commit()
cmy2.query("SELECT * FROM {0} WHERE c1 > 3".format(table))
self.assertEqual([(4,), (5,), (6,)], fetch_rows(cmy2))
cmy1.close()
cmy2.close()
def test_commit(self):
cmy1 = MySQL(buffered=True)
cmy1.connect(**self.connect_kwargs)
cmy2 = MySQL(buffered=True)
cmy2.connect(**self.connect_kwargs)
table = "commit_test"
cmy1.query("DROP TABLE IF EXISTS {0}".format(table))
cmy1.query("CREATE TABLE {0} (c1 INT)".format(table))
cmy1.query("START TRANSACTION")
cmy1.query("INSERT INTO {0} (c1) VALUES "
"(1), (2), (3)".format(table))
cmy2.query("SELECT * FROM {0}".format(table))
self.assertEqual([], fetch_rows(cmy2))
cmy1.commit()
cmy2.query("SELECT * FROM {0}".format(table))
self.assertEqual([(1,), (2,), (3,)], fetch_rows(cmy2))
cmy1.query("DROP TABLE IF EXISTS {0}".format(table))
def test_change_user(self):
connect_kwargs = self.connect_kwargs.copy()
connect_kwargs['unix_socket'] = None
cmy1 = MySQL(buffered=True)
cmy1.connect(**connect_kwargs)
cmy2 = MySQL(buffered=True)
cmy2.connect(**connect_kwargs)
new_user = {
'user': 'cextuser',
'host': self.config['host'],
'database': self.connect_kwargs['database'],
'password': 'connc',
}
try:
cmy1.query("DROP USER '{user}'@'{host}'".format(**new_user))
except MySQLInterfaceError:
# Probably not created
pass
stmt = ("CREATE USER '{user}'@'{host}' IDENTIFIED WITH "
"mysql_native_password").format(**new_user)
cmy1.query(stmt)
cmy1.query("SET old_passwords = 0")
res = cmy1.query("SET PASSWORD FOR '{user}'@'{host}' = "
"PASSWORD('{password}')".format(**new_user))
cmy1.query("GRANT ALL ON {database}.* "
"TO '{user}'@'{host}'".format(**new_user))
cmy2.query("SHOW GRANTS FOR {user}@{host}".format(**new_user))
cmy2.query("SELECT USER()")
orig_user = cmy2.fetch_row()[0]
cmy2.free_result()
cmy2.change_user(user=new_user['user'], password=new_user['password'],
database=new_user['database'])
cmy2.query("SELECT USER()")
current_user = cmy2.fetch_row()[0]
self.assertNotEqual(orig_user, current_user)
self.assertTrue(
u"{user}@".format(**new_user) in current_user.decode('utf8'))
cmy2.free_result()
def test_character_set_name(self):
cmy1 = MySQL(buffered=True)
self.assertRaises(MySQLInterfaceError, cmy1.character_set_name)
cmy1.connect(**self.connect_kwargs)
self.assertEqual('latin1', cmy1.character_set_name())
def test_set_character_set(self):
cmy1 = MySQL(buffered=True)
self.assertRaises(MySQLInterfaceError, cmy1.set_character_set, 'latin2')
cmy1.connect(**self.connect_kwargs)
orig = cmy1.character_set_name()
cmy1.set_character_set('utf8')
charset = cmy1.character_set_name()
self.assertNotEqual(orig, charset)
self.assertEqual('utf8', charset)
self.assertRaises(MySQLInterfaceError,
cmy1.set_character_set, 'ham_spam')
variables = ('character_set_connection',)
exp = {b'character_set_connection': b'utf8',}
self.assertEqual(exp, get_variables(cmy1, variables=variables))
exp = {b'character_set_connection': b'big5',}
cmy1.set_character_set('big5')
self.assertEqual(exp, get_variables(cmy1, variables=variables))
@unittest.skipIf(tests.MYSQL_VERSION == (5, 7, 4),
"test_get_ssl_cipher not tested with MySQL version 5.7.4")
def test_get_ssl_cipher(self):
cmy1 = MySQL(buffered=True)
self.assertRaises(MySQLInterfaceError, cmy1.get_ssl_cipher)
cmy1.connect(**self.connect_kwargs)
self.assertEqual(None, cmy1.get_ssl_cipher())
def test_hex_string(self):
config = self.connect_kwargs.copy()
cmy = MySQL(buffered=True)
table = "hex_string"
cases = {
'utf8': [
(u'ham', b"X'68616D'"),
],
'big5': [
(u'\u5C62', b"X'B9F0'")
],
'sjis': [
(u'\u005c', b"X'5C'"),
],
'gbk': [
(u'赵孟頫', b"X'D5D4C3CFEE5C'"),
(u'赵\孟\頫\\', b"X'D5D45CC3CF5CEE5C5C'"),
(u'遜', b"X'DF64'")
],
'ascii': [
('\x5c\x00\x5c', b"X'5C005C'"),
],
}
cmy.connect(**config)
def create_table(charset):
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
cmy.query("CREATE TABLE {0} (id INT, "
"c1 VARCHAR(400)) CHARACTER SET {1}".format(
table, charset))
insert = "INSERT INTO {0} (id, c1) VALUES ({{id}}, {{hex}})".format(
table)
select = "SELECT c1 FROM {0} WHERE id = {{id}}".format(table)
for encoding, data in cases.items():
create_table(encoding)
for i, info in enumerate(data):
case, exp = info
cmy.set_character_set(encoding)
hexed = cmy.hex_string(case.encode(encoding))
self.assertEqual(exp, hexed)
cmy.query(insert.format(id=i, hex=hexed.decode()))
cmy.query(select.format(id=i))
try:
fetched = fetch_rows(cmy)[0][0]
except UnicodeEncodeError:
self.fail("Could not encode {0}".format(encoding))
self.assertEqual(case, fetched.decode(encoding),
"Failed with case {0}/{1}".format(i, encoding))
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
def test_insert_id(self):
cmy = MySQL(buffered=True)
cmy.connect(**self.connect_kwargs)
table = "insert_id_test"
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
cmy.query("CREATE TABLE {0} (id INT AUTO_INCREMENT KEY)".format(table))
self.assertEqual(0, cmy.insert_id())
cmy.query("INSERT INTO {0} VALUES ()".format(table))
self.assertEqual(1, cmy.insert_id())
# Multiple-row
cmy.query("INSERT INTO {0} VALUES (), ()".format(table))
self.assertEqual(2, cmy.insert_id())
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
def test_warning_count(self):
cmy = MySQL()
cmy.connect(**self.connect_kwargs)
cmy.query("SELECT 'a' + 'b'", buffered=False)
fetch_rows(cmy)
self.assertEqual(2, cmy.warning_count())
cmy.query("SELECT 1 + 1", buffered=True)
self.assertEqual(0, cmy.warning_count())
fetch_rows(cmy)
def test_get_client_info(self):
cmy = MySQL(buffered=True)
match = re.match(r"(\d+\.\d+.\d+)(.*)", cmy.get_client_info())
self.assertNotEqual(None, match)
def test_get_client_version(self):
cmy = MySQL(buffered=True)
version = cmy.get_client_version()
self.assertTrue(isinstance(version, tuple))
self.assertTrue(all([ isinstance(v, int) for v in version]))
def test_get_host_info(self):
config = self.connect_kwargs.copy()
cmy = MySQL(buffered=True)
self.assertRaises(MySQLInterfaceError, cmy.get_host_info)
cmy.connect(**config)
if os.name == 'posix':
# On POSIX systems we would be connected by UNIX socket
self.assertTrue('via UNIX socket' in cmy.get_host_info())
# Connect using TCP/IP
config['unix_socket'] = None
cmy.connect(**config)
self.assertTrue('via TCP/IP' in cmy.get_host_info())
def test_query(self):
config = self.connect_kwargs.copy()
cmy = MySQL(buffered=True)
self.assertRaises(MySQLInterfaceError, cmy.query)
cmy.connect(**config)
self.assertRaises(MySQLInterfaceError, cmy.query, "SELECT spam")
self.assertTrue(cmy.query("SET @ham = 4"))
self.assertEqual(None, cmy.num_fields())
self.assertEqual(0, cmy.field_count())
self.assertTrue(cmy.query("SELECT @ham"))
self.assertEqual(4, cmy.fetch_row()[0])
self.assertEqual(None, cmy.fetch_row())
cmy.free_result()
self.assertTrue(cmy.query("SELECT 'ham', 'spam', 5", raw=True))
row = cmy.fetch_row()
self.assertTrue(isinstance(row[0], bytearray))
self.assertEqual(bytearray(b'spam'), row[1])
self.assertEqual(None, cmy.fetch_row())
cmy.free_result()
def test_st_server_status(self):
config = self.connect_kwargs.copy()
cmy = MySQL(buffered=True)
self.assertEqual(0, cmy.st_server_status())
cmy.connect(**config)
self.assertTrue(
cmy.st_server_status() & ServerFlag.STATUS_AUTOCOMMIT)
cmy.autocommit(False)
self.assertFalse(
cmy.st_server_status() & ServerFlag.STATUS_AUTOCOMMIT)
cmy.query("START TRANSACTION")
self.assertTrue(
cmy.st_server_status() & ServerFlag.STATUS_IN_TRANS)
cmy.query("ROLLBACK")
self.assertFalse(
cmy.st_server_status() & ServerFlag.STATUS_IN_TRANS)
def test_rollback(self):
cmy1 = MySQL(buffered=True)
cmy1.connect(**self.connect_kwargs)
cmy2 = MySQL(buffered=True)
cmy2.connect(**self.connect_kwargs)
table = "commit_test"
cmy1.query("DROP TABLE IF EXISTS {0}".format(table))
cmy1.query("CREATE TABLE {0} (c1 INT)".format(table))
cmy1.query("START TRANSACTION")
cmy1.query("INSERT INTO {0} (c1) VALUES "
"(1), (2), (3)".format(table))
cmy1.commit()
cmy2.query("SELECT * FROM {0}".format(table))
self.assertEqual([(1,), (2,), (3,)], fetch_rows(cmy2))
cmy1.query("START TRANSACTION")
cmy1.query("INSERT INTO {0} (c1) VALUES "
"(4), (5), (6)".format(table))
cmy1.rollback()
cmy2.query("SELECT * FROM {0}".format(table))
self.assertEqual(3, cmy2.num_rows())
cmy1.query("DROP TABLE IF EXISTS {0}".format(table))
def test_next_result(self):
cmy = MySQL()
cmy.connect(**self.connect_kwargs)
table = "next_result_test"
cmy.query("DROP TABLE IF EXISTS {0}".format(table))
cmy.query("CREATE TABLE {0} (c1 INT AUTO_INCREMENT KEY)".format(table))
var_names = ('"HAVE_CRYPT"', '"CHARACTER_SET_CONNECTION"')
queries = (
"SELECT 'HAM'",
"INSERT INTO {0} () VALUES ()".format(table),
"SELECT 'SPAM'",
)
exp = [
[(b'HAM',)],
{'insert_id': 1, 'affected': 1},
[(b'SPAM',)]
]
result = []
have_more = cmy.query(';'.join(queries))
self.assertTrue(have_more)
while have_more:
if cmy.have_result_set:
rows = []
row = cmy.fetch_row()
while row:
rows.append(row)
row = cmy.fetch_row()
result.append(rows)
else:
result.append({
"affected": cmy.affected_rows(),
"insert_id": cmy.insert_id()
})
have_more = cmy.next_result()
self.assertEqual(exp, result)
|