Provide user friendly messages for db sync

Currently 'karbor-manage db sync' prints stacktrace if you
pass invalid value for 'version'.

This patch validates 'version' for its type and maximum
limit and displays a meaningful message to the user.

Handles DbMigrationError exception when database schema
file is not present in migration repository.

Closes-Bug: #1699893
Change-Id: I2ebc068dfee9fdba20183fb996f703bc44d7ca09
This commit is contained in:
yushangbin 2017-06-23 05:11:30 +08:00 committed by Jeremy Liu
parent 3d5b5ac1a7
commit 9299ff11c8
2 changed files with 38 additions and 2 deletions

View File

@ -22,6 +22,7 @@ import os
import sys
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import migration
from oslo_log import log as logging
@ -54,11 +55,19 @@ def args(*args, **kwargs):
class DbCommands(object):
"""Class for managing the database."""
@args('version', nargs='?', default=None,
@args('version', nargs='?', default=None, type=int,
help='Database version')
def sync(self, version=None):
"""Sync the database up to the most recent version."""
if version is not None and version > db.MAX_INT:
print(_('Version should be less than or equal to '
'%(max_version)d.') % {'max_version': db.MAX_INT})
sys.exit(1)
try:
return db_migration.db_sync(version)
except db_exc.DbMigrationError as ex:
print("Error during database migration: %s" % ex)
sys.exit(1)
def version(self):
"""Print the current database version."""

View File

@ -17,8 +17,10 @@ try:
except ImportError:
import mock
from oslo_config import cfg
from oslo_db import exception as db_exc
from karbor.cmd import api as karbor_api
from karbor.cmd import manage as karbor_manage
from karbor.tests import base
from karbor import version
@ -57,3 +59,28 @@ class TestKarborApiCmd(base.TestCase):
launcher.launch_service.assert_called_once_with(server,
workers=server.workers)
launcher.wait.assert_called_once_with()
class TestKarborManageCmd(base.TestCase):
"""Unit test cases for python modules under karbor/cmd/manage.py."""
def setUp(self):
super(TestKarborManageCmd, self).setUp()
sys.argv = ['karbor-manage']
CONF(sys.argv[1:], project='karbor', version=version.version_string())
def tearDown(self):
super(TestKarborManageCmd, self).tearDown()
def test_db_commands_upgrade_out_of_range(self):
version = 1111111111
db_cmds = karbor_manage.DbCommands()
exit = self.assertRaises(SystemExit, db_cmds.sync, version + 1)
self.assertEqual(1, exit.code)
@mock.patch("oslo_db.sqlalchemy.migration.db_sync")
def test_db_commands_script_not_present(self, db_sync):
db_sync.side_effect = db_exc.DbMigrationError
db_cmds = karbor_manage.DbCommands()
exit = self.assertRaises(SystemExit, db_cmds.sync, 101)
self.assertEqual(1, exit.code)