Browse Source

Add Horizon plugin for Blazar

This patch adds a Horizon plugin for Blazar. The following features are
currently supported:

* Show a list of leases
* Show details of a lease
* Update a lease
* Delete lease(s)

Change-Id: I24c14e697d4280fa29d84d11324fb881009f089b
Partially Implements: blueprint climate-dashboard
Co-Authored-By: Pablo Andres Fuente <pablo.a.fuente@intel.com>
changes/31/480331/22
Hiroaki Kobayashi 5 years ago committed by Pierre Riteau
parent
commit
c4afe8b438
  1. 59
      .eslintrc
  2. 22
      .gitignore
  3. 17
      CONTRIBUTING.rst
  4. 4
      HACKING.rst
  5. 176
      LICENSE
  6. 29
      README.rst
  7. 5
      babel-django.cfg
  8. 14
      babel-djangojs.cfg
  9. 0
      blazar_dashboard/__init__.py
  10. 0
      blazar_dashboard/api/__init__.py
  11. 84
      blazar_dashboard/api/client.py
  12. 0
      blazar_dashboard/content/__init__.py
  13. 0
      blazar_dashboard/content/leases/__init__.py
  14. 88
      blazar_dashboard/content/leases/forms.py
  15. 22
      blazar_dashboard/content/leases/panel.py
  16. 87
      blazar_dashboard/content/leases/tables.py
  17. 43
      blazar_dashboard/content/leases/tabs.py
  18. 64
      blazar_dashboard/content/leases/templates/leases/_detail_overview.html
  19. 24
      blazar_dashboard/content/leases/templates/leases/_update.html
  20. 15
      blazar_dashboard/content/leases/templates/leases/detail.html
  21. 11
      blazar_dashboard/content/leases/templates/leases/index.html
  22. 11
      blazar_dashboard/content/leases/templates/leases/update.html
  23. 169
      blazar_dashboard/content/leases/tests.py
  24. 27
      blazar_dashboard/content/leases/urls.py
  25. 79
      blazar_dashboard/content/leases/views.py
  26. 22
      blazar_dashboard/enabled/_90_project_reservations_panelgroup.py
  27. 21
      blazar_dashboard/enabled/_91_project_reservations_leases_panel.py
  28. 0
      blazar_dashboard/enabled/__init__.py
  29. 0
      blazar_dashboard/test/__init__.py
  30. 25
      blazar_dashboard/test/helpers.py
  31. 0
      blazar_dashboard/test/integration_tests/__init__.py
  32. 37
      blazar_dashboard/test/settings.py
  33. 0
      blazar_dashboard/test/test_data/__init__.py
  34. 141
      blazar_dashboard/test/test_data/blazar_data.py
  35. 56
      blazar_dashboard/test/test_data/exceptions.py
  36. 30
      blazar_dashboard/test/test_data/utils.py
  37. 14
      blazar_dashboard/version.py
  38. 152
      doc/Makefile
  39. 437
      doc/source/conf.py
  40. 37
      doc/source/index.rst
  41. 52
      doc/source/install.rst
  42. 23
      manage.py
  43. 0
      releasenotes/notes/.placeholder
  44. 7
      releasenotes/notes/dashboard-support-1b429d36f395d93a.yaml
  45. 279
      releasenotes/source/conf.py
  46. 8
      releasenotes/source/index.rst
  47. 5
      releasenotes/source/unreleased.rst
  48. 17
      requirements.txt
  49. 29
      setup.cfg
  50. 27
      setup.py
  51. 24
      test-requirements.txt
  52. 87
      tools/tox_install.sh
  53. 75
      tox.ini

59
.eslintrc

@ -0,0 +1,59 @@
# Set up globals
globals:
angular: false
extends: openstack
# Most environment options are not explicitly enabled or disabled, only
# included here for completeness' sake. They are commented out, because the
# global updates.py script would otherwise override them during a global
# requirements synchronization.
#
# Individual projects should choose which platforms they deploy to.
env:
# browser global variables.
browser: true
# Adds all of the Jasmine testing global variables for version 1.3 and 2.0.
jasmine: true
# Enable eslint-plugin-angular
plugins:
- angular
# Below we adjust rules specific to horizon's usage of openstack's linting
# rules, and its own plugin inclusions.
rules:
#############################################################################
# Disabled Rules from eslint-config-openstack
#############################################################################
valid-jsdoc: [1, {
requireParamDescription: false
}]
brace-style: 1
block-scoped-var: 1
callback-return: 1
consistent-return: 1
guard-for-in: 1
no-extra-parens: 1
no-new: 1
no-redeclare: 1
no-undefined: 1
no-unneeded-ternary: 1
no-use-before-define: 1
quote-props: 0
semi-spacing: 1
space-in-parens: 1
#############################################################################
# Angular Plugin Customization
#############################################################################
angular/controller-as-vm:
- 1
- "ctrl"
# Remove after migrating to angular 1.4 or later.
angular/no-cookiestore:
- 1

