Skip to content

Commit

Permalink
Improve helper and settings functions code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
mohierf committed Apr 19, 2017
1 parent 4c3855d commit 6f9a471
Show file tree
Hide file tree
Showing 12 changed files with 182 additions and 91 deletions.
2 changes: 2 additions & 0 deletions alignak_webui/backend/datamanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,7 @@ def get_host_services(self, host, search=None, embedded=True):
return self.get_services(search=search, embedded=embedded, all_elements=True)

def get_host_overall_state(self, host):
# pylint: disable=no-self-use
"""Get a host real state (including services states).
Returns a tuple with host overall state and status
Expand Down Expand Up @@ -1635,6 +1636,7 @@ def get_service(self, search):
return items[0] if items else None

def get_service_overall_state(self, service):
# pylint: disable=no-self-use
"""Get a service real state (including services states).
Returns a tuple with service overall state and status
Expand Down
18 changes: 7 additions & 11 deletions alignak_webui/objects/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def __init__(self, params=None, date_format='%a, %d %b %Y %H:%M:%S %Z', embedded
self.__class__)
return

if not isinstance(params, dict):
if not isinstance(params, dict): # pragma: no cover, should not happen
if self.__class__ == params.__class__:
params = params.__dict__
elif self.get_known_classes() and params.__class__ in self.get_known_classes():
Expand Down Expand Up @@ -341,7 +341,7 @@ def __init__(self, params=None, date_format='%a, %d %b %Y %H:%M:%S %Z', embedded
key, params[key].__class__, value)

