Debian Codegraph @

dev/tools/run_examples.py

raw
1 import os
2 import sys
3 import warnings
4 import runpy
5 import pytest
6
7 from brian2 import device, set_device
8
9 import numpy as np
10 warnings.simplefilter('ignore')
11
12
13 class ExampleRun(pytest.Item):
14 '''
15 A test case that simply executes a python script
16 '''
17 @classmethod
18 def from_parent(cls, filename, codegen_target, dtype, parent):
19 super_class = super(ExampleRun, cls)
20 if hasattr(super_class, 'from_parent'):
21 new_node = super_class.from_parent(parent=parent,
22 name=ExampleRun.id(filename))
23 else:
24 # For pytest < 6
25 new_node = cls(parent=parent, name=ExampleRun.id(filename))
26 new_node.filename = filename
27 new_node.codegen_target = codegen_target
28 new_node.dtype = dtype
29 return new_node
30
31 @staticmethod
32 def id(filename):
33 # Remove the .py and pretend the dirname is a package and the filename
34 # is a class.
35 name = os.path.splitext(os.path.split(filename)[1])[0]
36 pkgname = os.path.split(os.path.split(filename)[0])[1]
37 return pkgname + '.' + name.replace('.', '_')
38
39 def shortDescription(self):
40 return str(self)
41
42 def runtest(self):
43 import matplotlib as _mpl
44 _mpl.use('Agg')
45 import numpy as np
46 from brian2 import prefs
47 from brian2.utils.filetools import ensure_directory_of_file
48 prefs.codegen.target = self.codegen_target
49 prefs.core.default_float_dtype = self.dtype
50 # Move to the file's directory for the run, so that it can do relative
51 # imports and load files (e.g. figure style files)
52 curdir = os.getcwd()
53 os.chdir(os.path.dirname(self.filename))
54 sys.path.append(os.path.dirname(self.filename))
55 try:
56 runpy.run_path(self.filename, run_name='__main__')
57 if self.codegen_target == 'cython' and self.dtype == np.float64:
58 for fignum in _mpl.pyplot.get_fignums():
59 fname = os.path.relpath(self.filename, self.example_dir)
60 fname = fname.replace('/', '.').replace('\\\\', '.')
61 fname = fname.replace('.py', '.%d.png' % fignum)
62 fname = os.path.abspath(os.path.join(self.example_dir,
63 '../docs_sphinx/resources/examples_images/',
64 fname))
65 ensure_directory_of_file(fname)
66 _mpl.pyplot.figure(fignum).savefig(fname)
67 finally:
68 _mpl.pyplot.close('all')
69 os.chdir(curdir)
70 sys.path.remove(os.path.dirname(self.filename))
71 device.reinit()
72 set_device('runtime')
73
74 def __str__(self):
75 return 'Example: %s (%s, %s)' % (self.filename, self.codegen_target,
76 self.dtype.__name__)
77
78
79 class ExampleCollector(pytest.Collector):
80 @classmethod
81 def from_parent(cls, example_dir, parent):
82 collector = super(ExampleCollector, cls)
83 if hasattr(collector, 'from_parent'):
84 new_collector = collector.from_parent(parent,
85 name='example_collector')
86 else:
87 # For pytest < 6
88 new_collector = cls(parent=parent, name='example_collector')
89 new_collector.example_dir = example_dir
90 return new_collector
91
92 def collect(self):
93 for dirname, dirs, files in os.walk(self.example_dir):
94 for filename in files:
95 if filename.endswith('.py'):
96 run = ExampleRun.from_parent(os.path.join(dirname, filename),
97 'cython',
98 np.float64,
99 parent=self)
100 run.example_dir = self.example_dir
101 yield run
102
103
104 class Plugin:
105 def __init__(self, example_dir):
106 self.example_dir = example_dir
107
108 def pytest_collect_file(self, path, parent):
109 return ExampleCollector.from_parent(self.example_dir, parent=parent)
110
111
112 if __name__ == '__main__':
113 example_dir = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'examples'))
114 sys.exit(pytest.main([__file__, '--verbose'],
115 plugins=[Plugin(example_dir)]))