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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
|
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2013, 2014, 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, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Unittests for mysql.connector.fabric
"""
from decimal import Decimal
import sys
import uuid
try:
from xmlrpclib import Fault, ServerProxy
except ImportError:
# Python v3
from xmlrpc.client import Fault, ServerProxy # pylint: disable=F0401
import tests
import mysql.connector
from mysql.connector import fabric, errorcode, errors
from mysql.connector.fabric import connection, caching, balancing
_HOST = 'tests.example.com'
_PORT = 1234
class _MockupXMLProxy(object):
"""Mock-up of XMLProxy simulating Fabric XMLRPC
This class can be used as a mockup for xmlrpclib.ServerProxy
"""
fabric_servers = ['tests.example.com:1234']
fabric_uuid = 'c4563310-f742-4d24-87ec-930088d892ff'
version_token = 1
ttl = 1 * 60
groups = {
'testgroup1': [
['a6ac2895-574f-11e3-bc32-bcaec56cc4a7', 'testgroup1',
_HOST, '3372', 1, 2, 1.0],
['af1cb1e4-574f-11e3-bc33-bcaec56cc4a7', 'testgroup1',
_HOST, '3373', 3, 3, 1.0],
],
'testgroup2': [
['b99bf2f3-574f-11e3-bc33-bcaec56cc4a7', 'testgroup2',
_HOST, '3374', 3, 3, 1.0],
['c3afdef6-574f-11e3-bc33-bcaec56cc4a7', 'testgroup2',
_HOST, '3375', 1, 2, 1.0],
],
'testglobalgroup': [
['91f7090e-574f-11e3-bc32-bcaec56cc4a7', 'testglobalgroup',
_HOST, '3370', 3, 3, 1.0],
['9c09932d-574f-11e3-bc32-bcaec56cc4a7', 'testglobalgroup',
_HOST, '3371', 1, 2, 1.0],
],
'onlysecondary': [
['b99bf2f3-574f-11e3-bc33-bcaec56cc4a7', 'onlysecondary',
_HOST, '3374', 1, 2, 1.0],
['c3afdef6-574f-11e3-bc33-bcaec56cc4a7', 'onlysecondary',
_HOST, '3375', 1, 2, 1.0],
],
'onlyprimary': [
['af1cb1e4-574f-11e3-bc33-bcaec56cc4a7', 'onlyprimary',
_HOST, '3373', 3, 3, 1.0],
],
'onlyspare': [
['b99bf2f3-574f-11e3-bc33-bcaec56cc4a7', 'onlyspare',
_HOST, '3374', 1, 1, 1.0],
['c3afdef6-574f-11e3-bc33-bcaec56cc4a7', 'onlyspare',
_HOST, '3375', 1, 1, 1.0],
],
'emptygroup': [],
}
sharding_information = {
'shardtype.range': [
['shardtype', 'range', 'id', '1', '1',
'RANGE', 'testgroup1', 'testglobalgroup'],
['shardtype', 'range', 'id', '21', '2',
'RANGE', 'testgroup2', 'testglobalgroup'],
],
'shardtype.hash': [
['shardtype', 'hash', 'name',
'513772EE53011AD9F4DC374B2D34D0E9', '1',
'HASH', 'testgroup1', 'testglobalgroup'],
['shardtype', 'hash', 'name',
'F617868BD8C41043DC4BEBC7952C7024', '2',
'HASH', 'testgroup2', 'testglobalgroup'],
],
'shardtype.spam': [
['shardtype', 'spam', 'emp_no', '1', '1',
'SPAM', 'testgroup1', 'testglobalgroup'],
['shardtype', 'spam', 'emp_no', '21', '2',
'SPAM', 'testgroup2', 'testglobalgroup'],
],
}
@staticmethod
def wrap_response(data):
return (
_MockupXMLProxy.fabric_uuid,
_MockupXMLProxy.version_token, # version
_MockupXMLProxy.ttl, # ttl
data,
)
@property
def server(self):
class Server(object):
@staticmethod
def set_status(server_uuid, status):
return server_uuid, status
return Server()
@property
def threat(self):
class Threat(object):
@staticmethod
def report_failure(server_uuid, reporter, status):
return server_uuid, status
@staticmethod
def report_error(server_uuid, reporter, status):
return server_uuid, status
return Threat()
@property
def dump(self):
class Dump(object):
"""Mocking Fabric dump commands"""
@staticmethod
def fabric_nodes():
return _MockupXMLProxy.wrap_response(
_MockupXMLProxy.fabric_servers)
@staticmethod
def servers(version, patterns):
groups = patterns.split(',')
data = []
for group in groups:
for server in _MockupXMLProxy.groups[group]:
data.append(server)
return _MockupXMLProxy.wrap_response(data)
@staticmethod
def sharding_information(version, patterns):
tables = patterns.split(',')
shards = _MockupXMLProxy.sharding_information
data = []
for table in tables:
try:
data.extend(shards[table])
except KeyError:
pass
return _MockupXMLProxy.wrap_response(data)
return Dump()
def __init__(self, *args, **kwargs):
"""Initializing"""
self._uri = kwargs.get('uri', None)
self._allow_none = kwargs.get('allow_none', None)
@staticmethod
def _some_nonexisting_method():
"""A non-existing method raising Fault"""
raise Fault(0, 'Testing')
class _MockupFabric(fabric.Fabric):
"""Mock-up of fabric.Fabric
This class is similar to fabric.Fabric except that it does not
create a connection with MySQL Fabric. It is used to be able to
unit tests without the need of having to run a complete Fabric
setup.
"""
_cnx_class = None
def seed(self, host=None, port=None):
if _HOST in (host, self._init_host):
self._cnx_class = _MockupFabricConnection
super(_MockupFabric, self).seed(host, port)
class _MockupFabricConnection(fabric.FabricConnection):
"""Mock-up of fabric.FabricConnection"""
def _xmlrpc_get_proxy(self):
return _MockupXMLProxy()
class FabricModuleTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.fabric module"""
def test___all___(self):
attrs = [
'MODE_READWRITE',
'MODE_READONLY',
'STATUS_PRIMARY',
'STATUS_SECONDARY',
'SCOPE_GLOBAL',
'SCOPE_LOCAL',
'FabricMySQLServer',
'FabricShard',
'connect',
'Fabric',
'FabricConnection',
'MySQLFabricConnection',
]
for attr in attrs:
try:
getattr(fabric, attr)
except AttributeError:
self.fail("Attribute '{0}' not in fabric.__all__".format(attr))
def test_fabricmyqlserver(self):
attrs = ['uuid', 'group', 'host', 'port', 'mode', 'status', 'weight']
try:
nmdtpl = fabric.FabricMySQLServer(*([''] * len(attrs)))
except TypeError:
self.fail("Fail creating namedtuple FabricMySQLServer")
self.check_namedtuple(nmdtpl, attrs)
def test_fabricshard(self):
attrs = [
'database', 'table', 'column', 'key', 'shard', 'shard_type',
'group', 'global_group'
]
try:
nmdtpl = fabric.FabricShard(*([''] * len(attrs)))
except TypeError:
self.fail("Fail creating namedtuple FabricShard")
self.check_namedtuple(nmdtpl, attrs)
def test_connect(self):
class FakeConnection(object):
def __init__(self, *args, **kwargs):
pass
orig = fabric.MySQLFabricConnection
fabric.MySQLFabricConnection = FakeConnection
self.assertTrue(isinstance(fabric.connect(), FakeConnection))
fabric.MySQLFabricConnection = orig
class ConnectionModuleTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.fabric.connection module"""
def test_module_variables(self):
error_codes = (
errorcode.CR_SERVER_LOST,
errorcode.ER_OPTION_PREVENTS_STATEMENT,
)
self.assertEqual(error_codes, connection.RESET_CACHE_ON_ERROR)
modvars = {
'MYSQL_FABRIC_PORT': 32274,
'FABRICS': {},
'_CNX_ATTEMPT_DELAY': 1,
'_CNX_ATTEMPT_MAX': 3,
'_GETCNX_ATTEMPT_DELAY': 1,
'_GETCNX_ATTEMPT_MAX': 3,
'MODE_READONLY': 1,
'MODE_WRITEONLY': 2,
'MODE_READWRITE': 3,
'STATUS_FAULTY': 0,
'STATUS_SPARE': 1,
'STATUS_SECONDARY': 2,
'STATUS_PRIMARY': 3,
'SCOPE_GLOBAL': 'GLOBAL',
'SCOPE_LOCAL': 'LOCAL',
'_SERVER_STATUS_FAULTY': 'FAULTY',
}
for modvar, value in modvars.items():
try:
self.assertEqual(value, getattr(connection, modvar))
except AttributeError:
self.fail("Module variable connection.{0} not found".format(
modvar))
def test_cnx_properties(self):
cnxprops = {
# name: (valid_types, description, default)
'group': ((str,), "Name of group of servers", None),
'key': ((int, str), "Sharding key", None),
'tables': ((tuple, list), "List of tables in query", None),
'mode': ((int,), "Read-Only, Write-Only or Read-Write",
connection.MODE_READWRITE),
'shard': ((str,), "Identity of the shard for direct connection",
None),
'mapping': ((str,), "", None),
'scope': ((str,), "GLOBAL for accessing Global Group, or LOCAL",
connection.SCOPE_LOCAL),
'attempts': ((int,), "Attempts for getting connection",
connection._CNX_ATTEMPT_MAX),
'attempt_delay': ((int,), "Seconds to wait between each attempt",
connection._CNX_ATTEMPT_DELAY),
}
for prop, desc in cnxprops.items():
try:
self.assertEqual(desc, connection._CNX_PROPERTIES[prop])
except KeyError:
self.fail("Connection property '{0}'' not available".format(
prop))
self.assertEqual(len(cnxprops), len(connection._CNX_PROPERTIES))
def test__fabric_xmlrpc_uri(self):
data = ('example.com', _PORT)
exp = 'http://{host}:{port}'.format(host=data[0], port=data[1])
self.assertEqual(exp, connection._fabric_xmlrpc_uri(*data))
def test__fabric_server_uuid(self):
data = ('example.com', _PORT)
url = 'http://{host}:{port}'.format(host=data[0], port=data[1])
exp = uuid.uuid3(uuid.NAMESPACE_URL, url)
self.assertEqual(exp, connection._fabric_server_uuid(*data))
def test__validate_ssl_args(self):
func = connection._validate_ssl_args
kwargs = dict(ssl_ca=None, ssl_key=None, ssl_cert=None)
self.assertEqual(None, func(**kwargs))
kwargs = dict(ssl_ca=None, ssl_key='/path/to/key',
ssl_cert=None)
self.assertRaises(AttributeError, func, **kwargs)
kwargs = dict(ssl_ca='/path/to/ca', ssl_key='/path/to/key',
ssl_cert=None)
self.assertRaises(AttributeError, func, **kwargs)
exp = {
'ca': '/path/to/ca',
'key': None,
'cert': None,
}
kwargs = dict(ssl_ca='/path/to/ca', ssl_key=None, ssl_cert=None)
self.assertEqual(exp, func(**kwargs))
exp = {
'ca': '/path/to/ca',
'key': '/path/to/key',
'cert': '/path/to/cert',
}
res = func(ssl_ca=exp['ca'], ssl_cert=exp['cert'], ssl_key=exp['key'])
self.assertEqual(exp, res)
def test_extra_failure_report(self):
func = connection.extra_failure_report
func([])
self.assertEqual([], connection.REPORT_ERRORS_EXTRA)
self.assertRaises(AttributeError, func, 1)
self.assertRaises(AttributeError, func, [1])
exp = [2222]
func(exp)
self.assertEqual(exp, connection.REPORT_ERRORS_EXTRA)
class FabricTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.fabric.Fabric class"""
def setUp(self):
self._orig_fabric_connection_class = connection.FabricConnection
self._orig_fabric_servers = _MockupXMLProxy.fabric_servers
connection.FabricConnection = _MockupFabricConnection
def tearDown(self):
connection.FabricConnection = self._orig_fabric_connection_class
_MockupXMLProxy.fabric_servers = self._orig_fabric_servers
def test___init__(self):
fab = fabric.Fabric(_HOST, port=_PORT)
attrs = {
'_fabric_instances': {},
'_fabric_uuid': None,
'_ttl': 1 * 60,
'_version_token': None,
'_connect_attempts': connection._CNX_ATTEMPT_MAX,
'_connect_delay': connection._CNX_ATTEMPT_DELAY,
'_cache': None,
'_group_balancers': {},
'_init_host': _HOST,
'_init_port': _PORT,
'_ssl': None,
'_username': None,
'_password': None,
'_report_errors': False,
}
for attr, default in attrs.items():
if attr in ('_cache', '_fabric_instances'):
# Tested later
continue
try:
self.assertEqual(default, getattr(fab, attr))
except AttributeError:
self.fail("Fabric instance has no attribute '{0}'".format(
attr))
self.assertTrue(isinstance(fab._cache, caching.FabricCache))
self.assertEqual(fab._fabric_instances, {})
# SSL
exp = {
'ca': '/path/to/ca',
'key': '/path/to/key',
'cert': '/path/to/cert',
}
fab = fabric.Fabric(_HOST, port=_PORT,
ssl_ca=exp['ca'], ssl_cert=exp['cert'],
ssl_key=exp['key'])
self.assertEqual(exp, fab._ssl)
# Check user/username
self.assertRaises(ValueError, fabric.Fabric, _HOST, username='ham',
user='spam')
fab = fabric.Fabric(_HOST, username='spam')
self.assertEqual('spam', fab._username)
fab = fabric.Fabric(_HOST, user='ham')
self.assertEqual('ham', fab._username)
def test_seed(self):
fab = _MockupFabric(_HOST, _PORT)
# Empty server list results in InterfaceError
_MockupXMLProxy.fabric_servers = None
self.assertRaises(errors.InterfaceError, fab.seed)
_MockupXMLProxy.fabric_servers = self._orig_fabric_servers
exp_server_uuid = uuid.UUID(_MockupXMLProxy.fabric_uuid)
exp_version = _MockupXMLProxy.version_token
exp_ttl = _MockupXMLProxy.ttl
fabrics = [
{'host': _HOST, 'port': _PORT}
]
# Normal operations
fab.seed()
self.assertEqual(exp_server_uuid, fab._fabric_uuid)
self.assertEqual(exp_version, fab._version_token)
self.assertEqual(exp_ttl, fab._ttl)
exp_fabinst_uuid = connection._fabric_server_uuid(
fabrics[0]['host'], fabrics[0]['port'])
self.assertTrue(exp_fabinst_uuid in fab._fabric_instances)
fabinst = fab._fabric_instances[exp_fabinst_uuid]
self.assertEqual(fabrics[0]['host'], fabinst.host)
self.assertEqual(fabrics[0]['port'], fabinst.port)
# Don't change anything when version did not change
exp_ttl = 10
fab.seed()
self.assertNotEqual(exp_ttl, fab._ttl)
def test_reset_cache(self):
class FabricNoServersLookup(_MockupFabric):
def get_group_servers(self, group, use_cache=True):
self.test_group = group
fab = FabricNoServersLookup(_HOST)
first_cache = fab._cache
fab.reset_cache()
self.assertNotEqual(first_cache, fab._cache)
exp = 'testgroup'
fab.reset_cache(exp)
self.assertEqual(exp, fab.test_group)
def test_get_instance(self):
fab = _MockupFabric(_HOST, _PORT)
self.assertRaises(errors.InterfaceError, fab.get_instance)
fab.seed()
if sys.version_info[0] == 2:
instance_list = fab._fabric_instances.keys()
exp = fab._fabric_instances[instance_list[0]]
else:
exp = fab._fabric_instances[list(fab._fabric_instances)[0]]
self.assertEqual(exp, fab.get_instance())
def test_report_failure(self):
fab = _MockupFabric(_HOST, _PORT)
fabinst = connection.FabricConnection(fab, _HOST, _PORT)
fabinst._proxy = _MockupXMLProxy()
fab._fabric_instances[fabinst.uuid] = fabinst
fab.report_failure(uuid.uuid4(), connection.REPORT_ERRORS[0])
def test_get_fabric_servers(self):
fab = _MockupFabric(_HOST, _PORT)
fab.seed()
exp = (
uuid.UUID('{' + _MockupXMLProxy.fabric_uuid + '}'),
_MockupXMLProxy.version_token,
_MockupXMLProxy.ttl,
[{'host': _HOST, 'port': _PORT}]
)
self.assertEqual(exp, fab.get_fabric_servers())
# No instances available
fabinst = _MockupFabricConnection(fab, _HOST, _PORT)
fab._fabric_instances = {}
self.assertRaises(errors.InterfaceError,
fab.get_fabric_servers)
fabinst.connect()
self.assertEqual(exp, fab.get_fabric_servers(fabinst))
fab.seed()
def test_get_group_servers(self):
fab = _MockupFabric(_HOST, _PORT)
fab.seed()
exp = [
# Secondary
fabric.FabricMySQLServer(
uuid='a6ac2895-574f-11e3-bc32-bcaec56cc4a7',
group='testgroup1',
host='tests.example.com', port=3372,
mode=1, status=2, weight=1.0),
# Primary
fabric.FabricMySQLServer(
uuid='af1cb1e4-574f-11e3-bc33-bcaec56cc4a7',
group='testgroup1',
host='tests.example.com', port=3373,
mode=3, status=3, weight=1.0),
]
self.assertEqual(exp, fab.get_group_servers('testgroup1'))
self.assertEqual(exp,
fab.get_group_servers('testgroup1', use_cache=False))
exp_balancers = {
'testgroup1': balancing.WeightedRoundRobin(
(exp[0].uuid, exp[0].weight))
}
self.assertEqual(exp_balancers, fab._group_balancers)
# No instances available, checking cache
fab._fabric_instances = {}
fab.get_group_servers('testgroup1')
self.assertEqual(exp, fab.get_group_servers('testgroup1'))
# Force lookup
self.assertRaises(errors.InterfaceError,
fab.get_group_servers, 'testgroup1', use_cache=False)
def test_get_group_server(self):
fab = _MockupFabric(_HOST, _PORT)
fab.seed()
self.assertRaises(ValueError, fab.get_group_server,
'testgroup1', mode=1, status=1)
self.assertRaises(errors.InterfaceError, fab.get_group_server,
'emptygroup')
# Request PRIMARY (master)
exp = fab.get_group_servers('testgroup1')[1]
self.assertEqual(
exp,
fab.get_group_server('testgroup1', status=fabric.STATUS_PRIMARY)
)
self.assertEqual(
exp,
fab.get_group_server('testgroup1', mode=fabric.MODE_READWRITE)
)
# Request PRIMARY, but non available
self.assertRaises(errors.InterfaceError,
fab.get_group_server,
'onlysecondary', status=fabric.STATUS_PRIMARY)
self.assertRaises(errors.InterfaceError,
fab.get_group_server,
'onlysecondary', mode=fabric.MODE_READWRITE)
# Request SECONDARY, but non available, returns primary
exp = fab.get_group_servers('onlyprimary')[0]
self.assertEqual(
exp,
fab.get_group_server('onlyprimary', mode=fabric.MODE_READONLY)
)
# Request SECONDARY
exp = fab.get_group_servers('testgroup1')[0]
self.assertEqual(
exp,
fab.get_group_server('testgroup1', status=fabric.STATUS_SECONDARY)
)
self.assertEqual(
exp,
fab.get_group_server('testgroup1', mode=fabric.MODE_READONLY)
)
# No Primary or Secondary
self.assertRaises(errors.InterfaceError,
fab.get_group_server, 'onlyspare',
status=fabric.STATUS_SECONDARY)
def test_get_sharding_information(self):
fab = _MockupFabric(_HOST, _PORT)
fab.seed()
self.assertRaises(ValueError, fab.get_sharding_information,
'notlist')
table = ('range', 'shardtype') # table name, database name
exp = {
1: {'group': 'testgroup1'},
21: {'group': 'testgroup2'}
}
fab.get_sharding_information([table])
entry = fab._cache.sharding_search(table[1], table[0])
self.assertEqual(exp, entry.partitioning)
fab.get_sharding_information([table[0]], 'shardtype')
entry = fab._cache.sharding_search(table[1], table[0])
self.assertEqual(exp, entry.partitioning)
def test_get_shard_server(self):
fab = _MockupFabric(_HOST, _PORT)
fab.seed()
self.assertRaises(ValueError, fab.get_shard_server, 'notlist', 1)
self.assertRaises(ValueError, fab.get_shard_server, ['not_list'], 1)
exp_local = [
# Secondary
fabric.FabricMySQLServer(
uuid='a6ac2895-574f-11e3-bc32-bcaec56cc4a7',
group='testgroup1',
host='tests.example.com', port=3372,
mode=1, status=2, weight=1.0),
# Primary
fabric.FabricMySQLServer(
uuid='af1cb1e4-574f-11e3-bc33-bcaec56cc4a7',
group='testgroup1',
host='tests.example.com', port=3373,
mode=3, status=3, weight=1.0),
]
exp_global = [
fabric.FabricMySQLServer(
uuid='91f7090e-574f-11e3-bc32-bcaec56cc4a7',
group='testglobalgroup',
host='tests.example.com', port=3370,
mode=3, status=3, weight=1.0),
fabric.FabricMySQLServer(
uuid='9c09932d-574f-11e3-bc32-bcaec56cc4a7',
group='testglobalgroup',
host='tests.example.com', port=3371,
mode=1, status=2, weight=1.0),
]
# scope=SCOPE_LOCAL, mode=None
self.assertEqual(
exp_local[0],
fab.get_shard_server(['shardtype.range'], 1)
)
# scope=SCOPE_GLOBAL, read-only and read-write
self.assertEqual(
exp_global[0],
fab.get_shard_server(['shardtype.range'], 1,
scope=fabric.SCOPE_GLOBAL,
mode=fabric.MODE_READWRITE)
)
self.assertEqual(
exp_global[1],
fab.get_shard_server(['shardtype.range'], 1,
scope=fabric.SCOPE_GLOBAL,
mode=fabric.MODE_READONLY)
)
self.assertRaises(errors.InterfaceError,
fab.get_shard_server, ['shardtype.spam'], 1)
self.assertRaises(errors.DatabaseError,
fab.get_shard_server, ['shartype.unknowntable'], 1)
class FabricConnectionTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.fabric.FabricConnection class"""
def setUp(self):
self.fab = connection.Fabric(_HOST, port=_PORT)
self.fabcnx = connection.FabricConnection(self.fab, _HOST, port=_PORT)
def tearDown(self):
connection.ServerProxy = ServerProxy
def test___init___(self):
self.assertRaises(ValueError,
connection.FabricConnection, None, _HOST, port=_PORT)
attrs = {
'_fabric': self.fab,
'_host': _HOST,
'_port': _PORT,
'_proxy': None,
'_connect_attempts': connection._CNX_ATTEMPT_MAX,
'_connect_delay': connection._CNX_ATTEMPT_DELAY,
}
for attr, default in attrs.items():
try:
self.assertEqual(default, getattr(self.fabcnx, attr))
except AttributeError:
self.fail("FabricConnection instance has no "
"attribute '{0}'".format(attr))
def test_host(self):
self.assertEqual(_HOST, self.fabcnx.host)
def test_port(self):
fabcnx = connection.FabricConnection(self.fab, _HOST, port=_PORT)
self.assertEqual(_PORT, self.fabcnx.port)
def test_uri(self):
self.assertEqual(connection._fabric_xmlrpc_uri(_HOST, _PORT),
self.fabcnx.uri)
def test_proxy(self):
# We did not yet connect
self.assertEqual(None, self.fabcnx.proxy)
def test__xmlrpc_get_proxy(self):
# Try connection, which fails
self.fabcnx._connect_attempts = 1 # Make it fail quicker
self.assertRaises(errors.InterfaceError,
self.fabcnx._xmlrpc_get_proxy)
# Using mock-up
connection.ServerProxy = _MockupXMLProxy
self.assertTrue(isinstance(self.fabcnx._xmlrpc_get_proxy(),
_MockupXMLProxy))
def test_connect(self):
# Try connection, which fails
self.fabcnx._connect_attempts = 1 # Make it fail quicker
self.assertRaises(errors.InterfaceError, self.fabcnx.connect)
# Using mock-up
connection.ServerProxy = _MockupXMLProxy
self.fabcnx.connect()
self.assertTrue(isinstance(self.fabcnx.proxy, _MockupXMLProxy))
def test_is_connected(self):
self.assertFalse(self.fabcnx.is_connected)
self.fabcnx._proxy = 'spam'
self.assertFalse(self.fabcnx.is_connected)
# Using mock-up
connection.ServerProxy = _MockupXMLProxy
self.fabcnx.connect()
self.assertTrue(self.fabcnx.is_connected)
class MySQLFabricConnectionTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.fabric.FabricConnection class"""
def setUp(self):
# Mock-up: we don't actually connect to Fabric
connection.ServerProxy = _MockupXMLProxy
self.fabric_config = {
'host': _HOST,
'port': _PORT,
}
config = {'fabric': self.fabric_config}
self.cnx = connection.MySQLFabricConnection(**config)
def tearDown(self):
connection.ServerProxy = ServerProxy
def _get_default_properties(self):
result = {}
for key, attr in connection._CNX_PROPERTIES.items():
result[key] = attr[2]
return result
def test___init__(self):
# Missing 'fabric' argument
self.assertRaises(ValueError,
connection.MySQLFabricConnection)
attrs = {
'_mysql_cnx': None,
'_fabric': None,
'_fabric_mysql_server': None,
'_mysql_config': {},
'_cnx_properties': {},
}
for attr, default in attrs.items():
if attr in ('_cnx_properties', '_fabric'):
continue
try:
self.assertEqual(default, getattr(self.cnx, attr),
"Wrong init for {0}".format(attr))
except AttributeError:
self.fail("MySQLFabricConnection instance has no "
"attribute '{0}'".format(attr))
self.assertEqual(self._get_default_properties(),
self.cnx._cnx_properties)
def test___getattr__(self):
none_supported_attrs = [
'cmd_refresh',
'cmd_quit',
'cmd_shutdown',
'cmd_statistics',
'cmd_process_info',
'cmd_process_kill',
'cmd_debug',
'cmd_ping',
'cmd_change_user',
'cmd_stmt_prepare',
'cmd_stmt_execute',
'cmd_stmt_close',
'cmd_stmt_send_long_data',
'cmd_stmt_reset',
]
for attr in none_supported_attrs:
self.assertRaises(errors.NotSupportedError,
getattr, self.cnx, attr)
def test_fabric_uuid(self):
self.cnx._fabric_mysql_server = fabric.FabricMySQLServer(
uuid='af1cb1e4-574f-11e3-bc33-bcaec56cc4a7',
group='testgroup1',
host='tests.example.com', port=3373,
mode=3, status=3, weight=1.0
)
exp = 'af1cb1e4-574f-11e3-bc33-bcaec56cc4a7'
self.assertEqual(exp, self.cnx.fabric_uuid)
def test_properties(self):
self.assertEqual(self.cnx._cnx_properties, self.cnx.properties)
def test_reset_cache(self):
self.cnx._fabric._cache.cache_group('spam', None)
self.cnx.reset_cache()
self.assertEqual({}, self.cnx._fabric._cache._groups)
def test_is_connected(self):
self.assertFalse(self.cnx.is_connected())
self.cnx._mysql_cnx = 'spam'
self.assertTrue(self.cnx.is_connected())
def test_reset_properties(self):
exp = self.cnx._cnx_properties
self.cnx._cnx_properties = {'spam': 'ham'}
self.cnx.reset_properties()
self.assertEqual(exp, self.cnx._cnx_properties)
self.assertEqual(connection._GETCNX_ATTEMPT_DELAY,
self.cnx._cnx_properties['attempt_delay'])
self.assertEqual(connection._GETCNX_ATTEMPT_MAX,
self.cnx._cnx_properties['attempts'])
def test_set_property__errors(self):
self.assertRaises(ValueError, self.cnx.set_property, unknown='Spam')
# Can't use 'group' when 'key' was set
self.cnx._cnx_properties = {'key': 42}
self.assertRaises(ValueError, self.cnx.set_property, group='spam')
self.cnx.reset_properties()
# Can't use 'key' when 'group' was set
self.cnx._cnx_properties = {'group': 'ham'}
self.assertRaises(ValueError, self.cnx.set_property, key=42)
self.cnx.reset_properties()
# Invalid scope and mode
self.assertRaises(ValueError, self.cnx.set_property, scope='SPAM')
self.assertRaises(ValueError, self.cnx.set_property, mode=99999)
# Invalid types
self.assertRaises(TypeError, self.cnx.set_property, mode='SPAM')
self.assertRaises(TypeError, self.cnx.set_property, tables='SPAM')
self.assertRaises(TypeError, self.cnx.set_property, key=('1',))
def test_set_property(self):
self.cnx._cnx_properties = {'key': 42}
self.cnx.set_property(key=None)
self.assertEqual(None, self.cnx._cnx_properties['key'])
self.cnx.reset_properties()
exp = 'ham'
self.cnx.set_property(group='ham')
self.assertEqual(exp, self.cnx._cnx_properties['group'])
self.cnx.set_property(attempts=None)
self.assertEqual(connection._GETCNX_ATTEMPT_MAX,
self.cnx._cnx_properties['attempts'])
class FabricConnectorPythonTests(tests.MySQLConnectorTests):
"""Testing mysql.connector.connect()"""
def setUp(self):
# Mock-up: we don't actually connect to Fabric
connection.ServerProxy = _MockupXMLProxy
self.fabric_config = {
'host': _HOST,
'port': _PORT,
}
self.config = {'fabric': self.fabric_config}
def tearDown(self):
connection.ServerProxy = ServerProxy
def test_connect(self):
self.assertTrue(isinstance(
mysql.connector.connect(**self.config),
connection.MySQLFabricConnection
))
class FabricBalancingBaseScheduling(tests.MySQLConnectorTests):
"""Test fabric.balancing.BaseScheduling"""
def setUp(self):
self.obj = balancing.BaseScheduling()
def test___init__(self):
self.assertEqual([], self.obj._members)
self.assertEqual([], self.obj._ratios)
def test_set_members(self):
self.assertRaises(NotImplementedError, self.obj.set_members, 'spam')
def test_get_next(self):
self.assertRaises(NotImplementedError, self.obj.get_next)
class FabricBalancingWeightedRoundRobin(tests.MySQLConnectorTests):
"""Test fabric.balancing.WeightedRoundRobin"""
def test___init__(self):
balancer = balancing.WeightedRoundRobin()
self.assertEqual([], balancer._members)
self.assertEqual([], balancer._ratios)
self.assertEqual([], balancer._load)
# init with args
class FakeWRR(balancing.WeightedRoundRobin):
def set_members(self, *args):
self.set_members_called = True
balancer = FakeWRR('ham', 'spam')
self.assertTrue(balancer.set_members_called)
def test_members(self):
balancer = balancing.WeightedRoundRobin()
self.assertEqual([], balancer.members)
balancer._members = ['ham']
self.assertEqual(['ham'], balancer.members)
def test_ratios(self):
balancer = balancing.WeightedRoundRobin()
self.assertEqual([], balancer.ratios)
balancer._ratios = ['ham']
self.assertEqual(['ham'], balancer.ratios)
def test_load(self):
balancer = balancing.WeightedRoundRobin()
self.assertEqual([], balancer.load)
balancer._load = ['ham']
self.assertEqual(['ham'], balancer.load)
def test_set_members(self):
balancer = balancing.WeightedRoundRobin()
balancer._members = ['ham']
balancer.set_members()
self.assertEqual([], balancer.members)
servers = [('ham1', 0.2), ('ham2', 0.8)]
balancer.set_members(*servers)
exp = [('ham2', Decimal('0.8')), ('ham1', Decimal('0.2'))]
self.assertEqual(exp, balancer.members)
self.assertEqual([400, 100], balancer.ratios)
self.assertEqual([0, 0], balancer.load)
def test_reset_load(self):
balancer = balancing.WeightedRoundRobin(*[('ham1', 0.2), ('ham2', 0.8)])
balancer._load = [5, 6]
balancer.reset()
self.assertEqual([0, 0], balancer.load)
def test_get_next(self):
servers = [('ham1', 0.2), ('ham2', 0.8)]
balancer = balancing.WeightedRoundRobin(*servers)
self.assertEqual(('ham2', Decimal('0.8')), balancer.get_next())
self.assertEqual([1, 0], balancer.load)
balancer._load = [80, 0]
self.assertEqual(('ham1', Decimal('0.2')), balancer.get_next())
self.assertEqual([80, 1], balancer.load)
balancer._load = [80, 20]
self.assertEqual(('ham2', Decimal('0.8')), balancer.get_next())
self.assertEqual([81, 20], balancer.load)
servers = [('ham1', 0.1), ('ham2', 0.2), ('ham3', 0.7)]
balancer = balancing.WeightedRoundRobin(*servers)
exp_sum = count = 101
while count > 0:
count -= 1
_ = balancer.get_next()
self.assertEqual(exp_sum, sum(balancer.load))
self.assertEqual([34, 34, 33], balancer.load)
servers = [('ham1', 0.2), ('ham2', 0.2), ('ham3', 0.7)]
balancer = balancing.WeightedRoundRobin(*servers)
exp_sum = count = 101
while count > 0:
count -= 1
_ = balancer.get_next()
self.assertEqual(exp_sum, sum(balancer.load))
self.assertEqual([34, 34, 33], balancer.load)
servers = [('ham1', 0.25), ('ham2', 0.25),
('ham3', 0.25), ('ham4', 0.25)]
balancer = balancing.WeightedRoundRobin(*servers)
exp_sum = count = 101
while count > 0:
count -= 1
_ = balancer.get_next()
self.assertEqual(exp_sum, sum(balancer.load))
self.assertEqual([26, 25, 25, 25], balancer.load)
servers = [('ham1', 0.5), ('ham2', 0.5)]
balancer = balancing.WeightedRoundRobin(*servers)
count = 201
while count > 0:
count -= 1
_ = balancer.get_next()
self.assertEqual(1, sum(balancer.load))
self.assertEqual([1, 0], balancer.load)
def test___repr__(self):
balancer = balancing.WeightedRoundRobin(*[('ham1', 0.2), ('ham2', 0.8)])
exp = ("<class 'mysql.connector.fabric.balancing.WeightedRoundRobin'>"
"(load=[0, 0], ratios=[400, 100])")
self.assertEqual(exp, repr(balancer))
def test___eq__(self):
servers = [('ham1', 0.2), ('ham2', 0.8)]
balancer1 = balancing.WeightedRoundRobin(*servers)
balancer2 = balancing.WeightedRoundRobin(*servers)
self.assertTrue(balancer1 == balancer2)
servers = [('ham1', 0.2), ('ham2', 0.3), ('ham3', 0.5)]
balancer3 = balancing.WeightedRoundRobin(*servers)
self.assertFalse(balancer1 == balancer3)
|