Skip to content

Commit

Permalink
Merge pull request #114 from alurban/unit-tests
Browse files Browse the repository at this point in the history
Unit test expansion pack
  • Loading branch information
jrsmith02 authored Mar 12, 2019
2 parents 19e378b + f419769 commit 1221312
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 256 deletions.
5 changes: 3 additions & 2 deletions bin/hveto
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ from gwpy.time import to_gps
from gwpy.segments import (Segment, SegmentList,
DataQualityFlag, DataQualityDict)

from gwdetchar.io.html import FancyPlot

from hveto import (__version__, log, config, core, plot, html, utils)
from hveto.plot import (HEADER_CAPTION, ROUND_CAPTION, FancyPlot,
get_column_label)
from hveto.plot import (HEADER_CAPTION, ROUND_CAPTION, get_column_label)
from hveto.segments import (write_ascii as write_ascii_segments,
read_veto_definer_file)
from hveto.triggers import (get_triggers, find_auxiliary_channels)
Expand Down
140 changes: 9 additions & 131 deletions hveto/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from MarkupPy import markup

from gwdetchar.io.html import package_table
from gwdetchar.io import html as gwhtml

from ._version import get_versions

Expand Down Expand Up @@ -325,128 +325,6 @@ def bold_param(key, value, **attrs):
return markup.oneliner.p('<b>%s</b>: %s' % (key, value), **attrs)


def html_link(href, txt, target="_blank", **params):
"""Write an HTML <a> tag
Parameters
----------
href : `str`
the URL to point to
txt : `str`
the text for the link
target : `str`, optional
the ``target`` of this link
**params
other HTML parameters for the ``<a>`` tag
Returns
-------
html : `str`
"""
if target is not None:
params.setdefault('target', target)
return markup.oneliner.a(txt, href=href, **params)


def cis_link(channel, **params):
"""Write a channel name as a link to the Channel Information System
Parameters
----------
channel : `str`
the name of the channel to link
**params
other HTML parmeters for the ``<a>`` tag
Returns
-------
html : `str`
"""
kwargs = {
'title': "CIS entry for %s" % channel,
'style': "font-family: Monaco, \"Courier New\", monospace;",
}
kwargs.update(params)
return html_link("https://cis.ligo.org/channel/byname/%s" % channel,
channel, **kwargs)


def fancybox_img(img, linkparams=dict(), **params):
"""Return the markup to embed an <img> in HTML
Parameters
----------
img : `FancyPlot`
a `FancyPlot` object containing the path of the image to embed
and its caption to be displayed
linkparams : `dict`
the HTML attributes for the ``<a>`` tag
**params
the HTML attributes for the ``<img>`` tag
Returns
-------
html : `str`
Notes
-----
See `~hveto.plot.FancyPlot` for more about the `FancyPlot` class.
"""
page = markup.page()
aparams = {
'title': img.caption,
'class_': 'fancybox',
'target': '_blank',
'data-fancybox-group': 'hveto-image',
}
aparams.update(linkparams)
img = str(img)
page.a(href=img, **aparams)
imgparams = {
'alt': os.path.basename(img),
'class_': 'img-responsive',
}
if img.endswith('.svg') and os.path.isfile(img.replace('.svg', '.png')):
imgparams['src'] = img.replace('.svg', '.png')
else:
imgparams['src'] = img
imgparams.update(params)
page.img(**imgparams)
page.a.close()
return str(page)


