Code indexing in gitaly is broken and leads to code not being visible to the user. We work on the issue with highest priority.

Skip to content
Snippets Groups Projects
Commit d528a33b authored by ext-rogers_c's avatar ext-rogers_c
Browse files

Use pylint static code analyzer on the tests

parent 17e02224
No related branches found
No related tags found
1 merge request!579Resolve "OpalElement wrapper"
Showing
with 182 additions and 134 deletions
import math """Test LocalCartesianOffset python implementation"""
import unittest import unittest
import pyopal.elements.local_cartesian_offset import pyopal.elements.local_cartesian_offset
"""
Test LocalCartesianOffset python implementation
"""
class LocalCartesianOffsetTest(unittest.TestCase): class LocalCartesianOffsetTest(unittest.TestCase):
"""Tests for LocalCartesianOffset"""
def test_init(self): def test_init(self):
"""Check that we can build an offset okay""" """Check that we can build an offset okay"""
offset = pyopal.elements.local_cartesian_offset.LocalCartesianOffset() offset = pyopal.elements.local_cartesian_offset.LocalCartesianOffset()
offset.end_position_x = 1.0 offset.end_position_x = 1.0
self.assertEqual(offset.end_position_x, 1.0) self.assertEqual(offset.end_position_x, 1.0)
offset.end_position_y = 2.0 offset.end_position_y = 2.0
self.assertEqual(offset.end_position_y, 2.0) self.assertEqual(offset.end_position_y, 2.0)
offset.end_normal_x = 3.0 offset.end_normal_x = 3.0
self.assertEqual(offset.end_normal_x, 3.0) self.assertEqual(offset.end_normal_x, 3.0)
offset.end_normal_y = 4.0 offset.end_normal_y = 4.0
self.assertEqual(offset.end_normal_y, 4.0) self.assertEqual(offset.end_normal_y, 4.0)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
import math """Test RingDefinition python implementation"""
import unittest import unittest
import pyopal.elements.ring_definition import pyopal.elements.ring_definition
"""
Test RingDefinition python implementation
"""
class RingDefinitionTest(unittest.TestCase): class RingDefinitionTest(unittest.TestCase):
"""Test RingDefinition python implementation"""
def setUp(self): def setUp(self):
"""setup the ring""" """setup the ring"""
self.ring_definition = pyopal.elements.ring_definition.RingDefinition() self.ring_definition = pyopal.elements.ring_definition.RingDefinition()
......
import math
import unittest
import pyopal.elements.vertical_ffa_magnet
""" """
Test VerticalFFAMagnet python implementation Test VerticalFFAMagnet python implementation
""" """
import math
import unittest
import pyopal.elements.vertical_ffa_magnet
class VerticalFFAMagnetTest(unittest.TestCase): class VerticalFFAMagnetTest(unittest.TestCase):
"""Test VerticalFFAMagnet"""
def setUp(self): def setUp(self):
"""Set some default magnet"""
self.magnet = pyopal.elements.vertical_ffa_magnet.VerticalFFAMagnet() self.magnet = pyopal.elements.vertical_ffa_magnet.VerticalFFAMagnet()
self.magnet.b0 = 4.0 self.magnet.b0 = 4.0
self.magnet.field_index = 2.0 self.magnet.field_index = 2.0
...@@ -42,16 +44,16 @@ class VerticalFFAMagnetTest(unittest.TestCase): ...@@ -42,16 +44,16 @@ class VerticalFFAMagnetTest(unittest.TestCase):
def test_bounding_box(self): def test_bounding_box(self):
"""Check that we can set up the bounding box okay""" """Check that we can set up the bounding box okay"""
for point in [(0.0, 0.0, -0.01, 0.0), (0.0, 0.0, 10.01, 0.0), for point in [(0.0, 0.0, -0.01, 0.0), (0.0, 0.0, 10.01, 0.0),
(0.0, -2.01, 5.0, 0.0), (0.0, 6.01, 5.0, 0.0), (0.0, -2.01, 5.0, 0.0), (0.0, 6.01, 5.0, 0.0),
(-0.51, 5.0, 0.0, 0.0), (0.51, 5.0, 0.0, 0.0), ]: (-0.51, 5.0, 0.0, 0.0), (0.51, 5.0, 0.0, 0.0),]:
value = self.magnet.get_field_value(*point) value = self.magnet.get_field_value(*point)
self.assertTrue(value[0], msg="{0} {1}".format(point, value)) self.assertTrue(value[0], msg=f"{point} {value}")
for point in [(0.0, 0.0, 0.01, 0.0), (0.0, 0.0, 9.99, 0.0), for point in [(0.0, 0.0, 0.01, 0.0), (0.0, 0.0, 9.99, 0.0),
(0.0, -1.99, 5.0, 0.0), (0.0, 5.99, 5.0, 0.0), (0.0, -1.99, 5.0, 0.0), (0.0, 5.99, 5.0, 0.0),
(-0.49, 5.0, 0.0, 0.0), (0.49, 5.0, 0.0, 0.0), ]: (-0.49, 5.0, 0.0, 0.0), (0.49, 5.0, 0.0, 0.0),]:
value = self.magnet.get_field_value(*point) value = self.magnet.get_field_value(*point)
self.assertFalse(value[0], msg="{0} {1}".format(point, value)) self.assertFalse(value[0], msg=f"{point} {value}")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
"""Check that beam can be set up okay"""
import unittest import unittest
import pyopal.objects.beam import pyopal.objects.beam
class TestBeam(unittest.TestCase): class TestBeam(unittest.TestCase):
"""Very light beam test class"""
def test_init(self): def test_init(self):
my_beam = pyopal.objects.beam.Beam() my_beam = pyopal.objects.beam.Beam()
my_beam.particle = "proton" my_beam.particle = "proton"
...@@ -24,11 +27,13 @@ class TestBeam(unittest.TestCase): ...@@ -24,11 +27,13 @@ class TestBeam(unittest.TestCase):
self.assertAlmostEqual(my_beam.number_of_particles, 8) self.assertAlmostEqual(my_beam.number_of_particles, 8)
def test_bad_particle_type(self): def test_bad_particle_type(self):
"""See what happens if we set a bad particle type"""
my_beam = pyopal.objects.beam.Beam() my_beam = pyopal.objects.beam.Beam()
my_beam.particle = "bad" my_beam.particle = "bad"
self.assertTrue(False, """"Should have thrown.""") # would not be terrible if this threw exception
def test_register(self): def test_register(self):
"""Check we can register the beam okay"""
my_beam = pyopal.objects.beam.Beam() my_beam = pyopal.objects.beam.Beam()
my_beam.register() my_beam.register()
......
"""Test that distribution parses okay"""
import unittest import unittest
import pyopal.objects.distribution import pyopal.objects.distribution
class TestDistribution(unittest.TestCase): class TestDistribution(unittest.TestCase):
"""Test that distribution parses okay"""
def test_init(self): def test_init(self):
"""Check we can initialise variables without a problem""" """Check we can initialise variables without a problem"""
my_distribution = pyopal.objects.distribution.Distribution() my_distribution = pyopal.objects.distribution.Distribution()
......
"""Test the field module"""
import unittest import unittest
import tempfile import tempfile
import sys import sys
...@@ -6,14 +7,16 @@ import pyopal.objects.parser ...@@ -6,14 +7,16 @@ import pyopal.objects.parser
import pyopal.objects.field import pyopal.objects.field
def run_encapsulated_test(file_name): def run_encapsulated_test(file_name):
"""Run the test in a subfile so that we don't get namespace clashes"""
pyopal.objects.parser.initialise_from_opal_file(file_name) pyopal.objects.parser.initialise_from_opal_file(file_name)
print("Testing") print("Testing")
value = pyopal.objects.field.get_field_value(0, 1, 0, 0) value = pyopal.objects.field.get_field_value(0, 1, 0, 0)
print(value) print(value)
return_code = abs(value[3]-2) > 1e-3 my_return_code = abs(value[3]-2) > 1e-3
return return_code return my_return_code
class FieldTest(unittest.TestCase): class FieldTest(unittest.TestCase):
"""Test that we can get fields out"""
def make_temp(self, a_string): def make_temp(self, a_string):
"""Dump string to a temporary file for use in testing""" """Dump string to a temporary file for use in testing"""
my_temp = tempfile.NamedTemporaryFile(mode='w+') my_temp = tempfile.NamedTemporaryFile(mode='w+')
...@@ -31,7 +34,7 @@ class FieldTest(unittest.TestCase): ...@@ -31,7 +34,7 @@ class FieldTest(unittest.TestCase):
temp_stdout = tempfile.TemporaryFile() temp_stdout = tempfile.TemporaryFile()
temp_stderr = subprocess.STDOUT temp_stderr = subprocess.STDOUT
proc = subprocess.run(["python3", __file__, "run_unit_test_encapsulation", temp_file.name], proc = subprocess.run(["python3", __file__, "run_unit_test_encapsulation", temp_file.name],
stdout=temp_stdout, stderr=temp_stderr) stdout=temp_stdout, stderr=temp_stderr, check=False)
if temp_stdout: if temp_stdout:
temp_stdout.close() # why does this not use resource allocation? temp_stdout.close() # why does this not use resource allocation?
self.assertEqual(proc.returncode, 0) self.assertEqual(proc.returncode, 0)
......
"""Test the Field Solver"""
import unittest import unittest
import pyopal.objects.field_solver import pyopal.objects.field_solver
class TestFieldSolver(unittest.TestCase): class TestFieldSolver(unittest.TestCase):
"""Test the Field Solver"""
def setUp(self): def setUp(self):
"""Set up some data""" """Set up some data"""
self.fs = pyopal.objects.field_solver.FieldSolver() self.fs = pyopal.objects.field_solver.FieldSolver()
...@@ -65,6 +68,7 @@ class TestFieldSolver(unittest.TestCase): ...@@ -65,6 +68,7 @@ class TestFieldSolver(unittest.TestCase):
def test_register(self): def test_register(self):
"""Check we can register the beam""" """Check we can register the beam"""
my_beam = pyopal.objects.field_solver.FieldSolver() my_beam = pyopal.objects.field_solver.FieldSolver()
my_beam.type = "None"
my_beam.register() my_beam.register()
......
"""Test Line implementation"""
# we are testing the dunder operator, hence disable pylint warning
# pylint: disable=unnecessary-dunder-call
import unittest import unittest
import pyopal.elements.vertical_ffa_magnet import pyopal.elements.vertical_ffa_magnet
import pyopal.objects.line import pyopal.objects.line
class TestLine(unittest.TestCase): class TestLine(unittest.TestCase):
"""Test Line implementation"""
def setUp(self): def setUp(self):
"""Define a few default variables""" """Define a few default variables"""
self.magnet1 = pyopal.elements.vertical_ffa_magnet.VerticalFFAMagnet() self.magnet1 = pyopal.elements.vertical_ffa_magnet.VerticalFFAMagnet()
...@@ -40,12 +46,9 @@ class TestLine(unittest.TestCase): ...@@ -40,12 +46,9 @@ class TestLine(unittest.TestCase):
self.assertEqual(self.line[1], self.magnet2) self.assertEqual(self.line[1], self.magnet2)
self.line.append(self.magnet1) self.line.append(self.magnet1)
self.assertEqual(self.line[2], self.magnet1) self.assertEqual(self.line[2], self.magnet1)
try: with self.assertRaises(AttributeError):
self.line.append("not an element") self.line.append("not an element")
self.assertTrue(False, "Should have thrown")
except AttributeError:
pass
def test_set(self): def test_set(self):
"""Check that we can set elements""" """Check that we can set elements"""
self.line.append(self.magnet1) self.line.append(self.magnet1)
...@@ -60,35 +63,23 @@ class TestLine(unittest.TestCase): ...@@ -60,35 +63,23 @@ class TestLine(unittest.TestCase):
self.assertEqual(self.line[1], self.magnet1) self.assertEqual(self.line[1], self.magnet1)
self.line.__setitem__(-2, self.magnet2) self.line.__setitem__(-2, self.magnet2)
self.assertEqual(self.line[0], self.magnet2) self.assertEqual(self.line[0], self.magnet2)
try: with self.assertRaises(AttributeError):
self.line[1] = "not an element" self.line[1] = "not an element"
self.assertTrue(False, "Should have thrown") with self.assertRaises(RuntimeError):
except AttributeError:
pass
try:
self.line.__setitem__(2, self.magnet2) self.line.__setitem__(2, self.magnet2)
self.assertTrue(False, "Should have thrown")
except RuntimeError:
pass
def test_get(self): def test_get(self):
"""Check that we can get elements""" """Check that we can get elements"""
try: with self.assertRaises(RuntimeError):
self.line[0] self.line[0]
self.assertTrue(False, "Should have thrown")
except RuntimeError:
pass
self.line.append(self.magnet1) self.line.append(self.magnet1)
self.line.append(self.magnet2) self.line.append(self.magnet2)
self.assertEqual(self.line.__getitem__(0), self.magnet1) self.assertEqual(self.line.__getitem__(0), self.magnet1)
self.assertEqual(self.line.__getitem__(1), self.magnet2) self.assertEqual(self.line.__getitem__(1), self.magnet2)
self.assertEqual(self.line.__getitem__(-1), self.magnet2) self.assertEqual(self.line.__getitem__(-1), self.magnet2)
self.assertEqual(self.line.__getitem__(-2), self.magnet1) self.assertEqual(self.line.__getitem__(-2), self.magnet1)
try: with self.assertRaises(RuntimeError):
self.line.__getitem__(3) self.line.__getitem__(3)
self.assertTrue(False, "Should have thrown")
except RuntimeError:
pass
def test_len(self): def test_len(self):
"""Check len function""" """Check len function"""
...@@ -98,4 +89,4 @@ class TestLine(unittest.TestCase): ...@@ -98,4 +89,4 @@ class TestLine(unittest.TestCase):
self.assertEqual(len(self.line), 2) self.assertEqual(len(self.line), 2)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
\ No newline at end of file
import unittest import unittest
import tempfile import tempfile
import subprocess import subprocess
import pyopal.objects.parser
import pyopal.objects.beam
class ParserTest(unittest.TestCase): class ParserTest(unittest.TestCase):
def make_temp(self, a_string): def make_temp(self, a_string):
...@@ -12,37 +10,26 @@ class ParserTest(unittest.TestCase): ...@@ -12,37 +10,26 @@ class ParserTest(unittest.TestCase):
my_temp.flush() my_temp.flush()
return my_temp return my_temp
def encapsulate_parser_in_subprocess(self, file_name): def encapsulate_parser_in_subprocess(self):
"""OPAL can kill python execution so we hide the test in a subprocess""" """OPAL can kill python execution so we hide the test in a subprocess"""
temp_file = self.make_temp(self.good_lattice) temp_file = self.make_temp(self.good_lattice)
temp_stdout = tempfile.TemporaryFile() temp_stdout = tempfile.TemporaryFile()
proc = subprocess.run(["python3", proc = subprocess.run(["python3",
"-c", self.command+"'"+temp_file.name+"')"], "-c", self.command+"'"+temp_file.name+"')"],
stdout=temp_stdout, stderr=subprocess.STDOUT) stdout=temp_stdout, stderr=subprocess.STDOUT, check=False)
temp_stdout.seek(0) if proc.returncode != 0:
for line in temp_stdout: temp_stdout.seek(0)
print(line[:-1]) for line in temp_stdout:
print(line[:-1])
temp_stdout.close() temp_stdout.close()
temp_file.close() temp_file.close()
return proc.returncode return proc.returncode
def test_parser_initialise(self): def test_parser_initialise(self):
"""Test that we can initialise some dummy lattice""" """Test that we can initialise some dummy lattice"""
is_error = self.encapsulate_parser_in_subprocess(self.good_lattice) is_error = self.encapsulate_parser_in_subprocess()
self.assertFalse(is_error) self.assertFalse(is_error)
def test_list_objects(self):
"""Test that we can initialise some dummy lattice"""
my_objects = pyopal.objects.parser.list_objects()
self.assertEqual(len(my_objects), 0)
print("MY OBJECTS", my_objects)
beam = pyopal.objects.beam.Beam()
beam.name = "FISH"
beam.register()
self.assertEqual(len(my_objects), 1)
self.assertEqual(my_objects[0], "FISH")
command = """ command = """
import pyopal.objects.parser import pyopal.objects.parser
pyopal.objects.parser.initialise_from_opal_file( pyopal.objects.parser.initialise_from_opal_file(
......
"""Test the track module"""
import unittest import unittest
import pyopal.objects.line
import pyopal.objects.beam
import pyopal.objects.track import pyopal.objects.track
class TestTrack(unittest.TestCase): class TestTrack(unittest.TestCase):
"""Quick check that we can run track okay"""
def setUp(self): def setUp(self):
"""Set up some data""" """Set up some data"""
self.track = pyopal.objects.track.Track() self.track = pyopal.objects.track.Track()
def test_init(self): def test_init(self):
"""Check I didn't make any typos""" """Check I didn't make any typos"""
pass self.track.line = "test_line"
self.track.beam = "test_beam"
self.track.dt = 1.0
self.track.dt_space_charge = 2.0
self.track.dtau = 3.0
self.track.t0 = 4.0
self.track.max_steps = [5]
self.track.steps_per_turn = 6.0
self.track.z_start = 7.0
self.track.z_stop = [8.0]
self.track.time_integrator = "integrator"
self.track.map_order = 9
def test_execute(self): def test_execute(self):
"""Check we can register the beam""" """Check we can register the beam"""
beam = pyopal.objects.beam.Beam()
beam.set_opal_name("test_track::beam")
beam.register()
line = pyopal.objects.line.Line()
line.register()
#line.set_opal_name("test_track::line") does not work
self.track.beam = "test_track::beam"
self.track.line = "LINE" # all lines are called LINE
self.track.execute() self.track.execute()
......
"""Module to test track run (and by extension the entire PyOpal workflow)"""
import os import os
import unittest import sys
import tempfile import tempfile
import subprocess
import unittest
import pyopal.elements.vertical_ffa_magnet import pyopal.elements.vertical_ffa_magnet
import pyopal.objects.track_run import pyopal.objects.track_run
import pyopal.objects.beam import pyopal.objects.beam
...@@ -12,21 +17,24 @@ import pyopal.objects.field_solver ...@@ -12,21 +17,24 @@ import pyopal.objects.field_solver
import pyopal.objects.track import pyopal.objects.track
import pyopal.objects.parser import pyopal.objects.parser
DISTRIBUTION = """10 class TrackRunExecute():
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 """Module to test track run (and by extension the entire PyOpal workflow)"""
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 def __init__(self):
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 """Set up the test"""
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.here = os.getcwd()
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.tmp_dir = tempfile.TemporaryDirectory()
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 os.chdir(self.tmp_dir.name)
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.field_solver = None
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.line = None
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.ring = None
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252 self.offset = None
""" self.distribution = None
self.distribution_file = tempfile.NamedTemporaryFile("w+")
self.track_run = pyopal.objects.track_run.TrackRun()
class TestTrackRun(unittest.TestCase):
def make_field_solver(self): def make_field_solver(self):
"""Make an empty fieldsolver"""
self.field_solver = pyopal.objects.field_solver.FieldSolver() self.field_solver = pyopal.objects.field_solver.FieldSolver()
self.field_solver.type = "NONE" self.field_solver.type = "NONE"
self.field_solver.mesh_size_x = 5 self.field_solver.mesh_size_x = 5
...@@ -43,6 +51,7 @@ class TestTrackRun(unittest.TestCase): ...@@ -43,6 +51,7 @@ class TestTrackRun(unittest.TestCase):
@classmethod @classmethod
def make_drift(cls): def make_drift(cls):
"""Returns a drift of length 0"""
drift = pyopal.elements.local_cartesian_offset.LocalCartesianOffset() drift = pyopal.elements.local_cartesian_offset.LocalCartesianOffset()
drift.end_position_x=0.0 drift.end_position_x=0.0
drift.end_position_y=0.0 drift.end_position_y=0.0
...@@ -51,6 +60,7 @@ class TestTrackRun(unittest.TestCase): ...@@ -51,6 +60,7 @@ class TestTrackRun(unittest.TestCase):
return drift return drift
def make_line(self): def make_line(self):
"""Make a beamline, just consisting of a drift section"""
drift = self.make_drift() drift = self.make_drift()
self.line = pyopal.objects.line.Line() self.line = pyopal.objects.line.Line()
self.ring = pyopal.elements.ring_definition.RingDefinition() self.ring = pyopal.elements.ring_definition.RingDefinition()
...@@ -69,12 +79,11 @@ class TestTrackRun(unittest.TestCase): ...@@ -69,12 +79,11 @@ class TestTrackRun(unittest.TestCase):
self.line.register() self.line.register()
def make_distribution(self): def make_distribution(self):
global DISTRIBUTION """Make a distribution, from tempfile data"""
self.distribution_file = tempfile.NamedTemporaryFile("w+") self.distribution_file.write(self.distribution_str)
self.distribution_file.write(DISTRIBUTION)
self.distribution_file.flush() self.distribution_file.flush()
self.distribution = pyopal.objects.distribution.Distribution() self.distribution = pyopal.objects.distribution.Distribution()
self.distribution.set_name("SuperDist") self.distribution.set_opal_name("SuperDist")
self.distribution.type = "FROMFILE" self.distribution.type = "FROMFILE"
self.distribution.fname = self.distribution_file.name self.distribution.fname = self.distribution_file.name
self.distribution.register() self.distribution.register()
...@@ -82,40 +91,70 @@ class TestTrackRun(unittest.TestCase): ...@@ -82,40 +91,70 @@ class TestTrackRun(unittest.TestCase):
return self.distribution return self.distribution
def run_one(self): def run_one(self):
"""Set up and run a simulation"""
self.make_line()
self.make_distribution()
self.make_field_solver()
beam = pyopal.objects.beam.Beam() beam = pyopal.objects.beam.Beam()
beam.set_opal_name("SuperBeam")
beam.mass = 0.938272 beam.mass = 0.938272
beam.charge = 1.0 beam.charge = 1.0
beam.momentum = 0.1 beam.momentum = 0.1
beam.beam_frequency = 1.0 beam.beam_frequency = 1.0
beam.number_of_slices = 10 beam.number_of_slices = 10
beam.number_of_particles = 10 beam.number_of_particles = 1
beam.register() beam.register()
line = self.make_line()
field_solver = self.make_field_solver()
distribution = self.make_distribution()
track = pyopal.objects.track.Track() track = pyopal.objects.track.Track()
track.line = "LINE" track.line = "LINE"
track.beam = "BEAM" track.beam = "SuperBeam"
run = pyopal.objects.track_run.TrackRun() run = pyopal.objects.track_run.TrackRun()
run.method = "CYCLOTRON-T" run.method = "CYCLOTRON-T"
run.keep_alive = True run.keep_alive = True
run.beam_name = "BEAM" run.beam_name = "SuperBeam"
run.distribution = ["SuperDist"] run.distribution = ["SuperDist"]
run.field_solver = "FIELDSOLVER" run.field_solver = "FIELDSOLVER"
print(pyopal.objects.parser.list_objects()) track.execute()
run.execute()
track.execute() track.execute()
run.execute() run.execute()
def setUp(self): def __del__(self):
"""Define a few default variables""" """move back to the old cwd"""
self.track_run = pyopal.objects.track_run.TrackRun() os.chdir(self.here)
self.tmp_dir.cleanup()
self.distribution_file.close()
distribution_str = """1
3.944586177309523 -0.02776333011661966 0.0 -0.0049890385556281445 0.1584654928597547 -0.0016918209895814252
"""
class TestTrackRun(unittest.TestCase):
"""Test class for track_run"""
def test_run_one(self):
"""
Test that we can run okay without an exception.
If running from the command line, will spit out the OPAL log to screen
"""
log = tempfile.TemporaryFile("w+")
proc = subprocess.run(["python", __file__, "run_test_track_run"],
stdout=log, stderr=subprocess.STDOUT, check=False)
log.seek(0)
error_message=""
if self.verbose:
error_message = log.read()
log.close()
self.assertEqual(proc.returncode, 0, msg=error_message)
def test_initialisation(self): verbose = False
"""Test that we can set member data okay"""
self.run_one()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() if "run_test_track_run" in sys.argv:
\ No newline at end of file TrackRunExecute().run_one()
else:
TestTrackRun.verbose = True
unittest.main()
"""Module to drive pylint tests"""
import tempfile import tempfile
import os import os
import unittest import unittest
...@@ -5,7 +7,7 @@ import subprocess ...@@ -5,7 +7,7 @@ import subprocess
class PyLintTest(unittest.TestCase): class PyLintTest(unittest.TestCase):
""" """
Because there is no actual python code in PyOpal, we use a pylint run Because there is no actual python code in PyOpal, we use a pylint run
against the tests as a proxy for checking that code is reasonably pythonic against the tests as a proxy for checking that code is reasonably pythonic
Would be better not to - sometimes test code is (deliberately) not pythonic Would be better not to - sometimes test code is (deliberately) not pythonic
...@@ -16,17 +18,22 @@ class PyLintTest(unittest.TestCase): ...@@ -16,17 +18,22 @@ class PyLintTest(unittest.TestCase):
# need an environment variable to define OPAL test location - does this # need an environment variable to define OPAL test location - does this
# exist? # exist?
self.opal_test_path = "tests/opal_src/PyOpal/" self.opal_test_path = "tests/opal_src/PyOpal/"
self.pass_score = 8 self.pass_score = 8.0
self.disables = ["missing-module-docstring", "missing-class-docstring"]
self.pylint_cmd = ["pylint"] self.pylint_cmd = ["pylint"]
def run_pylint(self, dirpath, fname): def run_pylint(self, dirpath, fname):
"""Run pylint and fill the log tempfile""" """Run pylint and fill the log tempfile"""
dis_list = []
for disable_item in self.disables:
dis_list += ["--disable", disable_item]
full_path = os.path.join(dirpath, fname) full_path = os.path.join(dirpath, fname)
subprocess.run(self.pylint_cmd+[full_path], subprocess.run(self.pylint_cmd+dis_list+[full_path],
stdout=self.log, stderr=subprocess.STDOUT) stdout=self.log, stderr=subprocess.STDOUT)
def get_score_from_line(self, line): def get_score_from_line(self, line):
"""Extract the pylint score by scraping the text output"""
if "Your code has been rated at" not in line: if "Your code has been rated at" not in line:
return -1 return -1
score = line.split("rated at ")[1:] score = line.split("rated at ")[1:]
...@@ -35,6 +42,7 @@ class PyLintTest(unittest.TestCase): ...@@ -35,6 +42,7 @@ class PyLintTest(unittest.TestCase):
return score return score
def check_logfile(self): def check_logfile(self):
"""Read the log and look for errors"""
self.log.flush() self.log.flush()
self.log.seek(0) self.log.seek(0)
buffer = "" buffer = ""
...@@ -43,18 +51,19 @@ class PyLintTest(unittest.TestCase): ...@@ -43,18 +51,19 @@ class PyLintTest(unittest.TestCase):
score = self.get_score_from_line(line) score = self.get_score_from_line(line)
if score < 0: if score < 0:
continue continue
msg=""" msg=f"""
Failed static code analysis with output Failed static code analysis with output
{0} {buffer}
Score must be greater than {1} to pass. Try running pylint to check manually. Score must be greater than {self.pass_score} to pass. Try running pylint to check manually.
""".format(buffer, self.pass_score) """
self.assertGreater(score, self.pass_score, msg) self.assertGreater(score, self.pass_score, msg)
buffer = "" buffer = ""
def test_check_pylint(self): def test_check_pylint(self):
"""Recurse up the directory structure and run pyline on each .py file"""
for dirpath, dirnames, filenames in os.walk(top=self.opal_test_path): for dirpath, dirnames, filenames in os.walk(top=self.opal_test_path):
for fname in filenames: for fname in filenames:
if fname[-3:] != ".py": if fname[-3:] != ".py":
...@@ -63,21 +72,7 @@ Score must be greater than {1} to pass. Try running pylint to check manually. ...@@ -63,21 +72,7 @@ Score must be greater than {1} to pass. Try running pylint to check manually.
self.run_pylint(dirpath, fname) self.run_pylint(dirpath, fname)
self.check_logfile() self.check_logfile()
def test_TODO(Self):
self.assertTrue(False, msg="""
* PyOpal module initialisation which wraps BOOST_PYTHON_MODULE and does
** initialise globals
** initialise exception handling
** handle exceptions in module initialisation (which is not handled by
Boost exception handling)
* Also a test module for pyobject.h
* Some way to share the gmsg object rather than initialise once for each module
e.g. a "core" module that is always imported during pyopal import and
binding to pull the object across during Global initialisation
* Get predefined string to check against the list of predefines
"""
verbose = False verbose = False
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
\ No newline at end of file
"""Module to run the unit tests"""
import sys import sys
import os
import unittest import unittest
def main(): def main():
"""A very simple test runner script"""
runner = unittest.TextTestRunner() runner = unittest.TextTestRunner()
suite = unittest.defaultTestLoader.discover( suite = unittest.defaultTestLoader.discover(
start_dir = "tests/opal_src/PyOpal/", start_dir = "tests/opal_src/PyOpal/",
pattern = "test*" pattern = "test*"
) )
result = runner.run(suite) result = runner.run(suite)
print("Ran tests with {0} errors and {1} failures".format(len(result.errors), n_errors = len(result.errors)
len(result.failures))) n_failures = len(result.failures)
print(f"Ran tests with {n_errors} errors and {n_failures} failures")
if result.wasSuccessful(): if result.wasSuccessful():
print("Tests passed") print("Tests passed")
sys.exit(0) sys.exit(0)
...@@ -18,6 +21,5 @@ def main(): ...@@ -18,6 +21,5 @@ def main():
print("Tests failed (don't forget to make install...)") print("Tests failed (don't forget to make install...)")
sys.exit(len(result.errors)+len(result.failures)) sys.exit(len(result.errors)+len(result.failures))
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment