Skip to content

Commit

Permalink
Unit tests for HTML construction (#256)
Browse files Browse the repository at this point in the history
* Populate a submodule for unit tests of gwsumm.html

* Unit tests for gwsumm.html.static

* Remove comments box, since they are no longer used

* Unit tests for gwsumm.html.html5

* Unit tests for gwsumm.html.bootstrap

* Removed global variable for comments boxes

* Exclude unit tests from coverage estimates

* Restore comments boxes

* Include id_ use case in unit test for base_map_dropdown

* Expand coverage of unit tests for gwsumm.html.html5

* Minor edits to test_static.py
  • Loading branch information
Alex L. Urban authored Apr 24, 2019
1 parent 8c55eeb commit 29fdde7
Show file tree
Hide file tree
Showing 7 changed files with 316 additions and 5 deletions.
6 changes: 2 additions & 4 deletions gwsumm/html/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,6 @@ def calendar(date, tag='a', class_='navbar-brand dropdown-toggle',
triggering dropdown
"""
mode = get_mode(mode)
if mode < Mode.day:
raise ValueError("Cannot generate calendar for Mode %s" % mode)
if dateformat is None:
if mode == Mode.day:
dateformat = '%B %d %Y'
Expand All @@ -105,7 +103,7 @@ def calendar(date, tag='a', class_='navbar-brand dropdown-toggle',
elif mode == Mode.year:
dateformat = '%Y'
else:
raise ValueError("Cannot set dateformat for Mode %s" % mode)
raise ValueError("Cannot generate calendar for Mode %s" % mode)
datestring = date.strftime(dateformat).replace(' 0', ' ')
data_date = date.strftime('%d-%m-%Y')
page = markup.page()
Expand Down Expand Up @@ -198,5 +196,5 @@ def base_map_dropdown(this, class_='btn-group pull-left base-map', id_=None,
class_='navbar-brand dropdown-toggle')))
page.div.close()
else:
page.div(str(this), class_='navbar-brand')
page.div(str(this), class_='navbar-brand', **id_)
return page
2 changes: 1 addition & 1 deletion gwsumm/html/html5.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def load(url, id_='main', error=False, success=None):
% (id_, url))
elif ps.netloc and not error:
error = ('alert("Cannot load content from %r, use browser console '
'to inspect failure.");')
'to inspect failure.");' % url)
else:
if not isinstance(error, (string_types, markup.page)):
error = 'Failed to load content from %r' % url
Expand Down
22 changes: 22 additions & 0 deletions gwsumm/html/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
# Copyright (C) Alex Urban (2019)
#
# This file is part of GWSumm.
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWSumm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.

"""Unit tests for gwsumm.html
"""

__author__ = 'Alex Urban <alexander.urban@ligo.org>'
106 changes: 106 additions & 0 deletions gwsumm/html/tests/test_bootstrap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# -*- coding: utf-8 -*-
# Copyright (C) Alex Urban (2019)
#
# This file is part of GWSumm.
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWSumm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.

"""Unit tests for gwsumm.html.bootstrap
"""

__author__ = 'Alex Urban <alexander.urban@ligo.org>'

import pytest
from datetime import datetime

from gwdetchar.utils import parse_html

from .. import bootstrap

# global variables
DATE = datetime.strptime('20140410', '%Y%m%d')
CALENDAR = """<a class="navbar-brand step-back" title="Step back" onclick="stepDate(-1)">&laquo;</a>
<a id="calendar" class="navbar-brand dropdown-toggle" title="Show/hide calendar" data-date="10-04-2014" data-date-format="dd-mm-yyyy" data-viewmode="{}">
{}
<b class="caret"></b>
</a>
<a class="navbar-brand step-forward" title="Step forwards" onclick="stepDate(1)">&raquo;</a>""" # nopep8


# test utilities

def test_banner():
banner = bootstrap.banner('Test', subtitle='Subtest')
assert parse_html(str(banner)) == parse_html(
'<div class="banner">\n<h1>Test</h1>\n<p>Subtest</p>\n</div>')
# test with classes
banner_wclass = bootstrap.banner(
'Test', subtitle='Subtest', titleclass='test', subtitleclass='subtest')
assert parse_html(str(banner_wclass)) == parse_html(
'<div class="banner">\n<h1 class=\"test\">Test</h1>\n'
'<p class=\"subtest\">Subtest</p>\n</div>')

@pytest.mark.parametrize('mode, datefmt', [
('day', 'April 10 2014'),
('week', 'Week of April 10 2014'),
('month', 'April 2014'),
('year', '2014'),
])
def test_calendar(mode, datefmt):
cal = bootstrap.calendar(DATE, mode=mode)
assert parse_html(str(cal)) == parse_html(CALENDAR.format(
'%ss' % mode, datefmt))


def test_calendar_no_mode():
# test with no Mode
with pytest.raises(ValueError) as exc:
cal = bootstrap.calendar(DATE)
assert str(exc.value).startswith('Cannot generate calendar for Mode')


def test_wrap_content():
content = bootstrap.wrap_content('test')
assert parse_html(str(content)) == parse_html(
'<div class="container" id="main">\ntest\n</div>')


def test_state_switcher():
switcher = bootstrap.state_switcher([('Test', '#test')])
assert parse_html(str(switcher)) == parse_html(
'<div class="btn-group pull-right state-switch">\n'
'<a class="navbar-brand dropdown-toggle" href="#" id="states" '
'title="Show/hide state menu" data-toggle="dropdown">\n'
'Test\n<b class="caret"></b>\n</a>\n'
'<ul class="dropdown-menu" id="statemenu">\n'
'<li class="dropdown-header">Select an option below to view '
'these data in another state (different time segments).</li>\n'
'<li class="divider"></li>\n<li>\n'
'<a class="state" title="Test" id="state_test" '
'onclick="$(this).load_state(&quot;#test&quot;);">Test</a>\n'
'</li>\n</ul>\n</div>')


def test_base_map_dropdown():
menu = bootstrap.base_map_dropdown('test', id_='id')
assert parse_html(str(menu)) == parse_html(
'<div class=\"navbar-brand\" id=\"id\">test</div>')
# test with bases
menu_wbases = bootstrap.base_map_dropdown('test', bases={'key': 'value'})
assert parse_html(str(menu_wbases)) == parse_html(
'<div class="btn-group pull-left base-map">\n'
'<a href="#" class="navbar-brand dropdown-toggle" '
'data-toggle="dropdown">\ntest\n<b class="caret"></b>\n</a>\n'
'<ul class="dropdown-menu">\n<li>\n'
'<a title="key" data-new-base="value">key</a>\n</li>\n</ul>\n</div>')
107 changes: 107 additions & 0 deletions gwsumm/html/tests/test_html5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
# Copyright (C) Alex Urban (2019)
#
# This file is part of GWSumm.
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWSumm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.

"""Unit tests for gwsumm.html.html5
"""

__author__ = 'Alex Urban <alexander.urban@ligo.org>'

from gwdetchar.utils import parse_html

from .. import html5

# global variables

URL = 'https://github.com/gwpy/gwsumm'
LOAD = """<script>
$.ajax({
url : '%s',
type : 'GET',
success: function(data, statusText, jqhxr){%s},
error: function(xhr, status, error){%s}
});
</script>"""

BOX = """<div id="disqus_thread">
<script type="text/javascript">
var disqus_shortname = "Test";
var disqus_identifier = "test";
var disqus_title = "Test";
var disqus_url = "%s";
(function() {
var dsq = document.createElement('script');
dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the</noscript>
<a href="https://disqus.com/?ref_noscript">comments powered by Disqus</a>
</div>"""


# test utilities

def test_load_state():
state = html5.load_state('test')
assert parse_html(str(state)) == parse_html(
'<script>\nif (location.hash.length <= 1) {\n'
' $("#state_test").load_state("test");\n}\n'
'</script>')


def test_load():
# test local url
content = html5.load('test')
assert parse_html(content) == parse_html(
'<script>$("#main").load("test");</script>')
# test non-local url
success = '$(\"#main\").html(data);'
errormsg = ('alert(\"Cannot load content from %r, use '
'browser console to inspect failure.\");' % URL)
content = html5.load(URL)
assert parse_html(content) == parse_html(LOAD % (URL, success, errormsg))
# test with non-string error argument
success = '$(\"#main\").html(data);'
error = 'Failed to load content from %r' % URL
errormsg = ('$(\"#main\").html(\"<div class=\'alert alert-warning\'>'
'<p>%s</p></div>\");' % error)
content = html5.load(URL, error=1)
assert parse_html(content) == parse_html(LOAD % (URL, success, errormsg))


def test_load_custom():
error = 'Error'
success = 'document.write(\"Success\")'
errormsg = ('$(\"#main\").html(\"<div class=\'alert alert-warning\'>'
'<p>%s</p></div>\");' % error)
# test local url
content = html5.load('test', success=success, error=error)
assert parse_html(content) == parse_html(
LOAD % ('test', success, errormsg))
# test non-local url
content = html5.load(URL, success=success, error=error)
assert parse_html(content) == parse_html(LOAD % (URL, success, errormsg))


def test_comments_box():
box = html5.comments_box('Test', identifier='test', title='Test', url=URL)
assert parse_html(str(box)) == parse_html(BOX % URL)
77 changes: 77 additions & 0 deletions gwsumm/html/tests/test_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
# Copyright (C) Alex Urban (2019)
#
# This file is part of GWSumm.
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWSumm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.

"""Unit tests for gwsumm.html.static
"""

__author__ = 'Alex Urban <alexander.urban@ligo.org>'

import os.path

from collections import OrderedDict

from gwdetchar.io.html import (CSS_FILES as GWDETCHAR_CSS_FILES,
JS_FILES as GWDETCHAR_JS_FILES)

from .. import static


# test simple utils

def test_get_css():
css = static.get_css()
assert isinstance(css, OrderedDict)
# test dict keys
keys = list(css.keys())
assert keys == [
'bootstrap',
'fancybox',
'datepicker',
'bootstrap-ligo',
'gwdetchar',
'gwsumm',
]
# test list of files
css_files = list(css.values())
assert len(css_files) == len(GWDETCHAR_CSS_FILES) + 2
assert set(GWDETCHAR_CSS_FILES) < set(css_files)
assert os.path.basename(css_files[2]) == 'bootstrap-datepicker.min.css'
assert os.path.basename(css_files[5]) == 'gwsumm.min.css'


def test_get_js():
js = static.get_js()
assert isinstance(js, OrderedDict)
# test dict keys
keys = list(js.keys())
assert keys == [
'jquery',
'moment',
'bootstrap',
'fancybox',
'datepicker',
'bootstrap-ligo',
'gwdetchar',
'gwsumm',
]
# test list of files
js_files = list(js.values())
assert len(js_files) == len(GWDETCHAR_JS_FILES) + 2
assert set(GWDETCHAR_JS_FILES) < set(js_files)
assert os.path.basename(js_files[4]) == 'bootstrap-datepicker.min.js'
assert os.path.basename(js_files[7]) == 'gwsumm.min.js'
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ parentdir_prefix =
source = gwsumm
omit =
gwsumm/tests/*
gwsumm/html/tests/*
gwsumm/*version*

[flake8]
Expand Down

0 comments on commit 29fdde7

Please sign in to comment.