object_type = getattr(self, '_linked_' + key, None)
if object_type is None:
if object_type is None: # pragma: no cover, should not happen
logger.error("__init__, object_type is None, key %s for %s, as %s for %s",
key, self.get_type(), object_type, params[key])
continue
Expand Down Expand Up @@ -395,7 +395,7 @@ def __init__(self, params=None, date_format='%a, %d %b %Y %H:%M:%S %Z', embedded
logger.error("__init__, item not found for %s, %s",
object_type, value)
continue
except:
except: # pragma: no cover, should not happen
logger.error("__init__, item not existing for %s, %s",
object_type, value)
continue
Expand Down Expand Up @@ -425,7 +425,7 @@ def __init__(self, params=None, date_format='%a, %d %b %Y %H:%M:%S %Z', embedded
logger.error("__init__, item not found for %s, %s",
object_type, value)
continue
except:
except: # pragma: no cover, should not happen
logger.error("__init__, item not existing for %s, %s",
object_type, value)
continue
Expand Down Expand Up @@ -481,16 +481,12 @@ def id(self):
@property
def updated(self):
"""Get Item update date as a timestamp"""
if hasattr(self, '_updated'):
return self._updated
return self._default_date
return self._updated

@property
def created(self):
"""Get Item creation date as a timestamp"""
if hasattr(self, '_created'):
return self._created
return self._default_date
return self._created

@property
def name(self):
Expand Down Expand Up @@ -638,7 +634,7 @@ def acknowledged(self):
return False

@property
def downtime(self):
def downtimed(self):
"""An element is never in a downtime except if it overloads this method"""
return False

Expand Down
2 changes: 1 addition & 1 deletion alignak_webui/plugins/hosts/views/host.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@
<span class="fa fa-external-link"></span> {{_('Actions') if len(action_urls) == 1 else _('Actions')}}&nbsp;<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
%for action_url in Helper.get_element_actions_url(host, default_title="Url", default_icon="globe", popover=True):
%for action_url in Helper.get_element_actions_url(host, default_title="Url", default_icon="globe"):
<li>{{! action_url}}</li>
%end
</ul>
Expand Down
2 changes: 1 addition & 1 deletion alignak_webui/plugins/services/views/service.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
<i class="fa fa-external-link"></i> {{_('Action') if len(action_urls) == 1 else _('Actions')}}&nbsp;<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
%for action_url in Helper.get_element_actions_url(service, default_title="Url", default_icon="globe", popover=True):
%for action_url in Helper.get_element_actions_url(service, default_title="Url", default_icon="globe"):
<li>{{!action_url}}</li>
%end
</ul>
Expand Down
61 changes: 21 additions & 40 deletions alignak_webui/utils/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def get_html_business_impact(business_impact, icon=True, text=False):
return ' '.join(element.split())

@staticmethod
def get_urls(url, default_title="Url", default_icon="globe", popover=False):
def get_urls(url, default_title="Url", default_icon="globe"):
"""Returns formatted HTML for an element URL
url string may contain a list of urls separated by | (pipe symbol)
Expand All @@ -260,10 +260,8 @@ def get_urls(url, default_title="Url", default_icon="globe", popover=False):
If title is not specified, default_title is used as title
If icon is not specified, default_icon is used as icon
If popover is true, a bootstrap popover is built, else a standard link ...
"""
logger.debug("get_urls: %s / %s / %s / %d", url, default_title, default_icon, popover)
logger.debug("get_urls: %s / %s / %s", url, default_title, default_icon)

items_count = url.split('|')
logger.debug("get_urls, items: %s", items_count)
Expand Down Expand Up @@ -294,58 +292,41 @@ def get_urls(url, default_title="Url", default_icon="globe", popover=False):
logger.debug("get_urls, found title and icon: %s / %s", title, icon)
logger.debug("get_urls, found description: %s", description)

if popover:
if url != '':
result.append(
'<a href="%s" target="_blank" role="button" data-toggle="popover urls" '
'data-container="body" data-html="true" data-content="%s" '
'data-trigger="hover focus" data-placement="bottom">'
'<span class="fa fa-%s"></span>&nbsp;%s</a>' % (
url, description, icon, title
)
)
else:
result.append(
'<a href="#" role="button" data-toggle="popover urls" '
'data-container="body" data-html="true" data-content="%s" '
'data-trigger="hover focus" data-placement="bottom">'
'<span class="fa fa-%s"></span>&nbsp;%s</span></a>' % (
description, icon, title
)
if url:
result.append(
'<a href="%s" target="_blank" role="button" data-toggle="popover urls" '
'data-container="body" data-html="true" data-content="%s" '
'data-trigger="hover focus" data-placement="bottom">'
'<span class="fa fa-%s"></span>&nbsp;%s</a>' % (
url, description, icon, title
)
)
else:
if url != '':
result.append(
'<a href="%s" target="_blank" title="%s">'
'<span class="fa fa-%s"></span>&nbsp;%s</a>' % (
url, description, icon, title
)
result.append(
'<a href="#" role="button" data-toggle="popover urls" '
'data-container="body" data-html="true" data-content="%s" '
'data-trigger="hover focus" data-placement="bottom">'
'<span class="fa fa-%s"></span>&nbsp;%s</span></a>' % (
description, icon, title
)
else:
result.append(
'<a href="#" title="%s">'
'<span class="fa fa-%s"></span>&nbsp;%s</a>' % (
description, icon, title
)
)

)
return result

@staticmethod
def get_element_actions_url(obj, default_title="Url", default_icon="globe", popover=False):
def get_element_actions_url(obj, default_title="Url", default_icon="globe"):
"""Return list of element action urls"""

try:
logger.debug("get_element_actions_url, url: %s", obj.action_url)
return Helper.get_urls(obj.action_url, default_title=default_title,
default_icon=default_icon, popover=popover)
default_icon=default_icon)
except AttributeError:
pass

return []

@staticmethod
def get_element_notes_url(obj, default_title="Url", default_icon="globe", popover=False):
def get_element_notes_url(obj, default_title="Url", default_icon="globe"):
"""Return list of element notes urls"""

if obj is not None and obj.notes:
Expand All @@ -364,7 +345,7 @@ def get_element_notes_url(obj, default_title="Url", default_icon="globe", popove
logger.debug("get_element_notes_url, note: %s", notes)

return Helper.get_urls('|'.join(notes), default_title=default_title,
default_icon=default_icon, popover=popover)
default_icon=default_icon)

return []

Expand Down
2 changes: 1 addition & 1 deletion alignak_webui/utils/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def get_service_metric(self, service):
state = s.state_id
if s.acknowledged:
state = 4
if s.downtime:
if s.downtimed:
state = 5

try: # pragma: no cover - no existing data when testing :(
Expand Down
27 changes: 6 additions & 21 deletions alignak_webui/utils/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Settings(OrderedDict):
Class used to manage configuration file and application configuration
"""

def __init__(self, filename=None):
def __init__(self, filenames=None):
"""
Initialize configuration
Expand All @@ -47,7 +47,7 @@ def __init__(self, filename=None):
"""
super(Settings, self).__init__()

self.filename = filename
self.filenames = filenames

def read(self, app_name='Alignak-WebUI'):
# pylint: disable=too-many-nested-blocks
Expand All @@ -74,26 +74,11 @@ def read(self, app_name='Alignak-WebUI'):
:param app_name: application name (to build configuration file name)
"""
if not app_name:
return None
app_name = app_name.lower()

if self.filename:
if not isinstance(self.filename, list):
settings_filenames = [
os.path.abspath(self.filename)
]
else:
settings_filenames = self.filename
else:
settings_filenames = [
'/usr/local/etc/%s/settings.cfg' % app_name,
'/etc/%s/settings.cfg' % app_name,
'~/%s/settings.cfg' % app_name,
os.path.abspath('../etc/settings.cfg'),
os.path.abspath('../%s/etc/settings.cfg' % app_name),
'./settings.cfg'
]
settings_filenames = self.filenames
if not isinstance(self.filenames, list):
settings_filenames = [os.path.abspath(self.filenames)]

try:
config = RawConfigParser()
Expand All @@ -116,7 +101,7 @@ def read(self, app_name='Alignak-WebUI'):
self[section + '.' + option] = False

return found_cfg_file
except Exception as exp:
except Exception as exp: # pragma: no cover - bad formated file
print("Bad formed configuration file.")
print("Exception: %s" % str(exp))
print("Traceback: %s" % traceback.format_exc())
Expand Down
2 changes: 1 addition & 1 deletion alignak_webui/views/modal_waiting.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<div class="modal-header text-center">
<h4 class="modal-title">{{_('Default waiting message')}}</h4>
</div>
<div class="modal-body" >
<div class="modal-body">
<div style="height:120px" class="text-center">
<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>
<span class="sr-only">{{_('Loading...')}}</span>
Expand Down
8 changes: 4 additions & 4 deletions test/test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ def test_notes_url(self):
})
assert host

html_notes = Helper.get_element_notes_url(host, default_title="Note", default_icon="tag", popover=True)
html_notes = Helper.get_element_notes_url(host, default_title="Note", default_icon="tag")
# Empty list when no notes exist
assert html_notes == []

Expand All @@ -803,7 +803,7 @@ def test_notes_url(self):
})
assert host