def scaffold_plots(plots, nperrow=2):
"""Embed a `list` of images in a bootstrap scaffold
Parameters
----------
plot : `list` of `str`
the list of image paths to embed
nperrow : `int`
the number of images to place in a row (on a desktop screen)
Returns
-------
page : `~MarkupPy.markup.page`
the markup object containing the scaffolded HTML
"""
page = markup.page()
x = int(12//nperrow)
# scaffold plots
for i, p in enumerate(plots):
if i % nperrow == 0:
page.div(class_='row')
page.div(class_='col-sm-%d' % x)
page.add(fancybox_img(p))
page.div.close() # col
if i % nperrow == nperrow - 1:
page.div.close() # row
if i % nperrow < nperrow-1:
page.div.close() # row
return page()


def write_footer(about=None, date=None):
"""Write a <footer> for an Hveto page
Expand Down Expand Up @@ -529,10 +407,10 @@ def write_summary(
for r in rounds:
page.tr()
# link round down page
page.td(html_link('#hveto-round-%d' % r.n, r.n, target=None,
title="Jump to round %d details" % r.n))
page.td(gwhtml.html_link('#hveto-round-%d' % r.n, r.n, target=None,
title="Jump to round %d details" % r.n))
# link name to CIS
page.td(cis_link(r.winner.name))
page.td(gwhtml.cis_link(r.winner.name))
for attr in ['window', 'snr', 'significance']:
v = getattr(r.winner, attr)
if isinstance(v, float):
Expand All @@ -557,7 +435,7 @@ def write_summary(

# scaffold plots
if plots:
page.add(scaffold_plots(plots, nperrow=plotsperrow))
page.add(gwhtml.scaffold_plots(plots, nperrow=plotsperrow))
return page()


Expand Down Expand Up @@ -605,7 +483,7 @@ def write_round(round):
files = [round.files[tag]]
else:
files = round.files[tag]
link = ' '.join([html_link(
link = ' '.join([gwhtml.html_link(
f, '[%s]' % os.path.splitext(f)[1].strip('.')) for f in files])
page.add(bold_param(desc, link))
# link omega scans if generated
Expand All @@ -631,11 +509,11 @@ def write_round(round):
page.div.close() # col
# plots
page.div(class_='col-md-9', id_='hveto-round-%d-plots' % round.n)
page.add(scaffold_plots(round.plots[:-1], nperrow=4))
page.add(gwhtml.scaffold_plots(round.plots[:-1], nperrow=4))
# add significance drop plot at end
page.div(class_='row')
page.div(class_='col-sm-12')
page.add(fancybox_img(round.plots[-1]))
page.add(gwhtml.fancybox_img(round.plots[-1]))
page.div.close() # col-sm-12
page.div.close() # row
page.div.close() # col-md-8
Expand Down Expand Up @@ -760,6 +638,6 @@ def write_about_page(configfile):
page.add(contents)

# runtime environment
page.add(package_table())
page.add(gwhtml.package_table())

return page
30 changes: 0 additions & 30 deletions hveto/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,36 +207,6 @@ def get_column_label(column):
return r'\texttt{{{0}}}'.format(column)


# -- Plot construction --------------------------------------------------------

class FancyPlot(object):
"""A helpful class of objects that coalesce image links and caption text
for fancybox figures.
Parameters
----------
img : `str` or `FancyPlot`
either a filename (including relative or absolute path) or another
FancyPlot instance
caption : `str`
the text to be displayed in a fancybox as this figure's caption
Examples
--------
>>> from hveto.plot import FancyPlot
>>> example = FancyPlot('plot.png')
>>> print example.img, example.caption
"""
def __init__(self, img, caption=None):
if isinstance(img, FancyPlot):
caption = caption if caption else img.caption
self.img = str(img)
self.caption = caption if caption else os.path.basename(self.img)

def __str__(self):
return self.img


# -- Functions ----------------------------------------------------------------

def before_after_histogram(
Expand Down
8 changes: 5 additions & 3 deletions hveto/segments.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@
def integer_segments(f):
@wraps(f)
def decorated_method(*args, **kwargs):
segs = f(*args, **kwargs)
return type(segs)(type(s)(int(s[0]), int(s[1])) for s in segs)
flag = f(*args, **kwargs)
segs = flag.active
flag.active = type(segs)(type(s)(int(s[0]), int(s[1])) for s in segs)
return flag
return decorated_method


Expand Down Expand Up @@ -74,6 +76,6 @@ def read_veto_definer_file(vetofile, start=None, end=None, ifo=None):
tmp = urlopen(vetofile)
vetofile = os.path.abspath(os.path.basename(vetofile))
with open(vetofile, 'w') as f:
f.write(tmp.read())
f.write(str(tmp.read()))
return DataQualityDict.from_veto_definer_file(
vetofile, format='ligolw', start=start, end=end, ifo=ifo)
69 changes: 9 additions & 60 deletions hveto/tests/test_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

from .. import html
from .._version import get_versions
from ..plot import FancyPlot
from ..utils import parse_html

VERSION = get_versions()['version']
Expand Down Expand Up @@ -135,64 +134,6 @@ def test_bold_param(args, kwargs, result):
assert h1 == h2


@pytest.mark.parametrize('args, kwargs, result', [
(('test.html', 'Test link'), {},
'<a href="test.html" target="_blank">Test link</a>'),
(('test.html', 'Test link'), {'class_': 'test-case'},
'<a class="test-case" href="test.html" target="_blank">Test link</a>'),
])
def test_html_link(args, kwargs, result):
h1 = parse_html(html.html_link(*args, **kwargs))
h2 = parse_html(result)
assert h1 == h2


def test_cis_link():
h1 = parse_html(html.cis_link('X1:TEST-CHANNEL'))
h2 = parse_html(
'<a style="font-family: Monaco, &quot;Courier New&quot;, '
'monospace;" href="https://cis.ligo.org/channel/byname/'
'X1:TEST-CHANNEL" target="_blank" title="CIS entry for '
'X1:TEST-CHANNEL">X1:TEST-CHANNEL</a>'
)
assert h1 == h2


def test_fancybox_img():
img = FancyPlot('test.png')
out = html.fancybox_img(img)
assert parse_html(out) == parse_html(
'<a class="fancybox" href="test.png" target="_blank" '
'data-fancybox-group="hveto-image" title="test.png">\n'
'<img class="img-responsive" alt="test.png" src="test.png" />'
'\n</a>'
)


def test_scaffold_plots():
h1 = parse_html(html.scaffold_plots([FancyPlot('plot1.png'),
FancyPlot('plot2.png')]))
h2 = parse_html(
'<div class="row">\n'
'<div class="col-sm-6">\n'
'<a class="fancybox" href="plot1.png" target="_blank" '
'data-fancybox-group="hveto-image" title="plot1.png">\n'
'<img class="img-responsive" alt="plot1.png" '
'src="plot1.png" />\n'
'</a>\n'
'</div>\n'
'<div class="col-sm-6">\n'
'<a class="fancybox" href="plot2.png" target="_blank" '
'data-fancybox-group="hveto-image" title="plot2.png">\n'
'<img class="img-responsive" alt="plot2.png" '
'src="plot2.png" />\n'
'</a>\n'
'</div>\n'
'</div>'
)
assert h1 == h2


def test_write_footer():
date = datetime.datetime.now()
out = html.write_footer(date=date)
Expand All @@ -204,7 +145,15 @@ def test_write_footer():

def test_write_hveto_page(tmpdir):
os.chdir(str(tmpdir))
html.write_hveto_page('L1', 0, 86400, [], [])
config = 'test.ini'
with open(config, 'w') as fobj:
fobj.write('[test]\nchannel = X1:TEST')
htmlv = {
'title': 'test',
'base': 'test',
'config': config,
}
html.write_hveto_page('L1', 0, 86400, [], [], **htmlv)
shutil.rmtree(str(tmpdir), ignore_errors=True)


Expand Down
13 changes: 0 additions & 13 deletions hveto/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,3 @@ def test_drop_plot(num):

with tempfile.NamedTemporaryFile(suffix='.svg') as svg:
plot.significance_drop(svg.name, old, new)


def test_fancy_plot():
# create a dummy FancyPlot instance
test = plot.FancyPlot('test.png')
assert test.img is 'test.png'
assert test.caption is 'test.png'

# check that its properties are unchanged when the argument
# to FancyPlot() is also a FancyPlot instance
test = plot.FancyPlot(test)
assert test.img is 'test.png'
assert test.caption is 'test.png'
Loading

0 comments on commit 1221312

Please sign in to comment.