Fixed mysql reconnect on error

Change-Id: I4bb502b295ee9f5d748bb11eadeae7392235981c
This commit is contained in:
Joe Keen 2015-08-21 14:37:53 -06:00
parent a82a49a1e8
commit 82ae201cc4
3 changed files with 62 additions and 0 deletions

1
.gitignore vendored
View File

@ -10,3 +10,4 @@ ChangeLog
build
dist
monasca_notification.egg-info
.*.sw*

View File

@ -1,4 +1,5 @@
# Copyright 2015 FUJITSU LIMITED
# (C) Copyright 2015 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
@ -52,11 +53,13 @@ class MysqlRepo(BaseRepo):
try:
if self._mysql is None:
self._connect_to_mysql()
cur = self._mysql.cursor()
cur.execute(self._find_alarm_action_sql, (alarm['alarmDefinitionId'], alarm['newState']))
for row in cur:
yield (row[1].lower(), row[0], row[2])
except MySQLdb.Error as e:
self._mysql = None
log.exception("Couldn't fetch alarms actions %s", e)
raise exc.DatabaseException(e)

58
tests/test_mysql_repo.py Normal file
View File

@ -0,0 +1,58 @@
# (C) Copyright 2015 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import unittest
import MySQLdb
from monasca_notification.common.repositories import exceptions as exc
from monasca_notification.common.repositories.mysql import mysql_repo
class TestMySqlRepo(unittest.TestCase):
@mock.patch('monasca_notification.common.repositories.mysql.mysql_repo.MySQLdb')
def testReconnect(self, mock_mysql):
m = mock.MagicMock()
m.cursor.side_effect = MySQLdb.Error
mock_mysql.connect.return_value = m
mock_mysql.Error = MySQLdb.Error
config = {'mysql': {'host': 'foo',
'user': 'bar',
'passwd': '1',
'db': '2'}}
repo = mysql_repo.MysqlRepo(config)
alarm = {'alarmDefinitionId': 'foo',
'newState': 'bar'}
def get_notification(repo, alarm):
g = repo.fetch_notification(alarm)
for x in g:
pass
try:
get_notification(repo, alarm)
except exc.DatabaseException:
try:
get_notification(repo, alarm)
except Exception:
pass
self.assertEqual(mock_mysql.connect.call_count, 2)