Add commands for verification API

Change-Id: I6b7075220bce16af9e162f2e42feb10ffd073169
Implements: blueprint support-verify-the-checkpoint-api
This commit is contained in:
chenying 2017-10-19 19:55:18 +08:00
parent dd2e3ff3a3
commit f13c3faef4
4 changed files with 282 additions and 0 deletions

View File

@ -0,0 +1,80 @@
# 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
from karborclient.tests.unit import base
from karborclient.tests.unit.v1 import fakes
cs = fakes.FakeClient()
mock_request_return = ({}, {'verification': {}})
class VerificationsTest(base.TestCaseShell):
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_list_verifications_with_marker_limit(self, mock_request):
mock_request.return_value = mock_request_return
cs.verifications.list(marker=1234, limit=2)
mock_request.assert_called_with(
'GET',
'/verifications?limit=2&marker=1234', headers={})
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_list_verifications_with_sort_key_dir(self, mock_request):
mock_request.return_value = mock_request_return
cs.verifications.list(sort_key='id', sort_dir='asc')
mock_request.assert_called_with(
'GET',
'/verifications?'
'sort_dir=asc&sort_key=id', headers={})
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_list_verifications_with_invalid_sort_key(self, mock_request):
self.assertRaises(ValueError,
cs.verifications.list,
sort_key='invalid', sort_dir='asc')
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_create_verification(self, mock_request):
mock_request.return_value = mock_request_return
cs.verifications.create('586cc6ce-e286-40bd-b2b5-dd32694d9944',
'2220f8b1-975d-4621-a872-fa9afb43cb6c',
'{}')
mock_request.assert_called_with(
'POST',
'/verifications',
data={
'verification':
{
'checkpoint_id': '2220f8b1-975d-4621-a872-fa9afb43cb6c',
'parameters': '{}',
'provider_id': '586cc6ce-e286-40bd-b2b5-dd32694d9944'
}}, headers={})
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_show_verification(self, mock_request):
mock_request.return_value = mock_request_return
cs.verifications.get('1')
mock_request.assert_called_with(
'GET',
'/verifications/1',
headers={})
@mock.patch('karborclient.common.http.HTTPClient.json_request')
def test_show_verification_with_headers(self, mock_request):
mock_request.return_value = mock_request_return
cs.verifications.get('1', session_id='fake_session_id')
mock_request.assert_called_with(
'GET',
'/verifications/1',
headers={'X-Configuration-Session': 'fake_session_id'})

View File

@ -21,6 +21,7 @@ from karborclient.v1 import providers
from karborclient.v1 import restores
from karborclient.v1 import scheduled_operations
from karborclient.v1 import triggers
from karborclient.v1 import verifications
class Client(object):
@ -45,3 +46,5 @@ class Client(object):
scheduled_operations.ScheduledOperationManager(self.http_client)
self.operation_logs = \
operation_logs.OperationLogManager(self.http_client)
self.verifications = verifications.VerificationManager(
self.http_client)

View File

