Add unit tests for pipeline layout, routing and SVG drawing
This commit is contained in:
1 parent
5146111ad5
commit
c916ed89b5
1 file changed
+310
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
# Needed to include from ../OpenBench/pipeline_layout.py, which has no Django dependencies
|
||||
PARENT = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir)
|
||||
sys.path.insert(0, os.path.abspath(PARENT))
|
||||
|
||||
from OpenBench.pipeline_layout import *
|
||||
|
||||
def step(name=None, **payload):
|
||||
base = { 'test_mode' : 'SPRT', 'test_bounds' : '[0.00, 2.00]', 'dev_time_control' : '8.0+0.08' }
|
||||
base.update(payload)
|
||||
return { 'name' : name, 'kind' : 'TEST', 'payload' : base }
|
||||
|
||||
def build(start, names, *edges):
|
||||
|
||||
""" build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')) """
|
||||
|
||||
return {
|
||||
'version' : 1, 'start' : start,
|
||||
'steps' : { key : step(key.upper()) for key in names },
|
||||
'edges' : [{ 'from' : s, 'on' : on, 'to' : t } for s, on, t in edges],
|
||||
}
|
||||
|
||||
SHAPES = {
|
||||
'chain' : build('a', 'abc', ('a', 'passed', 'b'), ('b', 'passed', 'c')),
|
||||
'fork' : build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')),
|
||||
'diamond' : build('a', 'abcd', ('a', 'passed', 'b'), ('a', 'failed', 'c'), ('b', 'any', 'd'), ('c', 'any', 'd')),
|
||||
'skip' : build('a', 'abc', ('a', 'passed', 'b'), ('b', 'passed', 'c'), ('a', 'failed', 'c')),
|
||||
'retry' : build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'a'), ('b', 'failed', 'a')),
|
||||
'wide' : build('a', 'abcdef', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'), ('a', 'any', 'e'), ('a', 'any', 'f')),
|
||||
'orphans' : build('a', 'abc', ('a', 'passed', 'b')),
|
||||
'ended' : build('a', 'ab', ('a', 'passed', 'b'), ('a', 'failed', None), ('b', 'any', None)),
|
||||
'single' : build('a', 'a'),
|
||||
'wordy' : dict(build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')),
|
||||
edges=[{ 'from' : 'a', 'on' : 'passed', 'to' : 'b', 'set' : { 'priority' : '1', 'test_bounds' : 'x', 'throughput' : '2' } },
|
||||
{ 'from' : 'a', 'on' : 'stopped', 'to' : 'c', 'set' : { k : '1' for k in ('dev_bench', 'base_bench', 'priority', 'throughput', 'book_name', 'upload_pgns', 'dev_options', 'base_options', 'dev_network', 'base_network') } }]),
|
||||
'two skips': build('a', 'abcd', ('a', 'passed', 'b'), ('b', 'passed', 'c'), ('c', 'passed', 'd'),
|
||||
('a', 'failed', 'c'), ('a', 'stopped', 'd')),
|
||||
'loop top' : build('a', 'abcd', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'), ('b', 'failed', 'a')),
|
||||
'tall' : build('a', 'abcdef', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'),
|
||||
('b', 'passed', 'e'), ('e', 'passed', 'f'), ('a', 'stopped', 'f'), ('d', 'failed', 'a')),
|
||||
}
|
||||
|
||||
def overlap(a, b):
|
||||
return not (a['x'] + a['w'] <= b['x'] or b['x'] + b['w'] <= a['x'] or
|
||||
a['y'] + a['h'] <= b['y'] or b['y'] + b['h'] <= a['y'])
|
||||
|
||||
class LayoutTests(unittest.TestCase):
|
||||
|
||||
def test_columns_follow_the_flow(self):
|
||||
nodes = layout(SHAPES['fork'])['nodes']
|
||||
self.assertEqual([nodes[k]['layer'] for k in 'abc'], [0, 1, 1])
|
||||
self.assertEqual(sorted((nodes['b']['row'], nodes['c']['row'])), [0, 1])
|
||||
|
||||
def test_a_step_sits_after_the_furthest_step_leading_into_it(self):
|
||||
self.assertEqual(layout(SHAPES['diamond'])['nodes']['d']['layer'], 2)
|
||||
self.assertEqual(layout(SHAPES['skip'])['nodes']['c']['layer'], 2) # Not 1, although a leads to it
|
||||
|
||||
def test_loops_do_not_push_steps_to_the_right(self):
|
||||
nodes = layout(SHAPES['retry'])['nodes']
|
||||
self.assertEqual((nodes['a']['layer'], nodes['b']['layer']), (0, 1))
|
||||
|
||||
def test_loop_edges_are_marked_and_dip_below_the_steps(self):
|
||||
|
||||
geometry = layout(SHAPES['retry'])
|
||||
loops = [e for e in geometry['edges'] if e['back']]
|
||||
|
||||
self.assertEqual(sorted(e['source'] for e in loops), ['a', 'b'])
|
||||
bottom = max(n['y'] + n['h'] for n in geometry['nodes'].values())
|
||||
for loop in loops:
|
||||
self.assertGreater(loop['ly'], bottom)
|
||||
self.assertGreater(geometry['height'], bottom + 30) # Room was made for them
|
||||
|
||||
def test_a_loop_onto_itself_is_a_loop(self):
|
||||
edge = [e for e in layout(SHAPES['retry'])['edges'] if e['source'] == e['target']]
|
||||
self.assertEqual(len(edge), 1); self.assertTrue(edge[0]['back'])
|
||||
|
||||
def test_steps_that_can_never_start_go_last_and_are_flagged(self):
|
||||
nodes = layout(SHAPES['orphans'])['nodes']
|
||||
self.assertTrue(nodes['a']['reachable'] and nodes['b']['reachable'])
|
||||
self.assertFalse(nodes['c']['reachable'])
|
||||
self.assertGreater(nodes['c']['layer'], nodes['b']['layer'])
|
||||
|
||||
def test_edges_leaving_one_step_use_different_ports(self):
|
||||
edges = layout(SHAPES['wide'])['edges']
|
||||
starts = [float(e['path'].split()[1]) for e in edges]
|
||||
self.assertEqual(len(set(starts)), len(starts))
|
||||
|
||||
def test_an_edge_to_nowhere_is_a_short_stub(self):
|
||||
ends = [e for e in layout(SHAPES['ended'])['edges'] if e['end']]
|
||||
self.assertEqual(len(ends), 2)
|
||||
self.assertTrue(all('ex' in e and e['ex'] > 0 for e in ends))
|
||||
|
||||
def test_the_stub_of_an_edge_to_nowhere_is_longer_than_its_label(self):
|
||||
for edge in [e for e in layout(SHAPES['ended'])['edges'] if e['end']]:
|
||||
self.assertGreaterEqual(edge['length'], label_width(edge_label(edge['on'], edge['changes'])) + 30)
|
||||
|
||||
def test_edges_pointing_at_missing_steps_are_skipped_not_fatal(self):
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['edges'].append({ 'from' : 'a', 'on' : 'failed', 'to' : 'ghost' })
|
||||
graph['edges'].append({ 'from' : 'ghost', 'on' : 'failed', 'to' : 'a' })
|
||||
self.assertEqual(len(layout(graph)['edges']), 1)
|
||||
|
||||
def test_nothing_overlaps_and_everything_fits_in_every_shape(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
nodes = list(geometry['nodes'].values())
|
||||
|
||||
for i, a in enumerate(nodes):
|
||||
self.assertGreaterEqual(a['x'], 0, name); self.assertGreaterEqual(a['y'], 0, name)
|
||||
self.assertLessEqual(a['x'] + a['w'], geometry['width'], name)
|
||||
self.assertLessEqual(a['y'] + a['h'], geometry['height'], name)
|
||||
for b in nodes[i + 1:]:
|
||||
self.assertFalse(overlap(a, b), '%s: %s overlaps %s' % (name, a['id'], b['id']))
|
||||
|
||||
def test_layout_is_deterministic(self):
|
||||
for graph in SHAPES.values():
|
||||
self.assertEqual(layout(graph), layout(graph))
|
||||
|
||||
def points(path, steps=40):
|
||||
|
||||
""" Points along an edge, from its SVG path ( only M, L and C are ever used ) """
|
||||
|
||||
tokens = re.findall(r'[MLC]|-?\d+\.?\d*', path)
|
||||
found, here, i = [], None, 0
|
||||
|
||||
while i < len(tokens):
|
||||
command = tokens[i]; i += 1
|
||||
count = 6 if command == 'C' else 2
|
||||
numbers = [float(n) for n in tokens[i:i + count]]; i += count
|
||||
|
||||
if command == 'M':
|
||||
here = (numbers[0], numbers[1])
|
||||
elif command == 'L':
|
||||
for k in range(steps + 1):
|
||||
found.append((here[0] + (numbers[0] - here[0]) * k / steps, here[1] + (numbers[1] - here[1]) * k / steps))
|
||||
here = (numbers[0], numbers[1])
|
||||
else:
|
||||
(x0, y0), (x1, y1, x2, y2, x3, y3) = here, numbers
|
||||
for k in range(steps + 1):
|
||||
u = k / steps; v = 1 - u
|
||||
found.append((v**3 * x0 + 3 * v * v * u * x1 + 3 * v * u * u * x2 + u**3 * x3,
|
||||
v**3 * y0 + 3 * v * v * u * y1 + 3 * v * u * u * y2 + u**3 * y3))
|
||||
here = (x3, y3)
|
||||
|
||||
return found
|
||||
|
||||
def inside(point, node, margin=1.5):
|
||||
return (node['x'] + margin < point[0] < node['x'] + node['w'] - margin and
|
||||
node['y'] + margin < point[1] < node['y'] + node['h'] - margin)
|
||||
|
||||
class RoutingTests(unittest.TestCase):
|
||||
|
||||
def test_no_forward_edge_runs_through_a_step_that_is_not_its_own(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
for edge in geometry['edges']:
|
||||
|
||||
if edge['back'] or edge['end']:
|
||||
continue # Loops run under the steps, and say so below
|
||||
|
||||
others = [n for k, n in geometry['nodes'].items() if k not in (edge['source'], edge['target'])]
|
||||
for point in points(edge['path']):
|
||||
for node in others:
|
||||
self.assertFalse(inside(point, node), '%s: edge %d cuts through %s at %s' % (name, edge['index'], node['id'], point))
|
||||
|
||||
def test_an_edge_that_skips_a_column_runs_above_the_steps_in_between(self):
|
||||
|
||||
geometry = layout(SHAPES['skip'])
|
||||
skipper = [e for e in geometry['edges'] if e['source'] == 'a' and e['target'] == 'c'][0]
|
||||
between = geometry['nodes']['b']
|
||||
|
||||
self.assertLess(skipper['ly'], between['y'])
|
||||
self.assertGreaterEqual(skipper['ly'], 0)
|
||||
|
||||
def test_every_label_fits_in_the_gap_that_it_sits_in(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
|
||||
for edge in geometry['edges']:
|
||||
if edge['back'] or edge['end'] or geometry['nodes'][edge['target']]['layer'] - geometry['nodes'][edge['source']]['layer'] != 1:
|
||||
continue
|
||||
|
||||
width = label_width(edge_label(edge['on'], edge['changes']))
|
||||
right = geometry['nodes'][edge['source']]['x'] + NODE_W
|
||||
left = geometry['nodes'][edge['target']]['x']
|
||||
|
||||
self.assertGreaterEqual(edge['lx'] - width / 2, right, '%s: label sticks into the step before it' % (name))
|
||||
self.assertLessEqual(edge['lx'] + width / 2, left, '%s: label sticks into the step after it' % (name))
|
||||
|
||||
def test_every_edge_stays_on_the_canvas(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
for edge in geometry['edges']:
|
||||
for x, y in points(edge['path']):
|
||||
self.assertTrue(-1 <= x <= geometry['width'] + 1 and -1 <= y <= geometry['height'] + 1, '%s: edge %d at %s' % (name, edge['index'], (x, y)))
|
||||
|
||||
def test_loops_run_under_every_step_not_just_their_own(self):
|
||||
|
||||
for name in ('retry', 'tall', 'loop top'):
|
||||
geometry = layout(SHAPES[name])
|
||||
lowest = max(n['y'] + n['h'] for n in geometry['nodes'].values())
|
||||
|
||||
for edge in [e for e in geometry['edges'] if e['back']]:
|
||||
self.assertGreater(edge['ly'], lowest, name)
|
||||
|
||||
def test_the_lines_inside_a_step_do_not_share_a_row_with_the_name(self):
|
||||
|
||||
root = ET.fromstring(render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'runs' : 2 } }))
|
||||
ys = { t.get('class') : float(t.get('y')) for t in root.iter('{http://www.w3.org/2000/svg}text') if t.get('class') }
|
||||
|
||||
self.assertLess(ys['pl-name'], ys['pl-what']); self.assertLess(ys['pl-what'], ys['pl-speed'])
|
||||
self.assertEqual(ys['pl-speed'], ys['pl-status']) # Sharing the last row, on opposite sides
|
||||
|
||||
class DrawingTests(unittest.TestCase):
|
||||
|
||||
def parse(self, svg):
|
||||
return ET.fromstring(svg) # Raises if the markup is not well formed
|
||||
|
||||
def texts(self, root):
|
||||
return [''.join(t.itertext()) for t in root.iter('{http://www.w3.org/2000/svg}text')]
|
||||
|
||||
def test_every_shape_draws_well_formed_svg(self):
|
||||
for name, graph in SHAPES.items():
|
||||
root = self.parse(render_svg(graph))
|
||||
self.assertEqual(root.tag, '{http://www.w3.org/2000/svg}svg', name)
|
||||
|
||||
def test_step_names_and_conditions_are_drawn(self):
|
||||
texts = self.texts(self.parse(render_svg(SHAPES['fork'])))
|
||||
for wanted in ('A', 'B', 'C', 'passed', 'failed'):
|
||||
self.assertIn(wanted, texts)
|
||||
|
||||
def test_names_cannot_inject_markup(self):
|
||||
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['steps']['a']['name'] = '<script>alert(1)</script>'
|
||||
graph['steps']['b']['name'] = '"><img src=x onerror=alert(2)>'
|
||||
graph['steps']['b']['payload']['test_bounds'] = '</text><script>alert(3)</script>'
|
||||
graph['edges'][0]['set'] = { 'priority' : '"><script>alert(4)</script>' }
|
||||
|
||||
svg = render_svg(graph)
|
||||
root = self.parse(svg)
|
||||
|
||||
self.assertNotIn('<script', svg); self.assertNotIn('<img', svg)
|
||||
self.assertEqual([e.tag for e in root.iter() if 'script' in e.tag or 'img' in e.tag], [])
|
||||
self.assertTrue(any(t.startswith('<script>alert(1)') for t in self.texts(root))) # Shown as text, not run
|
||||
|
||||
def test_ids_cannot_break_out_of_attributes(self):
|
||||
graph = build('a', 'a')
|
||||
graph['steps']['x"onload="alert(1)'] = step('X')
|
||||
root = self.parse(render_svg(graph))
|
||||
for element in root.iter():
|
||||
self.assertNotIn('onload', element.attrib)
|
||||
|
||||
def test_state_decides_the_look(self):
|
||||
svg = render_svg(SHAPES['fork'], states={
|
||||
'a' : { 'status' : 'PASSED' }, 'b' : { 'status' : 'running', 'runs' : 2 }, 'c' : { 'status' : 'nonsense' } })
|
||||
root = self.parse(svg)
|
||||
classes = { g.get('data-step') : g.get('class') for g in root.iter('{http://www.w3.org/2000/svg}g') if g.get('data-step') }
|
||||
self.assertIn('pl-s-passed', classes['a']); self.assertIn('pl-s-running', classes['b'])
|
||||
self.assertIn('pl-s-idle', classes['c']) # Unknown status never becomes a class
|
||||
self.assertIn('running x2', self.texts(root))
|
||||
|
||||
def test_followed_edges_stand_out(self):
|
||||
root = self.parse(render_svg(SHAPES['fork'], taken={ 0 }))
|
||||
classes = { g.get('data-edge') : g.get('class') for g in root.iter('{http://www.w3.org/2000/svg}g') if g.get('data-edge') }
|
||||
self.assertIn('pl-taken', classes['0']); self.assertIn('pl-idle', classes['1'])
|
||||
|
||||
def test_without_a_run_no_edge_is_quiet(self):
|
||||
svg = render_svg(SHAPES['fork'])
|
||||
self.assertNotIn('pl-idle', svg); self.assertNotIn('pl-taken', svg)
|
||||
|
||||
def test_links_must_be_paths_on_this_site(self):
|
||||
|
||||
for bad in ('http://evil.example/', '//evil.example/', 'javascript:alert(1)', ''):
|
||||
self.assertNotIn('<a ', render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'url' : bad } }), bad)
|
||||
|
||||
good = render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'url' : '/test/12/' } })
|
||||
self.assertIn('<a href="/test/12/">', good)
|
||||
|
||||
def test_edge_changes_are_counted_and_listed(self):
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['edges'][0]['set'] = { 'priority' : '5', 'test_bounds' : '[0.00, 5.00]' }
|
||||
svg = render_svg(graph)
|
||||
self.assertIn('passed (2 changes)', svg); self.assertIn('priority = 5', svg)
|
||||
|
||||
def test_summaries(self):
|
||||
self.assertEqual(step_summary(step()), ('SPRT [0.00, 2.00]', '8.0+0.08'))
|
||||
self.assertEqual(step_summary(step(test_mode='GAMES', test_max_games='40000')), ('40000 games', '8.0+0.08'))
|
||||
self.assertEqual(step_summary({ 'kind' : 'TUNE', 'payload' : { 'spsa_iterations' : '500' } })[0], 'SPSA, 500 iterations')
|
||||
self.assertEqual(step_summary({ 'kind' : 'DATAGEN', 'payload' : { 'datagen_max_games' : '9' } })[0], '9 games')
|
||||
self.assertEqual(step_summary({}), ('', ''))
|
||||
|
||||
def test_long_text_is_clipped(self):
|
||||
graph = build('a', 'a'); graph['steps']['a']['name'] = 'x' * 80
|
||||
name = [t for t in self.texts(self.parse(render_svg(graph))) if t.startswith('x')][0]
|
||||
self.assertEqual(len(name), NAME_LIMIT); self.assertTrue(name.endswith('\u2026'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user