22
.gitignore vendored

@ -0,0 +1,22 @@
AUTHORS
ChangeLog
build
cover
doc/source/sourcecode
node_modules
npm-debug.log
releasenotes/build
blazar_dashboard/test/.secret_key_store
.coverage*
.jshintrc
.project
.pydevproject
.settings
.tox
.venv
*.egg*
*.lock
*.mo
*.py[cod]
*.swp
*nose_results.html

17
CONTRIBUTING.rst

@ -0,0 +1,17 @@
If you would like to contribute to the development of OpenStack, you must
follow the steps in this page:
http://docs.openstack.org/infra/manual/developers.html
If you already have a good understanding of how the system works and your
OpenStack accounts are set up, you can skip to the development workflow
section of this documentation to learn how changes to OpenStack should be
submitted for review via the Gerrit tool:
http://docs.openstack.org/infra/manual/developers.html#development-workflow
Pull requests submitted through GitHub will be ignored.
Bugs should be filed on Launchpad, not GitHub:
https://bugs.launchpad.net/blazar

4
HACKING.rst

@ -0,0 +1,4 @@
blazar-dashboard Style Commandments
===================================
Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/

176
LICENSE

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

29
README.rst

@ -0,0 +1,29 @@
================
Blazar dashboard
================
Horizon plugin for the Blazar Reservation Service for OpenStack
* Free software: Apache license
* Source: https://git.openstack.org/cgit/openstack/blazar-dashboard
* Bugs: https://bugs.launchpad.net/blazar
Features
--------
The following features are currently supported:
* Show a list of leases
* Show details of a lease
* Update a lease
* Delete lease(s)
Enabling in DevStack
--------------------
* Not yet supported
Manual Installation
-------------------
See doc/source/install.rst

5
babel-django.cfg

