/
test_bugs.py
4558 lines (3695 loc) · 152 KB
/
test_bugs.py
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an
# additional permission to link the program and your derivative works
# with the separately licensed software that they have included with
# MySQL.
#
# Without limiting anything contained in the foregoing, this file,
# which is part of MySQL Connector/Python, is also subject to the
# Universal FOSS Exception, version 1.0, a copy of which can be found at
# http://oss.oracle.com/licenses/universal-foss-exception.
#
# 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, version 2.0, 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, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Test module for bugs
Bug test cases specific to a particular Python (major) version are loaded
from py2.bugs or py3.bugs.
This module was originally located in python2/tests and python3/tests. It
should contain bug test cases which work for both Python v2 and v3.
Whenever a bug is bout to a specific Python version, put the test cases
in tests/py2/bugs.py or tests/py3/bugs.py. It might be that these files need
to be created first.
"""
import io
import os
import gc
import tempfile
from datetime import datetime, timedelta, time
from threading import Thread
import traceback
import time
import unittest
import pickle
import tests
from tests import foreach_cnx, cnx_config
from . import PY2
from mysql.connector import (connection, cursor, conversion, protocol,
errors, constants, pooling)
from mysql.connector.optionfiles import read_option_files
from mysql.connector.catch23 import STRING_TYPES
import mysql.connector
import cpy_distutils
try:
from mysql.connector.connection_cext import CMySQLConnection
except ImportError:
# Test without C Extension
CMySQLConnection = None
ERR_NO_CEXT = "C Extension not available"
@unittest.skipIf(tests.MYSQL_VERSION == (5, 7, 4),
"Bug328998 not tested with MySQL version 5.7.4")
class Bug328998Tests(tests.MySQLConnectorTests):
"""Tests where connection timeout has been set"""
@cnx_config(connection_timeout=1)
@foreach_cnx()
def test_set_connection_timeout(self):
cur = self.cnx.cursor()
self.assertRaises(
errors.OperationalError,
cur.execute,
"SELECT SLEEP({0})".format(self.config['connection_timeout'] + 4)
)
class Bug437972Tests(tests.MySQLConnectorTests):
def test_windows_tcp_connection(self):
"""lp:437972 TCP connection to Windows"""
if os.name != 'nt':
pass
cnx = None
try:
cnx = connection.MySQLConnection(**tests.get_mysql_config())
except errors.InterfaceError:
self.fail()
if cnx:
cnx.close()
class Bug441430Tests(tests.MySQLConnectorTests):
@foreach_cnx()
def test_execute_return(self):
"""lp:441430 cursor.execute*() should return the cursor.rowcount"""
cur = self.cnx.cursor()
tbl = "buglp44130"
cur.execute("DROP TABLE IF EXISTS %s" % tbl)
cur.execute("CREATE TABLE %s (id INT)" % tbl)
cur.execute("INSERT INTO %s VALUES (%%s),(%%s)" % tbl, (1, 2,))
self.assertEqual(2, cur.rowcount)
stmt = "INSERT INTO %s VALUES (%%s)" % tbl
res = cur.executemany(stmt, [(3,), (4,), (5,), (6,), (7,), (8,)])
self.assertEqual(6, cur.rowcount)
res = cur.execute("UPDATE %s SET id = id + %%s" % tbl, (10,))
self.assertEqual(8, cur.rowcount)
cur.execute("DROP TABLE IF EXISTS {0}".format(tbl))
cur.close()
self.cnx.close()
class Bug454782(tests.MySQLConnectorTests):
"""lp:454782 fetchone() does not follow pep-0249"""
@foreach_cnx()
def test_fetch_retun_values(self):
cur = self.cnx.cursor()
self.assertEqual(None, cur.fetchone())
self.assertEqual([], cur.fetchmany())
self.assertRaises(errors.InterfaceError, cur.fetchall)
cur.close()
self.cnx.close()
class Bug454790(tests.MySQLConnectorTests):
"""lp:454790 pyformat / other named parameters broken"""
@foreach_cnx()
def test_pyformat(self):
cur = self.cnx.cursor()
data = {'name': 'Geert', 'year': 1977}
cur.execute("SELECT %(name)s,%(year)s", data)
self.assertEqual(('Geert', 1977), cur.fetchone())
data = [
{'name': 'Geert', 'year': 1977},
{'name': 'Marta', 'year': 1980}
]
cur.executemany("SELECT %(name)s,%(year)s", data)
self.assertEqual(2, cur.rowcount)
cur.close()
self.cnx.close()
class Bug480360(tests.MySQLConnectorTests):
"""lp:480360: fetchall() should return [] when no result"""
@foreach_cnx()
def test_fetchall(self):
cur = self.cnx.cursor()
# Trick to get empty result not needing any table
cur.execute("SELECT * FROM (SELECT 1) AS t WHERE 0 = 1")
self.assertEqual([], cur.fetchall())
cur.close()
self.cnx.close()
@unittest.skipIf(tests.MYSQL_VERSION >= (5, 6, 6),
"Bug380528 not tested with MySQL version >= 5.6.6")
class Bug380528(tests.MySQLConnectorTests):
"""lp:380528: we do not support old passwords"""
@foreach_cnx()
def test_old_password(self):
cur = self.cnx.cursor()
if self.config['unix_socket'] and os.name != 'nt':
user = "'myconnpy'@'localhost'"
else:
user = "'myconnpy'@'%s'" % (config['host'])
try:
cur.execute("GRANT SELECT ON %s.* TO %s" %
(self.config['database'], user))
cur.execute("SET PASSWORD FOR %s = OLD_PASSWORD('fubar')" % (user))
except:
self.fail("Failed executing grant.")
cur.close()
# Test using the newly created user
test_config = self.config.copy()
test_config['user'] = 'myconnpy'
test_config['password'] = 'fubar'
self.assertRaises(errors.NotSupportedError,
self.cnx.__class__, **test_config)
self.cnx = self.cnx.__class__(**self.config)
cur = self.cnx.cursor()
try:
cur.execute("REVOKE SELECT ON %s.* FROM %s" %
(self.config['database'], user))
cur.execute("DROP USER %s" % (user))
except mysql.connector.Error as exc:
self.fail("Failed cleaning up user {0}: {1}".format(user, exc))
cur.close()
class Bug499362(tests.MySQLConnectorTests):
"""lp:499362 Setting character set at connection fails"""
@cnx_config(charset='latin1')
@foreach_cnx()
def test_charset(self):
cur = self.cnx.cursor()
ver = self.cnx.get_server_version()
varlst = ['character_set_client', 'character_set_connection',
'character_set_results']
if ver < (5, 1, 12):
exp1 = [('character_set_client', 'latin1'),
('character_set_connection', 'latin1'),
('character_set_database', 'utf8'),
('character_set_filesystem', 'binary'),
('character_set_results', 'latin1'),
('character_set_server', 'utf8'),
('character_set_system', 'utf8')]
exp2 = [('character_set_client', 'latin2'),
('character_set_connection', 'latin2'),
('character_set_database', 'utf8'),
('character_set_filesystem', 'binary'),
('character_set_results', 'latin2'),
('character_set_server', 'utf8'),
('character_set_system', 'utf8')]
varlst = []
stmt = r"SHOW SESSION VARIABLES LIKE 'character\_set\_%%'"
exp1 = [('CHARACTER_SET_CONNECTION', 'latin1'),
('CHARACTER_SET_CLIENT', 'latin1'),
('CHARACTER_SET_RESULTS', 'latin1')]
exp2 = [('CHARACTER_SET_CONNECTION', 'latin2'),
('CHARACTER_SET_CLIENT', 'latin2'),
('CHARACTER_SET_RESULTS', 'latin2')]
elif ver >= (5, 7, 6):
# INFORMATION_SCHEMA is deprecated
exp1 = [('character_set_client', 'latin1'),
('character_set_connection', 'latin1'),
('character_set_results', 'latin1')]
exp2 = [('character_set_client', 'latin2'),
('character_set_connection', 'latin2'),
('character_set_results', 'latin2')]
stmt = ("SELECT * FROM performance_schema.session_variables "
"WHERE VARIABLE_NAME IN (%s,%s,%s)")
else:
exp1 = [('CHARACTER_SET_CONNECTION', 'latin1'),
('CHARACTER_SET_CLIENT', 'latin1'),
('CHARACTER_SET_RESULTS', 'latin1')]
exp2 = [('CHARACTER_SET_CONNECTION', 'latin2'),
('CHARACTER_SET_CLIENT', 'latin2'),
('CHARACTER_SET_RESULTS', 'latin2')]
stmt = ("SELECT * FROM INFORMATION_SCHEMA.SESSION_VARIABLES "
"WHERE VARIABLE_NAME IN (%s,%s,%s)")
cur.execute(stmt, varlst)
res1 = cur.fetchall()
self.cnx.set_charset_collation('latin2')
cur.execute(stmt, varlst)
res2 = cur.fetchall()
cur.close()
self.cnx.close()
self.assertTrue(tests.cmp_result(exp1, res1))
self.assertTrue(tests.cmp_result(exp2, res2))
class Bug501290(tests.MySQLConnectorTests):
"""lp:501290 Client flags are set to None when connecting"""
def _setup(self):
self.capabilities = self.cnx._handshake['capabilities']
self.default_flags = constants.ClientFlag.get_default()
if self.capabilities & constants.ClientFlag.PLUGIN_AUTH:
self.default_flags |= constants.ClientFlag.PLUGIN_AUTH
@foreach_cnx()
def test_default(self):
self._setup()
for flag in constants.ClientFlag.default:
self.assertTrue(self.cnx._client_flags & flag)
@foreach_cnx()
def test_set_unset(self):
self._setup()
orig = self.cnx._client_flags
exp = self.default_flags | constants.ClientFlag.COMPRESS
self.cnx.set_client_flags([constants.ClientFlag.COMPRESS])
for flag in constants.ClientFlag.default:
self.assertTrue(self.cnx._client_flags & flag)
self.cnx.set_client_flags([-constants.ClientFlag.COMPRESS])
self.assertEqual(self.cnx._client_flags, orig)
@foreach_cnx()
def test_isset_client_flag(self):
self._setup()
flag = constants.ClientFlag.COMPRESS
data = self.default_flags | flag
self.cnx._client_flags = data
self.assertEqual(True, self.cnx.isset_client_flag(flag))
class Bug507466(tests.MySQLConnectorTests):
"""lp:507466 BIT values are not converted correctly to Python"""
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
try:
cur = cnx.cursor()
cur.execute("DROP TABLE IF EXISTS myconnpy_bits")
except:
pass
cnx.close()
@foreach_cnx()
def test_bits(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS myconnpy_bits")
cur.execute("""CREATE TABLE `myconnpy_bits` (
`id` int NOT NULL AUTO_INCREMENT,
`c1` bit(8) DEFAULT NULL,
`c2` bit(16) DEFAULT NULL,
`c3` bit(24) DEFAULT NULL,
`c4` bit(32) DEFAULT NULL,
`c5` bit(40) DEFAULT NULL,
`c6` bit(48) DEFAULT NULL,
`c7` bit(56) DEFAULT NULL,
`c8` bit(64) DEFAULT NULL,
PRIMARY KEY (id)
)
""")
insert = """insert into myconnpy_bits (c1,c2,c3,c4,c5,c6,c7,c8)
values (%s,%s,%s,%s,%s,%s,%s,%s)"""
select = "SELECT c1,c2,c3,c4,c5,c6,c7,c8 FROM myconnpy_bits ORDER BY id"
data = []
data.append((0, 0, 0, 0, 0, 0, 0, 0))
data.append((
1 << 7, 1 << 15, 1 << 23, 1 << 31,
1 << 39, 1 << 47, 1 << 55, (1 << 63)-1,
))
cur.executemany(insert, data)
cur.execute(select)
rows = cur.fetchall()
self.assertEqual(rows, data)
self.cnx.close()
class Bug519301(tests.MySQLConnectorTests):
"""lp:519301 Temporary connection failures with 2 exceptions"""
@foreach_cnx()
def test_auth(self):
config = self.config.copy()
config.pop('unix_socket')
config['user'] = 'ham'
config['password'] = 'spam'
for _ in range(1, 100):
try:
cnx = self.cnx.__class__(**config)
except errors.ProgrammingError:
pass
except errors.Error as err:
self.fail("Failing authenticating: {0}".format(str(err)))
except:
raise
else:
cnx.close()
class Bug524668(tests.MySQLConnectorTests):
"""lp:524668 Error in server handshake with latest code"""
def test_handshake(self):
handshake = bytearray(
b'\x47\x00\x00\x00\x0a\x35\x2e\x30\x2e\x33\x30\x2d\x65'
b'\x6e\x74\x65\x72\x70\x72\x69\x73\x65\x2d\x67\x70\x6c'
b'\x2d\x6c\x6f'
b'\x67\x00\x09\x01\x00\x00\x68\x34\x69\x36\x6f\x50\x21\x4f\x00'
b'\x2c\xa2\x08\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00'
b'\x00\x00\x4c\x6e\x67\x39\x26\x50\x44\x40\x57\x72\x59\x48\x00'
)
prtcl = protocol.MySQLProtocol()
try:
prtcl.parse_handshake(handshake)
except:
self.fail("Failed handling handshake")
class Bug571201(tests.MySQLConnectorTests):
"""lp:571201 Problem with more than one statement at a time"""
def setUp(self):
self.tbl = 'Bug571201'
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
try:
cur = cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl))
except:
pass
cnx.close()
@foreach_cnx()
def test_multistmts(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl))
cur.execute(("CREATE TABLE {0} ( "
"id INT AUTO_INCREMENT KEY, "
"c1 INT)").format(self.tbl))
stmts = [
"SELECT * FROM %s" % (self.tbl),
"INSERT INTO %s (c1) VALUES (10),(20)" % (self.tbl),
"SELECT * FROM %s" % (self.tbl),
]
result_iter = cur.execute(';'.join(stmts), multi=True)
self.assertEqual(None, next(result_iter).fetchone())
self.assertEqual(2, next(result_iter).rowcount)
exp = [(1, 10), (2, 20)]
self.assertEqual(exp, next(result_iter).fetchall())
self.assertRaises(StopIteration, next, result_iter)
self.cnx.close()
class Bug551533and586003(tests.MySQLConnectorTests):
"""lp: 551533 as 586003: impossible to retrieve big result sets"""
def setUp(self):
self.tbl = 'Bug551533'
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
cnx.cmd_query("DROP TABLE IF EXISTS {table}".format(table=self.tbl))
cnx.close()
@cnx_config(connection_timeout=10)
@foreach_cnx()
def test_select(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {table}".format(table=self.tbl))
cur.execute(
("CREATE TABLE {table} (id INT AUTO_INCREMENT KEY, "
"c1 VARCHAR(100) DEFAULT 'abcabcabcabcabcabcabcabcabcabc') "
"ENGINE=INNODB").format(table=self.tbl)
)
insert = "INSERT INTO {table} (id) VALUES (%s)".format(table=self.tbl)
exp = 20000
cur.executemany(insert, [(None,)] * exp)
self.cnx.commit()
cur.execute(
'SELECT * FROM {table} LIMIT 20000'.format(table=self.tbl))
try:
rows = cur.fetchall()
except errors.Error as err:
self.fail("Failed retrieving big result set: {0}".format(err))
else:
self.assertEqual(exp, cur.rowcount)
self.assertEqual(exp, len(rows))
class Bug675425(tests.MySQLConnectorTests):
"""lp: 675425: Problems with apostrophe"""
def setUp(self):
self.tbl = 'Bug675425'
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
cur = cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl))
cnx.close()
@foreach_cnx()
def test_executemany_escape(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl))
cur.execute("CREATE TABLE {0} (c1 VARCHAR(30),"
" c2 VARCHAR(30))".format(self.tbl))
data = [
("ham", "spam",),
("spam", "ham",),
("ham \\' spam", "spam ' ham",)
]
sql = "INSERT INTO {0} VALUES (%s, %s)".format(self.tbl)
try:
cur.executemany(sql, data)
except Exception as exc:
self.fail(str(exc))
self.cnx.close()
class Bug695514(tests.MySQLConnectorTests):
"""lp: 695514: Infinite recursion when setting connection client_flags"""
@foreach_cnx()
def test_client_flags(self):
try:
config = tests.get_mysql_config()
config['connection_timeout'] = 2
config['client_flags'] = constants.ClientFlag.get_default()
self.cnx = self.cnx.__class__(**config)
except:
self.fail("Failed setting client_flags using integer")
class Bug809033(tests.MySQLConnectorTests):
"""lp: 809033: Lost connection causes infinite loop"""
def setUp(self):
self.table_name = 'Bug809033'
def _setup(self):
self.cnx.cmd_query("DROP TABLE IF EXISTS {0}".format(self.table_name))
table = (
"CREATE TABLE {table} ("
" id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
" c1 VARCHAR(255) DEFAULT '{default}',"
" PRIMARY KEY (id)"
")"
).format(table=self.table_name, default='a' * 255)
self.cnx.cmd_query(table)
stmt = "INSERT INTO {table} (id) VALUES {values}".format(
table=self.table_name,
values=','.join(['(NULL)'] * 1024)
)
self.cnx.cmd_query(stmt)
def tearDown(self):
try:
cnx = connection.MySQLConnection(**tests.get_mysql_config())
cnx.cmd_query(
"DROP TABLE IF EXISTS {0}".format(self.table_name))
cnx.close()
except:
pass
@foreach_cnx()
def test_lost_connection(self):
self._setup()
def kill(connection_id):
"""Kill connection using separate connection"""
killer = connection.MySQLConnection(**tests.get_mysql_config())
time.sleep(1)
killer.cmd_query("KILL {0}".format(connection_id))
killer.close()
def sleepy_select(cnx):
"""Execute a SELECT statement which takes a while to complete"""
cur = cnx.cursor()
# Ugly query ahead!
stmt = "SELECT x1.*, x2.* from {table} as x1, {table} as x2".format(
table=self.table_name)
cur.execute(stmt)
# Save the error so we can check in the calling thread
cnx.test_error = None
try:
cur.fetchall()
except errors.Error as err:
cnx.test_error = err
worker = Thread(target=sleepy_select, args=[self.cnx])
killer = Thread(target=kill, args=[self.cnx.connection_id])
worker.start()
killer.start()
worker.join()
killer.join()
self.assertTrue(
isinstance(self.cnx.test_error,
(errors.InterfaceError, errors.OperationalError))
)
self.cnx.close()
class Bug865859(tests.MySQLConnectorTests):
"""lp: 865859: sock.recv fails to return in some cases (infinite wait)"""
def setUp(self):
self.table_name = 'Bug865859'
@cnx_config(connection_timeout=1)
@foreach_cnx()
def test_reassign_connection(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.table_name))
cur.execute("CREATE TABLE {0} (c1 INT)".format(self.table_name))
cur.execute("INSERT INTO {0} (c1) VALUES (1)".format(self.table_name))
try:
# We create a new cnx, replacing current
self.cnx = self.cnx.__class__(**self.config)
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.table_name))
except errors.InterfaceError as err:
self.fail(
"Connection was not closed, we got timeout: {0}".format(err))
else:
cur.close()
self.cnx.close()
class BugOra13395083(tests.MySQLConnectorTests):
"""BUG#13395083: Using time zones"""
def setUp(self):
self.table_name = 'BugOra13395083'
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
cur = cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.table_name))
@cnx_config(time_zone="+00:00")
@foreach_cnx()
def test_time_zone(self):
utc = tests.UTCTimeZone()
testzone = tests.TestTimeZone(+2)
# Store a datetime in UTC into a TIMESTAMP column
now_utc = datetime.utcnow().replace(microsecond=0, tzinfo=utc)
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.table_name))
cur.execute("CREATE TABLE {0} (c1 TIMESTAMP)".format(self.table_name))
cur.execute(
"INSERT INTO {0} (c1) VALUES (%s)".format(self.table_name),
(now_utc,))
self.cnx.commit()
cur.execute("SELECT c1 FROM {0}".format(self.table_name))
row = cur.fetchone()
self.assertEqual(now_utc, row[0].replace(tzinfo=utc))
self.cnx.time_zone = "+02:00"
cur.execute("SELECT c1 FROM {0}".format(self.table_name))
row = cur.fetchone()
self.assertEqual(now_utc.astimezone(testzone),
row[0].replace(tzinfo=testzone))
self.cnx.close()
class BugOra13392739(tests.MySQLConnectorTests):
"""BUG#13392739: MySQLConnection.ping()"""
@cnx_config(connection_timeout=2, unix_socket=None)
@foreach_cnx()
def test_ping(self):
cnx = self.cnx.__class__()
self.assertRaises(errors.InterfaceError, cnx.ping)
try:
self.cnx.ping()
except Exception as e:
self.fail("Error raised although connection should be "
"available (%s)." % e)
self.cnx.close()
self.assertRaises(errors.InterfaceError, self.cnx.ping)
try:
self.cnx.ping(reconnect=True)
except Exception as e:
self.fail("Error raised although ping should reconnect. (%s)" % e)
# Temper with the host to which we reconnect to simulate the
# MySQL not being available.
self.cnx.disconnect()
self.cnx._host = 'some-unknown-host-somwhere-on.mars'
self.assertRaises(errors.InterfaceError, self.cnx.ping, reconnect=True)
@cnx_config(connection_timeout=2, unix_socket=None)
@foreach_cnx()
def test_reconnect(self):
self.cnx.disconnect()
self.assertRaises(errors.InterfaceError, self.cnx.ping)
try:
self.cnx.reconnect()
except:
self.fail("Errors raised although connection should have been "
"reconnected.")
self.cnx.disconnect()
# Temper with the host to which we reconnect to simulate the
# MySQL not being available.
self.cnx._host = 'some-unknown-host-somwhere-on-mars.example.com'
self.assertRaises(errors.InterfaceError, self.cnx.reconnect)
try:
self.cnx.reconnect(attempts=3)
except errors.InterfaceError as exc:
self.assertTrue('3 attempt(s)' in str(exc))
class BugOra13435186(tests.MySQLConnectorTests):
def setUp(self):
self.sample_size = 100
self.tolerate = 5
self._reset_samples()
self.samples = [0, ] * self.sample_size
gc.collect()
def _reset_samples(self):
self.samples = [0, ] * self.sample_size
def _assert_flat_line(self, samples):
counters = {}
for value in samples:
try:
counters[value] = counters[value] + 1
except KeyError:
counters[value] = 1
if len(counters) > self.tolerate:
self.fail("Counters of collected object higher than tolerated.")
def test_converter(self):
for i in range(0, self.sample_size):
conversion.MySQLConverter()
self.samples[i] = len(gc.get_objects())
self._assert_flat_line(self.samples)
@foreach_cnx()
def test_connection(self):
# Create a connection and close using close()-method
for i in range(0, self.sample_size):
cnx = self.cnx.__class__(**self.config)
cnx.close()
self.samples[i] = len(gc.get_objects())
self._assert_flat_line(self.samples)
self._reset_samples()
# Create a connection and rely on destructor to close
for i in range(0, self.sample_size):
cnx = self.cnx.__class__(**self.config)
self.samples[i] = len(gc.get_objects())
self._assert_flat_line(self.samples)
@foreach_cnx()
def test_cursor(self):
# Create a cursor and close using close()-method
for i in range(0, self.sample_size):
cursor = self.cnx.cursor()
cursor.close()
self.samples[i] = len(gc.get_objects())
self._assert_flat_line(self.samples)
self._reset_samples()
# Create a cursor and rely on destructor to close
for i in range(0, self.sample_size):
cursor = self.cnx.cursor()
self.samples[i] = len(gc.get_objects())
self._assert_flat_line(self.samples)
class BugOra14184643(tests.MySQLConnectorTests):
"""BUG#14184643: cmd_query() disregards waiting results"""
@foreach_cnx()
def test_cmd_query(self):
self.cnx.cmd_query('SELECT 1')
self.assertRaises(errors.InternalError, self.cnx.cmd_query,
'SELECT 2')
@foreach_cnx(connection.MySQLConnection)
def test_get_rows(self):
self.cnx.cmd_query('SELECT 1')
self.cnx.get_rows()
self.assertRaises(errors.InternalError, self.cnx.get_rows)
self.cnx.cmd_query('SELECT 1')
self.cnx.get_row()
self.assertEqual(None, self.cnx.get_row()[0])
self.assertRaises(errors.InternalError, self.cnx.get_row)
@unittest.skipIf(not CMySQLConnection, ERR_NO_CEXT)
@foreach_cnx(CMySQLConnection)
def test_get_rows(self):
self.cnx.cmd_query('SELECT 1')
while True:
self.cnx.get_rows()
if not self.cnx.next_result():
break
else:
self.fail("Found multiple results where only 1 was expected")
self.assertRaises(errors.InternalError, self.cnx.get_rows)
@foreach_cnx()
def test_cmd_statistics(self):
self.cnx.cmd_query('SELECT 1')
self.assertRaises(errors.InternalError, self.cnx.cmd_statistics)
self.cnx.get_rows()
class BugOra14208326(tests.MySQLConnectorTests):
"""BUG#14208326: cmd_query() does not handle multiple statements"""
def setUp(self):
self.table = "BugOra14208326"
def _setup(self):
self.cnx.cmd_query("DROP TABLE IF EXISTS %s" % self.table)
self.cnx.cmd_query("CREATE TABLE %s (id INT)" % self.table)
def tearDown(self):
config = tests.get_mysql_config()
self.cnx = connection.MySQLConnection(**config)
self.cnx.cmd_query("DROP TABLE IF EXISTS {0}".format(self.table))
@foreach_cnx(connection.MySQLConnection)
def test_cmd_query(self):
self._setup()
self.assertRaises(errors.InterfaceError,
self.cnx.cmd_query, 'SELECT 1; SELECT 2')
@unittest.skipIf(not CMySQLConnection, ERR_NO_CEXT)
@foreach_cnx(CMySQLConnection)
def test_cmd_query_iter(self):
self._setup()
stmt = 'SELECT 1; INSERT INTO %s VALUES (1),(2); SELECT 3'
results = []
try:
for result in self.cnx.cmd_query_iter(stmt % self.table):
results.append(result)
if 'columns' in result:
results.append(self.cnx.get_rows())
except NotImplementedError:
# Some cnx are not implementing this
if not isinstance(self.cnx, CMySQLConnection):
raise
class BugOra14201459(tests.MySQLConnectorTests):
"""BUG#14201459: Server error 1426 should raise ProgrammingError"""
def setUp(self):
self.tbl = 'Bug14201459'
def tearDown(self):
config = tests.get_mysql_config()
self.cnx = connection.MySQLConnection(**config)
self._setup()
def _setup(self):
self.cnx.cmd_query("DROP TABLE IF EXISTS %s" % (self.tbl))
@foreach_cnx()
def test_error1426(self):
cur = self.cnx.cursor()
self._setup()
create = "CREATE TABLE %s (c1 TIME(7))" % self.tbl
try:
cur.execute(create)
except errors.ProgrammingError as exception:
if tests.MYSQL_VERSION < (5, 6, 4) and exception.errno != 1064:
self.fail("ProgrammingError is not Error 1064")
elif tests.MYSQL_VERSION >= (5, 6, 4) and exception.errno != 1426:
self.fail("ProgrammingError is not Error 1426")
else:
self.fail("ProgrammingError not raised")
class BugOra14231160(tests.MySQLConnectorTests):
"""BUG#14231160: lastrowid, description and rowcount read-only"""
@foreach_cnx()
def test_readonly_properties(self):
cur = self.cnx.cursor()
for attr in ('description', 'rowcount', 'lastrowid'):
try:
setattr(cur, attr, 'spam')
except AttributeError:
# It's readonly, that's OK
pass
else:
self.fail('Need read-only property: {0}'.format(attr))
class BugOra14259954(tests.MySQLConnectorTests):
"""BUG#14259954: ON DUPLICATE KEY UPDATE VALUE FAILS REGEX"""
def setUp(self):
self.tbl = 'Bug14259954'
def _setup(self):
cur = self.cnx.cursor()
cur.execute("DROP TABLE IF EXISTS %s" % (self.tbl))
create = ("CREATE TABLE %s ( "
"`id` int(11) NOT NULL AUTO_INCREMENT, "
"`c1` int(11) NOT NULL DEFAULT '0', "
"PRIMARY KEY (`id`,`c1`))" % (self.tbl))
cur.execute(create)
def tearDown(self):
config = tests.get_mysql_config()
cnx = connection.MySQLConnection(**config)
cur = cnx.cursor()
cur.execute("DROP TABLE IF EXISTS {0}".format(self.tbl))
@foreach_cnx()
def test_executemany(self):
self._setup()
cur = self.cnx.cursor()
query = ("INSERT INTO %s (id,c1) VALUES (%%s,%%s) "
"ON DUPLICATE KEY UPDATE c1=VALUES(c1)") % self.tbl
try:
cur.executemany(query, [(1, 1), (2, 2)])
except errors.ProgrammingError as err:
self.fail("Regular expression fails with executemany(): %s" %
err)
class BugOra14548043(tests.MySQLConnectorTests):
"""BUG#14548043: ERROR MESSAGE SHOULD BE IMPROVED TO DIAGNOSE THE PROBLEM
"""
@foreach_cnx()
def test_unix_socket(self):
config = self.config.copy()
config['unix_socket'] = os.path.join(