@ -365,6 +365,140 @@ def do_restore_show(cs, args):
utils.print_dict(restore.to_dict(), dict_format_list=dict_format_list)
@utils.arg('provider_id',
metavar='<provider_id>',
help='Provider id.')
@utils.arg('checkpoint_id',
metavar='<checkpoint_id>',
help='Checkpoint id.')
@utils.arg('--parameters-json',
type=str,
dest='parameters_json',
metavar='<parameters>',
default=None,
help='Verification parameters in json format.')
@utils.arg('--parameters',
action='append',
metavar='resource_type=<type>[,resource_id=<id>,key=val,...]',
default=[],
help='Verification parameters, may be specified multiple times. '
'resource_type: type of resource to apply parameters. '
'resource_id: limit the parameters to a specific resource. '
'Other keys and values: according to provider\'s schema.'
)
def do_verification_create(cs, args):
"""Creates a verification."""
if not uuidutils.is_uuid_like(args.provider_id):
raise exceptions.CommandError(
"Invalid provider id provided.")
if not uuidutils.is_uuid_like(args.checkpoint_id):
raise exceptions.CommandError(
"Invalid checkpoint id provided.")
verification_parameters = arg_utils.extract_parameters(args)
verification = cs.verifications.create(args.provider_id,
args.checkpoint_id,
verification_parameters)
dict_format_list = {"parameters"}
utils.print_dict(verification.to_dict(), dict_format_list=dict_format_list)
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning verifications that appear later in the'
'list than that represented by this verification id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of verifications to return. Default=None.')
@utils.arg('--sort_key',
metavar='<sort_key>',
default=None,
help=argparse.SUPPRESS)
@utils.arg('--sort_dir',
metavar='<sort_dir>',
default=None,
help=argparse.SUPPRESS)
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--tenant',
type=str,
dest='tenant',
nargs='?',
metavar='<tenant>',
help='Display information from single tenant (Admin only).')
def do_verification_list(cs, args):
"""Lists all verifications."""
all_tenants = 1 if args.tenant else \
int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'project_id': args.tenant,
'status': args.status,
}
if args.sort and (args.sort_key or args.sort_dir):
raise exceptions.CommandError(
'The --sort_key and --sort_dir arguments are '
'not supported with --sort.')
verifications = cs.verifications.list(search_opts=search_opts,
marker=args.marker,
limit=args.limit,
sort_key=args.sort_key,
sort_dir=args.sort_dir,
sort=args.sort)
key_list = ['Id', 'Project id', 'Provider id', 'Checkpoint id',
'Parameters', 'Status']
if args.sort_key or args.sort_dir or args.sort:
sortby_index = None
else:
sortby_index = 0
formatters = {"Parameters": lambda obj: json.dumps(
obj.parameters, indent=2, sort_keys=True)}
utils.print_list(verifications, key_list, exclude_unavailable=True,
sortby_index=sortby_index, formatters=formatters)
@utils.arg('verification',
metavar='<verification>',
help='ID of verification.')
def do_verification_show(cs, args):
"""Shows verification details."""
verification = cs.verifications.get(args.verification)
dict_format_list = {"parameters"}
utils.print_dict(verification.to_dict(),
dict_format_list=dict_format_list)
def do_protectable_list(cs, args):
"""Lists all protectable types."""

View File

@ -0,0 +1,65 @@
# 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.
from karborclient.common import base
class Verification(base.Resource):
def __repr__(self):
return "<Verification %s>" % self._info
class VerificationManager(base.ManagerWithFind):
resource_class = Verification
def create(self, provider_id, checkpoint_id, parameters):
body = {
'verification': {
'provider_id': provider_id,
'checkpoint_id': checkpoint_id,
'parameters': parameters,
}
}
url = "/verifications"
return self._create(url, body, 'verification')
def get(self, verification_id, session_id=None):
if session_id:
headers = {'X-Configuration-Session': session_id}
else:
headers = {}
url = "/verifications/{verification_id}".format(
verification_id=verification_id)
return self._get(url, response_key="verification", headers=headers)
def list(self, detailed=False, search_opts=None, marker=None, limit=None,
sort_key=None, sort_dir=None, sort=None):
"""Lists all verifications.
:param detailed: Whether to return detailed verification info.
:param search_opts: Search options to filter out verifications.
:param marker: Begin returning verifications that appear later in the
list than that represented by this verification id.
:param limit: Maximum number of verifications to return.
:param sort_key: Key to be sorted;
:param sort_dir: Sort direction, should be 'desc' or 'asc';
:param sort: Sort information
:rtype: list of :class:`Verification`
"""
resource_type = "verifications"
url = self._build_list_url(
resource_type, detailed=detailed,
search_opts=search_opts, marker=marker,
limit=limit, sort_key=sort_key,
sort_dir=sort_dir, sort=sort)
return self._list(url, 'verifications')