forked from mysql/mysql-connector-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unittests.py
1223 lines (1091 loc) · 38.7 KB
/
unittests.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009, 2023, Oracle and/or its affiliates.
#
# 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
"""Script for running unittests
unittests.py launches all or selected unit tests. For more information and
options, simply do:
shell> python unittests.py --help
The unittest.py script will check for tests in Python source files prefixed
with 'test_' in the folder tests/.
Examples:
Running unit tests using MySQL installed under /opt
shell> python unittests.py --with-mysql=/opt/mysql/mysql-5.7
Executing unit tests for cursor module
shell> python unittests.py -t cursor
Keep the MySQL server(s) running; speeds up multiple runs:
shell> python unittests.py --keep
Force shutting down of still running MySQL servers, and bootstrap again:
shell> python unittests.py --force
Show a more verbose and comprehensive output of tests (see --help to safe
information to a database):
shell> python unittests.py --keep --stats
Run tests using IPv6:
shell> python unittests.py --ipv6
unittests.py has exit status 0 when tests were ran successfully, 1 otherwise.
"""
import os
import platform
import re
import shutil
import sys
import time
import unittest
try:
from urlparse import urlsplit
except ImportError:
# Python 3
from urllib.parse import urlsplit
import logging
try:
from argparse import ArgumentParser
except ImportError:
# Python v2.6
from optparse import OptionParser
try:
from unittest import TextTestResult
except ImportError:
# Compatibility with Python v2.6
from unittest import _TextTestResult as TextTestResult
import tests
from tests import mysqld
_TOPDIR = os.path.dirname(os.path.realpath(__file__))
LOGGER = logging.getLogger(tests.LOGGER_NAME)
tests.setup_logger(LOGGER)
# Only run for supported Python Versions
if not (((2, 6) <= sys.version_info < (3, 0)) or sys.version_info >= (3, 3)):
LOGGER.error(
"Python v%d.%d is not supported",
sys.version_info[0],
sys.version_info[1],
)
sys.exit(1)
else:
sys.path.insert(0, os.path.join(_TOPDIR, "lib"))
sys.path.insert(0, os.path.join(_TOPDIR))
tests.TEST_BUILD_DIR = os.path.join(_TOPDIR, "build", "testing")
sys.path.insert(0, tests.TEST_BUILD_DIR)
# MySQL option file template. Platform specifics dynamically added later.
MY_CNF = """
# MySQL option file for MySQL Connector/Python tests
[mysqld]
plugin-load={mysqlx_plugin}
loose_mysqlx_port={mysqlx_port}
{mysqlx_bind_address}
max_allowed_packet = 26777216
net_read_timeout = 120
net_write_timeout = 120
connect_timeout = 60
basedir = {basedir}
datadir = {datadir}
tmpdir = {tmpdir}
port = {port}
socket = {unix_socket}
bind_address = {bind_address}
pid-file = {pid_file}
skip_name_resolve
server_id = {serverid}
sql_mode = ""
default_time_zone = +00:00
log-error = mysqld_{name}.err
log-bin = mysqld_{name}_bin
local_infile = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_file_size = 1Gb
general_log_file = general_{name}.log
{secure_file_priv}
"""
# Platform specifics
if os.name == "nt":
MY_CNF += "\n".join(
(
"ssl-ca = {ssl_ca}",
"ssl-cert = {ssl_cert}",
"ssl-key = {ssl_key}",
)
)
MYSQL_DEFAULT_BASE = os.environ.get(
"MYSQL",
os.path.join("C:/", "Program Files", "MySQL", "MySQL Server 8.0"),
)
else:
MY_CNF += "\n".join(
(
"ssl-ca = {ssl_ca}",
"ssl-cert = {ssl_cert}",
"ssl-key = {ssl_key}",
"innodb_flush_method = O_DIRECT",
)
)
MYSQL_DEFAULT_BASE = os.environ.get(
"MYSQL", os.path.join("/", "usr", "local", "mysql")
)
MY_CNF += "\nssl={ssl}"
MYSQL_DEFAULT_TOPDIR = _TOPDIR
_UNITTESTS_CMD_ARGS = {
("-T", "--one-test"): {
"dest": "onetest",
"metavar": "NAME",
"help": (
"Particular test to execute, format: "
"<module>[.<class>[.<method>]]. For example, to run a particular "
"test BugOra13392739.test_reconnect() from the tests.test_bugs "
"module, use following value for the -T option: "
" tests.test_bugs.BugOra13392739.test_reconnect"
),
},
("-t", "--test"): {
"dest": "testcase",
"metavar": "NAME",
"help": "Tests to execute, see --help-tests for more information",
},
("-r", "--test-regex"): {
"dest": "test_regex_pattern",
"metavar": "NAME",
"help": "Run tests matching the regex pattern.",
},
("-l", "--log"): {
"dest": "logfile",
"metavar": "NAME",
"default": None,
"help": "Log file location (if not given, logging is disabled)",
},
("", "--force"): {
"dest": "force",
"action": "store_true",
"default": False,
"help": "Remove previous MySQL test installation.",
},
("", "--keep"): {
"dest": "keep",
"action": "store_true",
"default": False,
"help": "Keep MySQL installation (i.e. for debugging)",
},
("", "--debug"): {
"dest": "debug",
"action": "store_true",
"default": False,
"help": "Show/Log debugging messages",
},
("", "--verbosity"): {
"dest": "verbosity",
"metavar": "NUMBER",
"default": 0,
"type": int,
"help": "Verbosity of unittests (default 0)",
"type_optparse": "int",
},
("", "--stats"): {
"dest": "stats",
"default": False,
"action": "store_true",
"help": "Show timings of each individual test.",
},
("", "--stats-host"): {
"dest": "stats_host",
"default": None,
"metavar": "NAME",
"help": (
"MySQL server for saving unittest statistics. Specify this option "
"to start saving results to a database. Implies --stats."
),
},
("", "--stats-port"): {
"dest": "stats_port",
"default": 3306,
"metavar": "PORT",
"help": (
"TCP/IP port of the MySQL server for saving unittest statistics. "
"Implies --stats. (default 3306)"
),
},
("", "--stats-user"): {
"dest": "stats_user",
"default": "root",
"metavar": "NAME",
"help": (
"User for connecting with the MySQL server for saving unittest "
"statistics. Implies --stats. (default root)"
),
},
("", "--stats-password"): {
"dest": "stats_password",
"default": "",
"metavar": "PASSWORD",
"help": (
"Password for connecting with the MySQL server for saving unittest "
"statistics. Implies --stats. (default to no password)"
),
},
("", "--stats-db"): {
"dest": "stats_db",
"default": "test",
"metavar": "NAME",
"help": (
"Database name for saving unittest statistics. "
"Implies --stats. (default test)"
),
},
("", "--with-mysql"): {
"dest": "mysql_basedir",
"metavar": "NAME",
"default": MYSQL_DEFAULT_BASE,
"help": (
"Installation folder of the MySQL server. " "(default {default})"
).format(default=MYSQL_DEFAULT_BASE),
},
("", "--with-mysql-share"): {
"dest": "mysql_sharedir",
"metavar": "NAME",
"default": None,
"help": "share folder of the MySQL server (default <basedir>/share)",
},
("", "--mysql-topdir"): {
"dest": "mysql_topdir",
"metavar": "NAME",
"default": MYSQL_DEFAULT_TOPDIR,
"help": (
"Where to bootstrap the new MySQL instances for testing. "
"(default {default})"
).format(default=MYSQL_DEFAULT_TOPDIR),
},
("", "--secure-file-priv"): {
"dest": "secure_file_priv",
"metavar": "DIRECTORY",
"default": None,
"help": "MySQL server option, can be empty to disable",
},
("", "--bind-address"): {
"dest": "bind_address",
"metavar": "NAME",
"default": "127.0.0.1",
"help": "IP address to bind to",
},
("-H", "--host"): {
"dest": "host",
"metavar": "NAME",
"default": os.environ.get("MYSQL_HOST", "127.0.0.1"),
"help": "Hostname or IP address for TCP/IP connections to use in a "
"bootstrapped server or to use with an external server.",
},
("-P", "--port"): {
"dest": "port",
"metavar": "NUMBER",
"default": os.environ.get("MYSQL_PORT", 3306),
"type": int,
"help": "First TCP/IP port to use in a bootstrapped server or to use "
"with an external server.",
"type_optparse": int,
},
("", "--mysqlx-port"): {
"dest": "mysqlx_port",
"metavar": "NUMBER",
"default": os.environ.get("MYSQLX_PORT", 33060),
"type": int,
"help": "First TCP/IP port to use for the mysqlx protocol in a "
"bootstrapped server or to use with an external server.",
"type_optparse": int,
},
("", "--user"): {
"dest": "user",
"default": os.environ.get("MYSQL_USER", "root"),
"metavar": "NAME",
"help": "User to use with an external server.",
},
("", "--password"): {
"dest": "password",
"default": os.environ.get("MYSQL_PASSWORD", ""),
"metavar": "PASSWORD",
"help": "Password to use with an external server.",
},
("", "--unix-socket"): {
"dest": "unix_socket_folder",
"metavar": "NAME",
"help": "Folder where UNIX Sockets will be created or the unix socket "
"to be used with an external server.",
},
("", "--ipv6"): {
"dest": "ipv6",
"action": "store_true",
"default": False,
"help": "Use IPv6 to run tests. This sets --bind-address=:: --host=::1.",
},
("", "--with-django"): {
"dest": "django_path",
"metavar": "NAME",
"default": None,
"help": "Location of Django (none installed source)",
},
("", "--help-tests"): {
"dest": "show_tests",
"action": "store_true",
"help": "Show extra information about test groups",
},
("", "--skip-install"): {
"dest": "skip_install",
"action": "store_true",
"default": False,
"help": "Skip installation of Connector/Python, reuse previous.",
},
("", "--use-external-server"): {
"dest": "use_external_server",
"action": "store_true",
"default": False,
"help": "Use an external server instead of bootstrap a server.",
},
("", "--with-mysql-capi"): {
"dest": "mysql_capi",
"metavar": "NAME",
"default": None,
"help": "Location of MySQL C API installation or full path to mysql_config",
},
("", "--with-openssl-include-dir"): {
"dest": "openssl_include_dir",
"metavar": "NAME",
"default": os.environ.get("MYSQLXPB_OPENSSL_INCLUDE_DIR"),
"help": ("Location of OpenSSL include directory"),
},
("", "--with-openssl-lib-dir"): {
"dest": "openssl_lib_dir",
"metavar": "NAME",
"default": os.environ.get("MYSQLXPB_OPENSSL_LIB_DIR"),
"help": "Location of OpenSSL library directory",
},
("", "--with-protobuf-include-dir"): {
"dest": "protobuf_include_dir",
"metavar": "NAME",
"default": os.environ.get("MYSQLXPB_PROTOBUF_INCLUDE_DIR"),
"help": "Location of Protobuf include directory",
},
("", "--with-protobuf-lib-dir"): {
"dest": "protobuf_lib_dir",
"metavar": "NAME",
"default": os.environ.get("MYSQLXPB_PROTOBUF_LIB_DIR"),
"help": "Location of Protobuf library directory",
},
("", "--with-protoc"): {
"dest": "protoc",
"metavar": "NAME",
"default": os.environ.get("MYSQLXPB_PROTOC"),
"help": "Location of Protobuf protoc binary",
},
("", "--extra-compile-args"): {
"dest": "extra_compile_args",
"metavar": "NAME",
"default": None,
"help": "Extra compile args for the C extension",
},
("", "--extra-link-args"): {
"dest": "extra_link_args",
"metavar": "NAME",
"default": None,
"help": "Extra link args for the C extension",
},
}
def _get_arg_parser():
"""Parse command line ArgumentParser
This function parses the command line arguments and returns the parser.
It works with both optparse and argparse where available.
"""
def _clean_optparse(adict):
"""Remove items from dictionary ending with _optparse"""
new_dict = {}
for key in adict.keys():
if not key.endswith("_optparse"):
new_dict[key] = adict[key]
return new_dict
new = True
try:
parser = ArgumentParser()
add = parser.add_argument
except NameError:
# Fallback to old optparse
new = False
parser = OptionParser()
add = parser.add_option
for flags, params in _UNITTESTS_CMD_ARGS.items():
if new:
flags = [i for i in flags if i]
add(*flags, **_clean_optparse(params))
return parser
def _show_help(msg=None, parser=None, exit_code=0):
"""Show the help of the given parser and exits
If exit_code is -1, this function will not call sys.exit().
"""
tests.printmsg(msg)
if parser is not None:
parser.print_help()
if exit_code > -1:
sys.exit(exit_code)
def get_stats_tablename():
return "myconnpy_{version}".format(
version="_".join([str(i) for i in mysql.connector.__version_info__[0:3]])
)
def get_stats_field(pyver=None, myver=None):
if not pyver:
pyver = ".".join([str(i) for i in sys.version_info[0:2]])
if not myver:
myver = ".".join([str(i) for i in tests.MYSQL_SERVERS[0].version[0:2]])
return "py{python}my{mysql}".format(
python=pyver.replace(".", ""), mysql=myver.replace(".", "")
)
class StatsTestResult(TextTestResult):
"""Store test results in a database"""
separator1 = "=" * 78
separator2 = "-" * 78
def __init__(self, stream, descriptions, verbosity, dbcnx=None):
super(StatsTestResult, self).__init__(stream, descriptions, verbosity)
self.stream = stream
self.showAll = 0
self.dots = 0
self.descriptions = descriptions
self._start_time = None
self._stop_time = None
self.elapsed_time = None
self._dbcnx = dbcnx
self._name = None
@staticmethod
def get_description(test): # pylint: disable=R0201
"""Return test description, if needed truncated to 60 characters"""
return "{0:.<60s} ".format(str(test)[0:58])
def startTest(self, test):
super(StatsTestResult, self).startTest(test)
self.stream.write(self.get_description(test))
self.stream.flush()
self._start_time = time.time()
def addSuccess(self, test):
super(StatsTestResult, self).addSuccess(test)
self._stop_time = time.time()
self.elapsed_time = self._stop_time - self._start_time
fmt = "{timing:>8.3f}s {state:<20s}"
self.stream.writeln(fmt.format(state="ok", timing=self.elapsed_time))
if self._dbcnx:
cur = self._dbcnx.cursor()
stmt = (
"INSERT INTO {table} (test_case, {field}) "
"VALUES (%s, %s) ON DUPLICATE KEY UPDATE {field} = %s"
).format(table=get_stats_tablename(), field=get_stats_field())
cur.execute(stmt, (str(test), self.elapsed_time, self.elapsed_time))
cur.close()
def _save_not_ok(self, test):
cur = self._dbcnx.cursor()
stmt = (
"INSERT INTO {table} (test_case, {field}) "
"VALUES (%s, %s) ON DUPLICATE KEY UPDATE {field} = %s"
).format(table=get_stats_tablename(), field=get_stats_field())
cur.execute(stmt, (str(test), -1, -1))
cur.close()
def addError(self, test, err):
super(StatsTestResult, self).addError(test, err)
self.stream.writeln("ERROR")
if self._dbcnx:
self._save_not_ok(test)
def addFailure(self, test, err):
super(StatsTestResult, self).addFailure(test, err)
self.stream.writeln("FAIL")
if self._dbcnx:
self._save_not_ok(test)
def addSkip(self, test, reason):
try:
super(StatsTestResult, self).addSkip(test, reason)
except AttributeError:
# We are using Python v2.6/v3.1
pass
self.stream.writeln("skipped")
if self._dbcnx:
self._save_not_ok(test)
def addExpectedFailure(self, test, err):
super(StatsTestResult, self).addExpectedFailure(test, err)
self.stream.writeln("expected failure")
if self._dbcnx:
self._save_not_ok(test)
def addUnexpectedSuccess(self, test):
super(StatsTestResult, self).addUnexpectedSuccess(test)
self.stream.writeln("unexpected success")
if self._dbcnx:
self._save_not_ok(test)
class StatsTestRunner(unittest.TextTestRunner):
"""Committing results test results"""
resultclass = StatsTestResult
def __init__(
self,
stream=sys.stderr,
descriptions=False,
verbosity=1,
failfast=False,
buffer=False,
resultclass=None,
dbcnx=None,
):
try:
super(StatsTestRunner, self).__init__(
stream=sys.stderr,
descriptions=descriptions,
verbosity=verbosity,
failfast=False,
buffer=False,
)
except TypeError:
# Compatibility with Python v2.6
super(StatsTestRunner, self).__init__(
stream=sys.stderr,
descriptions=descriptions,
verbosity=verbosity,
)
self._dbcnx = dbcnx
def _makeResult(self):
return self.resultclass(
self.stream, self.descriptions, self.verbosity, dbcnx=self._dbcnx
)
def run(self, test):
result = super(StatsTestRunner, self).run(test)
if self._dbcnx:
self._dbcnx.commit()
return result
class BasicTestResult(TextTestResult):
"""Basic test result"""
def addSkip(self, test, reason):
"""Save skipped reasons"""
if self.showAll:
self.stream.writeln("skipped")
elif self.dots:
self.stream.write("s")
self.stream.flush()
tests.MESSAGES["SKIPPED"].append(reason)
class BasicTestRunner(unittest.TextTestRunner):
"""Basic test runner"""
resultclass = BasicTestResult
def __init__(
self,
stream=sys.stderr,
descriptions=False,
verbosity=1,
failfast=False,
buffer=False,
warnings="ignore",
):
try:
super(BasicTestRunner, self).__init__(
stream=stream,
descriptions=descriptions,
verbosity=verbosity,
failfast=failfast,
buffer=buffer,
warnings=warnings,
)
except TypeError:
# Python v3.1
super(BasicTestRunner, self).__init__(
stream=stream, descriptions=descriptions, verbosity=verbosity
)
class Python26TestRunner(unittest.TextTestRunner):
"""Python v2.6/3.1 Test Runner backporting needed functionality"""
def __init__(
self,
stream=sys.stderr,
descriptions=False,
verbosity=1,
failfast=False,
buffer=False,
):
super(Python26TestRunner, self).__init__(
stream=stream, descriptions=descriptions, verbosity=verbosity
)
def _makeResult(self):
return BasicTestResult(self.stream, self.descriptions, self.verbosity)
def setup_stats_db(cnx):
"""Setup the database for storing statistics"""
cur = cnx.cursor()
supported_python = ("3.8", "3.9", "3.10", "3.11")
supported_mysql = ("5.7", "8.0", "8.1")
columns = []
for pyver in supported_python:
for myver in supported_mysql:
columns.append(
" py{python}my{mysql} DECIMAL(8,4) DEFAULT -1".format(
python=pyver.replace(".", ""), mysql=myver.replace(".", "")
)
)
create_table = (
"CREATE TABLE {table} ( "
" test_case VARCHAR(100) NOT NULL,"
" {pymycols}, "
" PRIMARY KEY (test_case)"
") ENGINE=InnoDB"
).format(table=get_stats_tablename(), pymycols=", ".join(columns))
try:
cur.execute(create_table)
except mysql.connector.ProgrammingError as err:
if err.errno != 1050:
raise
LOGGER.info(
"Using exists table '{0}' for saving statistics".format(
get_stats_tablename()
)
)
else:
LOGGER.info(
"Created table '{0}' for saving statistics".format(get_stats_tablename())
)
cur.close()
def init_mysql_server(port, options):
"""Initialize a MySQL Server"""
name = "server{0}".format(len(tests.MYSQL_SERVERS) + 1)
extra_args = [
{
"version": (5, 7, 17),
"options": {
"mysqlx_bind_address": "mysqlx_bind_address={0}".format(
"::" if tests.IPV6_AVAILABLE else "0.0.0.0"
)
},
}
]
if options.secure_file_priv is not None:
extra_args += [
{
"version": (5, 5, 53),
"options": {
"secure_file_priv": "secure_file_priv = %s"
% options.secure_file_priv
},
}
]
else:
extra_args += [{"version": (5, 5, 53), "options": {"secure_file_priv": ""}}]
try:
mysql_server = mysqld.MySQLServer(
basedir=options.mysql_basedir,
topdir=os.path.join(options.mysql_topdir, "cpy_" + name),
cnf=MY_CNF,
bind_address=options.bind_address,
port=port,
mysqlx_port=options.mysqlx_port,
unix_socket_folder=options.unix_socket_folder,
ssl_folder=os.path.abspath(tests.SSL_DIR),
ssl_ca="tests_CA_cert.pem",
ssl_cert="tests_server_cert.pem",
ssl_key="tests_server_key.pem",
name=name,
extra_args=extra_args,
sharedir=options.mysql_sharedir,
)
except tests.mysqld.MySQLBootstrapError as err:
LOGGER.error(
"Failed initializing MySQL server "
"'{name}': {error}".format(name=name, error=str(err))
)
sys.exit(1)
if len(mysql_server.unix_socket) > 103:
LOGGER.error(
"Unix socket file is to long for mysqld (>103). "
"Consider using --unix-socket"
)
sys.exit(1)
mysql_server._debug = options.debug
have_to_bootstrap = True
if options.force:
# Force removal of previous test data
if mysql_server.check_running():
mysql_server.stop()
if not mysql_server.wait_down():
LOGGER.error(
"Failed shutting down the MySQL server '{name}'".format(name=name)
)
sys.exit(1)
mysql_server.remove()
else:
if mysql_server.check_running():
LOGGER.info(
"Reusing previously bootstrapped MySQL server '{name}'".format(
name=name
)
)
have_to_bootstrap = False
else:
LOGGER.warning(
"Can not connect to previously bootstrapped "
"MySQL Server '{name}'; forcing bootstrapping".format(name=name)
)
mysql_server.remove()
tests.MYSQL_VERSION = mysql_server.version
tests.MYSQL_LICENSE = mysql_server.license
tests.MYSQL_VERSION_TXT = ".".join([str(i) for i in mysql_server.version])
tests.MYSQL_SERVERS.append(mysql_server)
mysql_server.client_config = {
"host": options.host,
"port": port,
"unix_socket": mysql_server.unix_socket,
"user": "root",
"password": "",
"database": "myconnpy",
"connection_timeout": 60,
}
mysql_server.xplugin_config = {
"host": options.host,
"port": options.mysqlx_port,
"user": "root",
"password": "",
"schema": "myconnpy",
}
if mysql_server.version >= (5, 7, 15):
mysql_server.xplugin_config["socket"] = mysql_server.mysqlx_unix_socket
os.environ["MYSQLX_UNIX_PORT"] = mysql_server.mysqlx_unix_socket
# Bootstrap and start a MySQL server
if have_to_bootstrap:
LOGGER.info("Bootstrapping MySQL server '{name}'".format(name=name))
try:
mysql_server.bootstrap()
except tests.mysqld.MySQLBootstrapError as exc:
LOGGER.error(
"Failed bootstrapping MySQL server '{name}': "
"{error}".format(name=name, error=str(exc))
)
sys.exit(1)
mysql_server.start()
if not mysql_server.wait_up():
LOGGER.error(
"Failed to start the MySQL server '{name}'. "
"Check error log.".format(name=name)
)
sys.exit(1)
def warnings_filter(record):
"""Filter out warnings."""
return record.levelno != logging.WARNING
def main():
parser = _get_arg_parser()
options = parser.parse_args()
tests.OPTIONS_INIT = True
if isinstance(options, tuple):
# Fallback to old optparse
options = options[0]
if options.show_tests:
sys.path.insert(0, os.path.join(os.getcwd(), "lib"))
for name, _, description in tests.get_test_modules():
print("{0:22s} {1}".format(name, description))
sys.exit()
# Setup tests logger
tests.setup_logger(LOGGER, debug=options.debug, logfile=options.logfile)
# Setup mysql.connector and mysqlx loggers, and filter out warnings
mysql_connector_logger = logging.getLogger("mysql.connector")
tests.setup_logger(
mysql_connector_logger,
debug=options.debug,
logfile=options.logfile,
filter=warnings_filter,
)
mysqlx_logger = logging.getLogger("mysqlx")
tests.setup_logger(
mysqlx_logger,
debug=options.debug,
logfile=options.logfile,
filter=warnings_filter,
)
LOGGER.info(
"MySQL Connector/Python unittest using Python v{0}".format(
".".join([str(v) for v in sys.version_info[0:3]])
)
)
# Check if we can test IPv6
if options.ipv6:
if not tests.IPV6_AVAILABLE:
LOGGER.error("Can not test IPv6: not available on your system")
sys.exit(1)
options.bind_address = "::"
options.host = "::1"
LOGGER.info("Testing using IPv6. Binding to :: and using host ::1")
else:
tests.IPV6_AVAILABLE = False
if not options.mysql_sharedir:
options.mysql_sharedir = os.path.join(options.mysql_basedir, "share")
LOGGER.debug("Setting default sharedir: %s", options.mysql_sharedir)
if options.mysql_topdir != MYSQL_DEFAULT_TOPDIR:
# Make sure the topdir is absolute
if not os.path.isabs(options.mysql_topdir):
options.mysql_topdir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
options.mysql_topdir,
)
# If Django was supplied, add Django to PYTHONPATH
if options.django_path:
sys.path.insert(0, options.django_path)
try:
import django
tests.DJANGO_VERSION = django.VERSION[0:3]
except ImportError:
msg = "Could not find django package at {0}".format(options.django_path)
LOGGER.error(msg)
sys.exit(1)
if sys.version_info[0] == 3 and tests.DJANGO_VERSION < (1, 5):
LOGGER.error("Django older than v1.5 will not work with Python 3")
sys.exit(1)
# We have to at least run 1 MySQL server
if options.use_external_server:
name = "server{}".format(len(tests.MYSQL_SERVERS) + 1)
mysql_server = mysqld.MySQLExternalServer(MY_CNF, name)
mysql_server.client_config = {
"host": options.host,
"port": options.port,
"user": options.user,
"password": options.password,
"database": "myconnpy",
"connection_timeout": 60,
"unix_socket": options.unix_socket_folder,
}
mysql_server.xplugin_config = {
"host": options.host,
"port": options.mysqlx_port,
"user": options.user,
"password": options.password,
"schema": "myconnpy",
"socket": options.unix_socket_folder,
}
tests.MYSQL_SERVERS.append(mysql_server)
tests.MYSQL_EXTERNAL_SERVER = True
version_re = re.compile(r"^(\d+)\.(\d+)\.(\d+)+", re.ASCII)
try:
import mysql.connector
with mysql.connector.connect(
host=options.host,
port=options.port,
user=options.user,
password=options.password,
) as cnx:
with cnx.cursor() as cur:
cur = cnx.cursor()
# Create database for testing
LOGGER.info("Creating 'myconnpy' database")
cur.execute("DROP DATABASE IF EXISTS myconnpy")
cur.execute("CREATE DATABASE myconnpy CHARACTER SET utf8mb4")
# Version
cur.execute("SELECT VERSION()")
res = cur.fetchone()
match = version_re.match(res[0])
if not match:
raise ValueError("Invalid version number '{}'".format(res[0]))