html_notes = Helper.get_element_notes_url(host, default_title="Note", default_icon="tag", popover=True)
html_notes = Helper.get_element_notes_url(host, default_title="Note", default_icon="tag")
# 5 declared notes, but only 2 URLs
# Expecting 5 links
assert html_notes == [
Expand All @@ -826,7 +826,7 @@ def test_actions_url(self):
})
assert host

html_actions = Helper.get_element_actions_url(host, default_title="Url", default_icon="globe", popover=True)
html_actions = Helper.get_element_actions_url(host, default_title="Url", default_icon="globe")
assert html_actions == []

host = Host({
Expand All @@ -839,7 +839,7 @@ def test_actions_url(self):
})
assert host

html_actions = Helper.get_element_actions_url(host, default_title="Url", default_icon="globe", popover=True)
html_actions = Helper.get_element_actions_url(host, default_title="Url", default_icon="globe")
# 3 declared actions, with different parameters
# Expecting 3 links
assert html_actions == [
Expand Down
9 changes: 0 additions & 9 deletions test/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@
loggerDm.setLevel(logging.DEBUG)


def setup_module(module):
# Get configuration from only one file ...
print ("read configuration")
cfg = Settings(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'settings.cfg'))
found_cfg_files = cfg.read('Alignak-WebUI')
assert found_cfg_files
set_app_config(cfg)


class TestClassElements(unittest2.TestCase):
def test_class(self):
""" Items - class variables """
Expand Down

0 comments on commit 6f9a471

Please sign in to comment.