@ -0,0 +1,5 @@
[extractors]
django = django_babel.extract:extract_django
[python: **.py]
[django: templates/**.html]

14
babel-djangojs.cfg

@ -0,0 +1,14 @@
[extractors]
# We use a custom extractor to find translatable strings in AngularJS
# templates. The extractor is included in horizon.utils for now.
# See http://babel.pocoo.org/docs/messages/#referencing-extraction-methods for
# details on how this works.
angular = horizon.utils.babel_extract_angular:extract_angular
[javascript: **.js]
# We need to look into all static folders for HTML files.
# The **/static ensures that we also search within
# /openstack_dashboard/dashboards/XYZ/static which will ensure
# that plugins are also translated.
[angular: **/static/**.html]

0
blazar_dashboard/__init__.py

0
blazar_dashboard/api/__init__.py

84
blazar_dashboard/api/client.py

@ -0,0 +1,84 @@
# 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 __future__ import absolute_import
import logging
from horizon import exceptions
from horizon.utils.memoized import memoized
from openstack_dashboard.api import base
from blazarclient import client as blazar_client
LOG = logging.getLogger(__name__)
class Lease(base.APIDictWrapper):
"""Represents one Blazar lease."""
ACTIONS = (CREATE, DELETE, UPDATE, START, STOP
) = ('CREATE', 'DELETE', 'UPDATE', 'START', 'STOP')
STATUSES = (IN_PROGRESS, FAILED, COMPLETE
) = ('IN_PROGRESS', 'FAILED', 'COMPLETE')
_attrs = ['id', 'name', 'start_date', 'end_date', 'user_id', 'project_id',
'before_end_date', 'action', 'status', 'status_reason']
def __init__(self, apiresource):
super(Lease, self).__init__(apiresource)
@memoized
def blazarclient(request):
try:
api_url = base.url_for(request, 'reservation')
except exceptions.ServiceCatalogException:
LOG.debug('No Reservation service is configured.')
return None
LOG.debug('blazarclient connection created using the token "%s" and url'
'"%s"' % (request.user.token.id, api_url))
return blazar_client.Client(
blazar_url=api_url,
auth_token=request.user.token.id)
def lease_list(request):
"""List the leases."""
leases = blazarclient(request).lease.list()
return [Lease(l) for l in leases]
def lease_get(request, lease_id):
"""Get a lease."""
lease = blazarclient(request).lease.get(lease_id)
return Lease(lease)
def lease_create(request, name, start, end, reservations, events):
"""Create a lease."""
lease = blazarclient(request).lease.create(
name, start, end, reservations, events)
return Lease(lease)
def lease_update(request, lease_id, **kwargs):
"""Update a lease."""
lease = blazarclient(request).lease.update(lease_id, **kwargs)
return Lease(lease)
def lease_delete(request, lease_id):
"""Delete a lease."""
blazarclient(request).lease.delete(lease_id)

0
blazar_dashboard/content/__init__.py

0
blazar_dashboard/content/leases/__init__.py

88
blazar_dashboard/content/leases/forms.py

@ -0,0 +1,88 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from blazar_dashboard import api
LOG = logging.getLogger(__name__)
class UpdateForm(forms.SelfHandlingForm):
class Meta(object):
name = _('Update Lease Parameters')
lease_id = forms.CharField(
label=_('Lease ID'), widget=forms.widgets.HiddenInput, required=True)
lease_name = forms.CharField(
label=_('Lease name'), widget=forms.TextInput(), required=False)
start_time = forms.CharField(
label=_('Start time'),
widget=forms.TextInput(
attrs={'placeholder': _('Valid suffix are d/h/m (e.g. +1h)')}),
required=False)
end_time = forms.CharField(
label=_('End time'),
widget=forms.TextInput(
attrs={'placeholder': _('Valid suffix are d/h/m (e.g. +1h)')}),
required=False)
def handle(self, request, data):
lease_id = data.get('lease_id')
fields = {}
lease_name = data.get('lease_name', None)
if lease_name:
fields['name'] = lease_name
start_time = data.get('start_time', None)
end_time = data.get('end_time', None)
if start_time:
if start_time[0] == '+':
fields['defer_by'] = start_time[1:]
elif start_time[0] == '-':
fields['advance_by'] = start_time[1:]
if end_time:
if end_time[0] == '+':
fields['prolong_for'] = end_time[1:]
elif end_time[0] == '-':
fields['reduce_by'] = end_time[1:]
try:
api.client.lease_update(self.request, lease_id=lease_id, **fields)
messages.success(request, _("Lease update started."))
return True
except Exception as e:
LOG.error('Error updating lease: %s', e)
exceptions.handle(request,
message="An error occurred while updating this"
" lease: %s. Please try again." % e)
def clean(self):
cleaned_data = super(UpdateForm, self).clean()
lease_name = cleaned_data.get("lease_name")
start_time = cleaned_data.get("start_time")
end_time = cleaned_data.get("end_time")
if not (lease_name or start_time or end_time):
raise forms.ValidationError("Nothing to update.")

22
blazar_dashboard/content/leases/panel.py

@ -0,0 +1,22 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 django.utils.translation import ugettext_lazy as _
import horizon
class Leases(horizon.Panel):
name = _("Leases")
slug = "leases"

87
blazar_dashboard/content/leases/tables.py

@ -0,0 +1,87 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 datetime import datetime
from functools import partial
from django.template import defaultfilters as django_filters
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import tables
from horizon.utils import filters
import pytz
from blazar_dashboard import api
class UpdateLease(tables.LinkAction):
name = "update"
verbose_name = _("Update Lease")
url = "horizon:project:leases:update"
classes = ("btn-create", "ajax-modal")
def allowed(self, request, lease):
if datetime.strptime(lease.end_date, '%Y-%m-%dT%H:%M:%S.%f').\
replace(tzinfo=pytz.utc) > datetime.now(pytz.utc):
return True
return False
class DeleteLease(tables.DeleteAction):
name = "delete"
data_type_singular = _("Lease")
data_type_plural = _("Leases")
classes = ('btn-danger', 'btn-terminate')
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Lease",
u"Delete Leases",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Lease",
u"Deleted Leases",
count
)
def delete(self, request, lease_id):
api.client.lease_delete(request, lease_id)
class LeasesTable(tables.DataTable):
name = tables.Column("name", verbose_name=_("Lease name"),
link="horizon:project:leases:detail",)
start_date = tables.Column("start_date", verbose_name=_("Start date"),
filters=(filters.parse_isotime,
partial(django_filters.date,
arg='Y-m-d H:i T')),)
end_date = tables.Column("end_date", verbose_name=_("End date"),
filters=(filters.parse_isotime,
partial(django_filters.date,
arg='Y-m-d H:i T')),)
action = tables.Column("action", verbose_name=_("Action"),)
status = tables.Column("status", verbose_name=_("Status"),)
status_reason = tables.Column("status_reason", verbose_name=_("Reason"),)
class Meta(object):
name = "leases"
verbose_name = _("Leases")
table_actions = (DeleteLease, )
row_actions = (UpdateLease, DeleteLease, )

43
blazar_dashboard/content/leases/tabs.py

@ -0,0 +1,43 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from blazar_dashboard.api import client
class OverviewTab(tabs.Tab):
name = _("Overview")
slug = "overview"
template_name = "project/leases/_detail_overview.html"
def get_context_data(self, request):
lease_id = self.tab_group.kwargs['lease_id']
try:
lease = client.lease_get(self.request, lease_id)
except Exception:
redirect = reverse('horizon:project:leases:index')
msg = _('Unable to retrieve lease details.')
exceptions.handle(request, msg, redirect=redirect)
return {'lease': lease}
class LeaseDetailTabs(tabs.TabGroup):
slug = "lease_details"
tabs = (OverviewTab,)

64
blazar_dashboard/content/leases/templates/leases/_detail_overview.html

@ -0,0 +1,64 @@
{% load i18n sizeformat %}
<div class="detail">
<div class="info detail">
<h4>{% trans "Lease" %}</h4>
<hr class="header_rule">
<dl>
<dt>{% trans "Name" %}</dt>
<dd>{{ lease.name|default:_("None") }}</dd>
<dt>{% trans "Id" %}</dt>
<dd>{{ lease.id|default:_("None") }}</dd>
<dt>{% trans "Project Id" %}</dt>
<dd>{{ lease.project_id|default:_("None") }}</dd>
<dt>{% trans "Start date" %}</dt>
<dd>{{ lease.start_date|parse_isotime|date:"Y-m-d H:i T"|default:"-" }}</dd>
<dt>{% trans "End date" %}</dt>
<dd>{{ lease.end_date|parse_isotime|date:"Y-m-d H:i T"|default:"-" }}</dd>
<dt>{% trans "Action" %}</dt>
<dd>{{ lease.action|default:"-" }}</dd>
<dt>{% trans "Status" %}</dt>
<dd>{{ lease.status|default:"-" }}</dd>
<dt>{% trans "Status Reason" %}</dt>
<dd>{{ lease.status_reason|default:"-" }}</dd>
</dl>
</div>
<div class="info detail">
<h4>{% trans "Events" %}</h4>
<hr class="header_rule">
<dl>
{% for event in lease.events %}
<dt>{{ event.event_type }}</dt>
<dd>
<ul>
<li><em>{% trans "Status:" %}</em>&nbsp;{{ event.status|replace_underscores|lower|capfirst }}</li>
<li><em>{% trans "Time:" %}</em>&nbsp;{{ event.time|parse_isotime|date:"Y-m-d H:i T"|default:"-" }}</li>
</ul>
</dd>
{% empty %}
<dt>{% trans "No events defined." %}</dt>
{% endfor %}
</dl>
</div>
<div class="info detail">
<h4>{% trans "Reservations" %}</h4>
<hr class="header_rule">
<dl>
{% for reservation in lease.reservations %}
<dt>{{ reservation.resource_type }}</dt>
<dd>
<ul>
<li><em>{% trans "Id:" %}</em>&nbsp;{{ reservation.id|default:_("None") }}
<li><em>{% trans "Status:" %}</em>&nbsp;{{ reservation.status|replace_underscores|lower|capfirst }}</li>
<li><em>{% trans "Resource Id:" %}</em>&nbsp;{{ reservation.resource_id }}</li>
<li><em>{% trans "Created at:" %}</em>&nbsp;{{ reservation.created_at|parse_isotime|date:"Y-m-d H:i T"|default:"-" }}</li>
<li><em>{% trans "Updated at:" %}</em>&nbsp;{{ reservation.updated_at|parse_isotime|date:"Y-m-d H:i T"|default:"-" }}</li>
</ul>
</dd>
{% empty %}
<dt>{% trans "No reservations defined." %}</dt>
{% endfor %}
</dl>
</div>
</div>

24
blazar_dashboard/content/leases/templates/leases/_update.html

@ -0,0 +1,24 @@
{% extends "horizon/common/_modal_form.html" %}
{% load i18n %}
{% block form_id %}update_lease{% endblock %}
{% block form_action %}{% url 'horizon:project:leases:update' lease.id %}{% endblock %}
{% block modal_id %}update_lease_modal{% endblock %}
{% block modal-body %}
<div class="left">
<fieldset>
{% include "horizon/common/_form_fields.html" %}
</fieldset>
</div>
<div class="right">
<h3>{% trans "Description" %}:</h3>
<p>{% trans "Update a lease with the provided values." %}</p>
</div>
{% endblock %}
{% block modal-footer %}
<input class="btn btn-primary pull-right" type="submit" value="{% trans "Update" %}" />
<a href="{% url 'horizon:project:leases:index' %}" class="btn secondary cancel close">{% trans "Cancel" %}</a>
{% endblock %}

15
blazar_dashboard/content/leases/templates/leases/detail.html

@ -0,0 +1,15 @@
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Lease Detail"%}{% endblock %}
{% block page_header %}
{% include "horizon/common/_page_header.html" with title=_("Lease Detail") %}
{% endblock page_header %}
{% block main %}
<div class="row">
<div class="col-md-12">
{{ tab_group.render }}
</div>
</div>
{% endblock %}

11
blazar_dashboard/content/leases/templates/leases/index.html

@ -0,0 +1,11 @@
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Leases" %}{% endblock %}
{% block page_header %}
{% include "horizon/common/_page_header.html" with title=_("Leases") %}
{% endblock page_header %}
{% block main %}
{{ table.render }}
{% endblock %}

11
blazar_dashboard/content/leases/templates/leases/update.html

@ -0,0 +1,11 @@
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Update Lease" %}{% endblock %}
{% block page_header %}
{% include "horizon/common/_page_header.html" with title=_("Update Lease") %}
{% endblock page_header %}
{% block main %}
{% include 'project/leases/_update.html' %}
{% endblock %}

169
blazar_dashboard/content/leases/tests.py

@ -0,0 +1,169 @@
# 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 django.core.urlresolvers import reverse
from django import http
from mox3.mox import IsA
from blazar_dashboard import api
from blazar_dashboard.test import helpers as test
import logging
LOG = logging.getLogger(__name__)
INDEX_TEMPLATE = 'project/leases/index.html'
INDEX_URL = reverse('horizon:project:leases:index')
DETAIL_TEMPLATE = 'project/leases/detail.html'
DETAIL_URL_BASE = 'horizon:project:leases:detail'
UPDATE_URL_BASE = 'horizon:project:leases:update'
UPDATE_TEMPLATE = 'project/leases/update.html'
class LeasesTests(test.TestCase):
@test.create_stubs({api.client: ('lease_list',)})
def test_index(self):
leases = self.leases.list()
api.client.lease_list(IsA(http.HttpRequest)).AndReturn(leases)
self.mox.ReplayAll()
res = self.client.get(INDEX_URL)
self.assertTemplateUsed(res, INDEX_TEMPLATE)
self.assertNoMessages(res)
self.assertContains(res, 'lease-2')
self.assertContains(res, 'lease-1')
@test.create_stubs({api.client: ('lease_list',)})
def test_index_no_leases(self):
api.client.lease_list(IsA(http.HttpRequest)).AndReturn(())
self.mox.ReplayAll()
res = self.client.get(INDEX_URL)
self.assertTemplateUsed(res, INDEX_TEMPLATE)
self.assertNoMessages(res)
self.assertContains(res, 'No items to display')
@test.create_stubs({api.client: ('lease_list',)})
def test_index_error(self):
api.client.lease_list(
IsA(http.HttpRequest)
).AndRaise(self.exceptions.blazar)
self.mox.ReplayAll()
res = self.client.get(INDEX_URL)
self.assertTemplateUsed(res, INDEX_TEMPLATE)
self.assertMessageCount(res, error=1)
def test_lease_actions(self):
pass
@test.create_stubs({api.client: ('lease_get',)})
def test_lease_detail(self):
lease = self.leases.get(name='lease-1')
api.client.lease_get(IsA(http.HttpRequest),
lease['id']).AndReturn(lease)
self.mox.ReplayAll()
res = self.client.get(reverse(DETAIL_URL_BASE, args=[lease['id']]))
self.assertTemplateUsed(res, DETAIL_TEMPLATE)
self.assertContains(res, 'lease-1')
@test.create_stubs({api.client: ('lease_get',)})
def test_lease_detail_error(self):
api.client.lease_get(IsA(http.HttpRequest),
'invalid').AndRaise(self.exceptions.blazar)
self.mox.ReplayAll()
res = self.client.get(reverse(DETAIL_URL_BASE, args=['invalid']))
self.assertTemplateNotUsed(res, DETAIL_TEMPLATE)
self.assertMessageCount(error=1)
self.assertRedirectsNoFollow(res, INDEX_URL)
@test.create_stubs({api.client: ('lease_get', 'lease_update')})
def test_update_lease(self):
lease = self.leases.get(name='lease-1')
api.client.lease_get(
IsA(http.HttpRequest),
lease['id']
).AndReturn(lease)
api.client.lease_update(
IsA(http.HttpRequest),
lease_id=lease['id'],
name='newname',
prolong_for='1h'
)
form_data = {
'lease_id': lease['id'],
'lease_name': 'newname',
'end_time': '+1h'
}
self.mox.ReplayAll()
res = self.client.post(reverse(UPDATE_URL_BASE, args=[lease['id']]),
form_data)
self.assertNoFormErrors(res)
self.assertMessageCount(success=1)
self.assertRedirectsNoFollow(res, INDEX_URL)
@test.create_stubs({api.client: ('lease_get', 'lease_update')})
def test_update_lease_error(self):
lease = self.leases.get(name='lease-1')
api.client.lease_get(
IsA(http.HttpRequest),
lease['id']
).AndReturn(lease)
api.client.lease_update(
IsA(http.HttpRequest),
lease_id=lease['id'],
name='newname',
prolong_for='1h'
).AndRaise(self.exceptions.blazar)
form_data = {
'lease_id': lease['id'],
'lease_name': 'newname',
'end_time': '+1h'
}
self.mox.ReplayAll()
res = self.client.post(reverse(UPDATE_URL_BASE, args=[lease['id']]),
form_data)
self.assertTemplateUsed(UPDATE_TEMPLATE)
self.assertNoFormErrors(res)
self.assertContains(res, 'An error occurred while updating')
@test.create_stubs({api.client: ('lease_list', 'lease_delete')})
def test_delete_lease(self):
leases = self.leases.list()
lease = self.leases.get(name='lease-1')
api.client.lease_list(IsA(http.HttpRequest)).AndReturn(leases)
api.client.lease_delete(IsA(http.HttpRequest), lease['id'])
self.mox.ReplayAll()
action = 'leases__delete__%s' % lease['id']
form_data = {'action': action}
res = self.client.post(INDEX_URL, form_data)
self.assertMessageCount(success=1)
self.assertRedirectsNoFollow(res, INDEX_URL)
@test.create_stubs({api.client: ('lease_list', 'lease_delete')})
def test_delete_lease_error(self):
leases = self.leases.list()
lease = self.leases.get(name='lease-1')
api.client.lease_list(IsA(http.HttpRequest)).AndReturn(leases)
api.client.lease_delete(IsA(http.HttpRequest),
lease['id']).AndRaise(self.exceptions.blazar)
self.mox.ReplayAll()
action = 'leases__delete__%s' % lease['id']
form_data = {'action': action}
res = self.client.post(INDEX_URL, form_data)
self.assertMessageCount(error=1)
self.assertRedirectsNoFollow(res, INDEX_URL)

27
blazar_dashboard/content/leases/urls.py

@ -0,0 +1,27 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 django.conf.urls import url
from blazar_dashboard.content.leases import views as leases_views
urlpatterns = [
url(r'^$', leases_views.IndexView.as_view(), name='index'),
url(r'^(?P<lease_id>[^/]+)/$', leases_views.DetailView.as_view(),
name='detail'),
url(r'^(?P<lease_id>[^/]+)/update$', leases_views.UpdateView.as_view(),
name='update'),
]

79
blazar_dashboard/content/leases/views.py

@ -0,0 +1,79 @@
# Copyright 2014 Intel Corporation
# All Rights Reserved.
#
# 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 django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon import tabs
from horizon.utils import memoized
from blazar_dashboard import api
from blazar_dashboard.content.leases import forms as project_forms
from blazar_dashboard.content.leases import tables as project_tables
from blazar_dashboard.content.leases import tabs as project_tabs
class IndexView(tables.DataTableView):
table_class = project_tables.LeasesTable
template_name = 'project/leases/index.html'
def get_data(self):
try:
leases = api.client.lease_list(self.request)
except Exception:
leases = []
msg = _('Unable to retrieve lease information.')
exceptions.handle(self.request, msg)
return leases
class DetailView(tabs.TabView):
tab_group_class = project_tabs.LeaseDetailTabs
template_name = 'project/leases/detail.html'
class UpdateView(forms.ModalFormView):
form_class = project_forms.UpdateForm
template_name = 'project/leases/update.html'
success_url = reverse_lazy('horizon:project:leases:index')
def get_initial(self):
initial = super(UpdateView, self).get_initial()
initial['lease'] = self.get_object()
if initial['lease']:
initial['lease_id'] = initial['lease'].id
initial['name'] = initial['lease'].name
return initial
def get_context_data(self, **kwargs):
context = super(UpdateView, self).get_context_data(**kwargs)
context['lease'] = self.get_object()
return context
@memoized.memoized_method
def get_object(self):
lease_id = self.kwargs['lease_id']
try:
lease = api.client.lease_get(self.request, lease_id)
except Exception:
msg = _("Unable to retrieve lease.")
redirect = reverse('horizon:project:leases:index')
exceptions.handle(self.request, msg, redirect=redirect)
return lease

22
blazar_dashboard/enabled/_90_project_reservations_panelgroup.py

@ -0,0 +1,22 @@
# 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 django.utils.translation import ugettext_lazy as _
# The slug of the panel group to be added to HORIZON_CONFIG. Required.
PANEL_GROUP = 'reservations'
# The display name of the PANEL_GROUP. Required.
PANEL_GROUP_NAME = _('Reservations')
# The slug of the dashboard the PANEL_GROUP associated with. Required.
PANEL_GROUP_DASHBOARD = 'project'
ADD_INSTALLED_APPS = ['blazar_dashboard']

21
blazar_dashboard/enabled/_91_project_reservations_leases_panel.py

@ -0,0 +1,21 @@
# 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.
# The slug of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'leases'
# The slug of the panel group the PANEL is associated with.
PANEL_GROUP = 'reservations'
# The slug of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'project'
# Python panel class of the PANEL to be added.
ADD_PANEL = 'blazar_dashboard.content.leases.panel.Leases'

0
blazar_dashboard/enabled/__init__.py

0
blazar_dashboard/test/__init__.py

25
blazar_dashboard/test/helpers.py

@ -0,0 +1,25 @@
# 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 openstack_dashboard.test import helpers
from blazar_dashboard.test.test_data import utils
def create_stubs(stubs_to_create={}):
return helpers.create_stubs(stubs_to_create)
class TestCase(helpers.TestCase):
def _setup_test_data(self):
super(TestCase, self)._setup_test_data()
utils.load_test_data(self)

0
blazar_dashboard/test/integration_tests/__init__.py

37
blazar_dashboard/test/settings.py

@ -0,0 +1,37 @@
# 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.
# Default to Horizons test settings to avoid any missing keys
from horizon.test.settings import * # noqa: F403,H303
from openstack_dashboard.test.settings import * # noqa: F403,H303
# pop these keys to avoid log warnings about deprecation
# update_dashboards will populate them anyway
HORIZON_CONFIG.pop('dashboards', None)
HORIZON_CONFIG.pop('default_dashboard', None)
# Update the dashboards with blazar_dashboard
import blazar_dashboard.enabled
import openstack_dashboard.enabled
from openstack_dashboard.utils import settings
settings.update_dashboards(
[
blazar_dashboard.enabled,
openstack_dashboard.enabled,
],
HORIZON_CONFIG,
INSTALLED_APPS
)
# Ensure any duplicate apps are removed after the update_dashboards call
INSTALLED_APPS = list(set(INSTALLED_APPS))

0
blazar_dashboard/test/test_data/__init__.py

141
blazar_dashboard/test/test_data/blazar_data.py

@ -0,0 +1,141 @@
# 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 openstack_dashboard.test.test_data import utils
from blazar_dashboard import api
lease_sample1 = {
'status': None,
'user_id': None,
'name': 'lease-1',
'end_date': '2030-06-30T18:00:00.000000',
'reservations': [
{
'status': 'pending',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'min': 1,
'max': 1,
'hypervisor_properties': '',
'resource_id': '3850a831-8c08-49c4-b703-d804284a6baf',
'resource_properties': '[">=", "$vcpus", "2"]',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'id': '087bc740-6d2d-410b-9d47-c7b2b55a9d36',
'resource_type': 'physical:host'
}
],
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'events': [
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'start_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2017-06-27T18:00:00.000000',
'id': '188a8584-f832-4df9-9a4a-51e6364420ff'
},
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'end_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2030-06-30T18:00:00.000000',
'id': '277d6436-dfcb-4eae-ae5e-ac7fa9c2fd56'
},
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'before_end_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2030-06-28T18:00:00.000000',
'id': 'f583af71-ca21-4b66-87de-52211d118029'
}
],
'id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'action': None,
'project_id': 'aa45f56901ef45ee95e3d211097c0ea3',
'status_reason': None,
'start_date': '2017-06-27T18:00:00.000000',
'trust_id': 'b442a580b9504ababf305bf2b4c49512'
}
lease_sample2 = {
'status': None,
'user_id': None,
'name': 'lease-2',
'end_date': '2030-06-30T18:00:00.000000',
'reservations': [
{
'status': 'pending',
'lease_id': '9bcfff36-872e-4f47-9abe-9a58a4f22038',
'min': 1,
'max': 1,
'hypervisor_properties': '',
'resource_id': '369c83cb-d3de-4e15-9e15-b74625cf9ee5',
'resource_properties': '[">=", "$vcpus", "2"]',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'id': '1b05370e-d92a-452d-80db-89842666b604',
'resource_type': 'physical:host'
}
],
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'events': [
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'start_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2017-06-27T18:00:00.000000',
'id': '0d81cdd7-9390-4d19-8acf-746bc8f0167d'
},
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'end_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2030-06-30T18:00:00.000000',
'id': 'b2ac8924-b6d1-46fe-b1a9-43d9d5c683cf'
},
{
'status': 'UNDONE',
'lease_id': '6ee55c78-ac52-41a6-99af-2d2d73bcc466',
'event_type': 'before_end_lease',
'created_at': '2017-06-27 15:00:00',
'updated_at': None,
'time': '2030-06-28T18:00:00.000000',
'id': 'ba97b406-e721-47fe-9097-8ce6569f15d3'
}
],
'id': 'ef32abe8-a1f7-4c2f-b5f2-941428848230',
'action': None,
'project_id': 'aa45f56901ef45ee95e3d211097c0ea3',
'status_reason': None,
'start_date': '2017-06-27T18:00:00.000000',
'trust_id': 'b442a580b9504ababf305bf2b4c49512'
}
def data(TEST):
TEST.leases = utils.TestDataContainer()
TEST.leases.add(api.client.Lease(lease_sample1))
TEST.leases.add(api.client.Lease(lease_sample2))

56
blazar_dashboard/test/test_data/exceptions.py

@ -0,0 +1,56 @@
# 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 openstack_dashboard.test.test_data import exceptions
from openstack_dashboard.test.test_data import utils
import six
import blazarclient.exception as blazar_exceptions
def create_stubbed_exception(cls, status_code=500):
msg = "Expected failure."
def fake_init_exception(self, code=None, message=None, **kwargs):
if code is not None:
if hasattr(self, 'http_status'):
self.http_status = code
else:
self.code = code
self.message = message or self.__class__.message
try:
# Neutron sometimes updates the message with additional
# information, like a reason.
self.message = self.message % kwargs
except Exception:
pass # We still have the main error message.
def fake_str(self):
return str(self.message)
def fake_unicode(self):
return six.text_type(self.message)
cls.__init__ = fake_init_exception
cls.__str__ = fake_str
cls.__unicode__ =