| 1 |
""" |
| 2 |
Package contain all unit/integration tests for the `brian2` package. |
| 3 |
""" |
| 4 |
|
| 5 |
import os |
| 6 |
import sys |
| 7 |
import tempfile |
| 8 |
from io import StringIO |
| 9 |
|
| 10 |
import numpy as np |
| 11 |
|
| 12 |
import brian2 |
| 13 |
from brian2.core.preferences import prefs |
| 14 |
from brian2.devices.device import all_devices, reinit_and_delete, reset_device |
| 15 |
|
| 16 |
try: |
| 17 |
import importlib |
| 18 |
|
| 19 |
import pytest |
| 20 |
from _pytest import doctest as pytest_doctest |
| 21 |
|
| 22 |
class OurDoctestModule(pytest_doctest.DoctestModule): |
| 23 |
def collect(self): |
| 24 |
for item in super().collect(): |
| 25 |
# Check the object for exclusion from doctests |
| 26 |
full_name = item.name.split(".") |
| 27 |
test_name = [] |
| 28 |
module_name = os.path.splitext(os.path.basename(self.name))[0] |
| 29 |
while full_name[-1] != module_name: |
| 30 |
test_name.append(full_name.pop()) |
| 31 |
tested_obj = self.obj |
| 32 |
for name in reversed(test_name): |
| 33 |
tested_obj = getattr(tested_obj, name) |
| 34 |
if not getattr(tested_obj, "_do_not_run_doctests", False): |
| 35 |
yield item |
| 36 |
|
| 37 |
# Monkey patch pytest |
| 38 |
pytest_doctest.DoctestModule = OurDoctestModule |
| 39 |
|
| 40 |
except ImportError: |
| 41 |
pytest = None |
| 42 |
|
| 43 |
|
| 44 |
class PreferencePlugin: |
| 45 |
def __init__(self, prefs, fail_for_not_implemented=True): |
| 46 |
self.prefs = prefs |
| 47 |
self.device = "runtime" |
| 48 |
self.device_options = {} |
| 49 |
self.fail_for_not_implemented = fail_for_not_implemented |
| 50 |
|
| 51 |
def pytest_configure(self, config): |
| 52 |
config.brian_prefs = dict(self.prefs) |
| 53 |
config.fail_for_not_implemented = self.fail_for_not_implemented |
| 54 |
config.device = self.device |
| 55 |
config.device_options = self.device_options |
| 56 |
if config.pluginmanager.hasplugin("xdist"): |
| 57 |
xdist_plugin = XDistPreferencePlugin(self) |
| 58 |
config.pluginmanager.register(xdist_plugin) |
| 59 |
|
| 60 |
|
| 61 |
class XDistPreferencePlugin: |
| 62 |
def __init__(self, pref_plugin): |
| 63 |
self._pref_plugin = pref_plugin |
| 64 |
|
| 65 |
def pytest_configure_node(self, node): |
| 66 |
"""xdist hook""" |
| 67 |
prefs = dict(self._pref_plugin.prefs) |
| 68 |
for k, v in prefs.items(): |
| 69 |
if isinstance(v, type): |
| 70 |
prefs[k] = ("TYPE", repr(v)) |
| 71 |
node.workerinput["brian_prefs"] = prefs |
| 72 |
node.workerinput["fail_for_not_implemented"] = ( |
| 73 |
self._pref_plugin.fail_for_not_implemented |
| 74 |
) |
| 75 |
node.workerinput["device"] = self._pref_plugin.device |
| 76 |
node.workerinput["device_options"] = self._pref_plugin.device_options |
| 77 |
|
| 78 |
|
| 79 |
def clear_caches(): |
| 80 |
from brian2.utils.logger import BrianLogger |
| 81 |
|
| 82 |
BrianLogger._log_messages.clear() |
| 83 |
from brian2.codegen.translation import make_statements |
| 84 |
|
| 85 |
make_statements._cache.clear() |
| 86 |
|
| 87 |
|
| 88 |
def make_argv(dirnames, markers=None, doctests=False, test_GSL=False): |
| 89 |
""" |
| 90 |
Create the list of arguments for the ``pytests`` call. |
| 91 |
|
| 92 |
Parameters |
| 93 |
---------- |
| 94 |
markers : str, optional |
| 95 |
The markers of the tests to include. |
| 96 |
doctests : bool, optional |
| 97 |
Whether to run doctests. Defaults to ``False``. |
| 98 |
test_GSL : bool, optional |
| 99 |
Whether to run tests requiring the GSL. If set to |
| 100 |
``False``, tests marked with ``gsl`` will be |
| 101 |
excluded. Defaults to ``False``. |
| 102 |
|
| 103 |
Returns |
| 104 |
------- |
| 105 |
argv : list of str |
| 106 |
The arguments for `pytest.main`. |
| 107 |
|
| 108 |
""" |
| 109 |
if doctests: |
| 110 |
if markers is not None: |
| 111 |
raise TypeError("Cannot give markers for doctests") |
| 112 |
argv = dirnames + [ |
| 113 |
"-c", |
| 114 |
os.path.join(os.path.dirname(__file__), "pytest.ini"), |
| 115 |
"--quiet", |
| 116 |
"--doctest-modules", |
| 117 |
"--doctest-glob=*.rst", |
| 118 |
"--doctest-ignore-import-errors", |
| 119 |
"--confcutdir", |
| 120 |
os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), |
| 121 |
"--pyargs", |
| 122 |
"brian2", |
| 123 |
] |
| 124 |
if len(dirnames) == 2: |
| 125 |
# If we are testing files in docs_sphinx, ignore conf.py |
| 126 |
argv += [f"--ignore={os.path.join(dirnames[1], 'conf.py')}"] |
| 127 |
else: |
| 128 |
if not test_GSL: |
| 129 |
markers += " and not gsl" |
| 130 |
argv = dirnames + [ |
| 131 |
"-c", |
| 132 |
os.path.join(os.path.dirname(__file__), "pytest.ini"), |
| 133 |
"--quiet", |
| 134 |
"-m", |
| 135 |
f"{markers}", |
| 136 |
"--confcutdir", |
| 137 |
os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), |
| 138 |
] |
| 139 |
return argv |
| 140 |
|
| 141 |
|
| 142 |
def run( |
| 143 |
codegen_targets=None, |
| 144 |
long_tests=False, |
| 145 |
test_codegen_independent=True, |
| 146 |
test_standalone=None, |
| 147 |
test_openmp=False, |
| 148 |
test_in_parallel=["codegen_independent", "numpy", "cython", "cpp_standalone"], |
| 149 |
reset_preferences=True, |
| 150 |
fail_for_not_implemented=True, |
| 151 |
test_GSL=False, |
| 152 |
build_options=None, |
| 153 |
extra_test_dirs=None, |
| 154 |
sphinx_dir=None, |
| 155 |
float_dtype=None, |
| 156 |
additional_args=None, |
| 157 |
): |
| 158 |
""" |
| 159 |
Run brian's test suite. Needs an installation of the pytest testing tool. |
| 160 |
|
| 161 |
For testing, the preferences will be reset to the default preferences. |
| 162 |
After testing, the user preferences will be restored. |
| 163 |
|
| 164 |
Parameters |
| 165 |
---------- |
| 166 |
codegen_targets : list of str or str |
| 167 |
A list of codegeneration targets or a single target, e.g. |
| 168 |
``['numpy', 'cython']`` to test. The whole test suite will be repeatedly |
| 169 |
run with `codegen.target` set to the respective value. If not |
| 170 |
specified, all available code generation targets will be tested. |
| 171 |
long_tests : bool, optional |
| 172 |
Whether to run tests that take a long time. Defaults to ``False``. |
| 173 |
test_codegen_independent : bool, optional |
| 174 |
Whether to run tests that are independent of code generation. Defaults |
| 175 |
to ``True``. |
| 176 |
test_standalone : str, optional |
| 177 |
Whether to run tests for a standalone mode. Should be the name of a |
| 178 |
standalone mode (e.g. ``'cpp_standalone'``) and expects that a device |
| 179 |
of that name and an accordingly named "simple" device (e.g. |
| 180 |
``'cpp_standalone_simple'`` exists that can be used for testing (see |
| 181 |
`CPPStandaloneSimpleDevice` for details. Defaults to ``None``, meaning |
| 182 |
that no standalone device is tested. |
| 183 |
test_openmp : bool, optional |
| 184 |
Whether to test standalone test with multiple threads and OpenMP. Will |
| 185 |
be ignored if ``cpp_standalone`` is not tested. Defaults to ``False``. |
| 186 |
reset_preferences : bool, optional |
| 187 |
Whether to reset all preferences to the default preferences before |
| 188 |
running the test suite. Defaults to ``True`` to get test results |
| 189 |
independent of the user's preference settings but can be switched off |
| 190 |
when the preferences are actually necessary to pass the tests (e.g. for |
| 191 |
device-specific settings). |
| 192 |
fail_for_not_implemented : bool, optional |
| 193 |
Whether to fail for tests raising a `NotImplementedError`. Defaults to |
| 194 |
``True``, but can be switched off for devices known to not implement |
| 195 |
all of Brian's features. |
| 196 |
test_GSL : bool, optional |
| 197 |
Whether to test support for GSL state updaters (requires an installation |
| 198 |
of the GSL development packages). Defaults to ``False``. |
| 199 |
build_options : dict, optional |
| 200 |
Non-default build options that will be passed as arguments to the |
| 201 |
`set_device` call for the device specified in ``test_standalone``. |
| 202 |
extra_test_dirs : list of str or str, optional |
| 203 |
Additional directories as a list of strings (or a single directory as |
| 204 |
a string) that will be searched for additional tests. |
| 205 |
sphinx_dir : str, optional |
| 206 |
The full path to ``docs_sphinx``, in order to execute doc tests in the |
| 207 |
rst files. If not provided, assumes we are running from a checked out |
| 208 |
repository where the directory can be found at ``../../docs_sphinx``. |
| 209 |
Will ignore the provided directory if it does not exist. |
| 210 |
float_dtype : np.dtype, optional |
| 211 |
Set the dtype to use for floating point variables to a value different |
| 212 |
from the default `core.default_float_dtype` setting. |
| 213 |
additional_args : list of str, optional |
| 214 |
Optional command line arguments to pass to ``pytest`` |
| 215 |
""" |
| 216 |
if pytest is None: |
| 217 |
raise ImportError("Running the test suite requires the 'pytest' package.") |
| 218 |
|
| 219 |
if build_options is None: |
| 220 |
build_options = {} |
| 221 |
|
| 222 |
if os.name == "nt": |
| 223 |
test_in_parallel = [] |
| 224 |
|
| 225 |
if extra_test_dirs is None: |
| 226 |
extra_test_dirs = [] |
| 227 |
elif isinstance(extra_test_dirs, str): |
| 228 |
extra_test_dirs = [extra_test_dirs] |
| 229 |
if additional_args is None: |
| 230 |
additional_args = [] |
| 231 |
|
| 232 |
multiprocess_arguments = ["-n", "auto"] |
| 233 |
|
| 234 |
if codegen_targets is None: |
| 235 |
codegen_targets = ["numpy"] |
| 236 |
try: |
| 237 |
import Cython |
| 238 |
|
| 239 |
codegen_targets.append("cython") |
| 240 |
except ImportError: |
| 241 |
pass |
| 242 |
elif isinstance(codegen_targets, str): # allow to give a single target |
| 243 |
codegen_targets = [codegen_targets] |
| 244 |
|
| 245 |
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) |
| 246 |
dirnames = [dirname] + extra_test_dirs |
| 247 |
|
| 248 |
print(f"Running tests in {', '.join(dirnames)} ", end="") |
| 249 |
if codegen_targets: |
| 250 |
print(f"for targets {', '.join(codegen_targets)}", end="") |
| 251 |
ex_in = "including" if long_tests else "excluding" |
| 252 |
print(f" ({ex_in} long tests)") |
| 253 |
|
| 254 |
print( |
| 255 |
f"Running Brian version {brian2.__version__} from" |
| 256 |
f" '{os.path.dirname(brian2.__file__)}'" |
| 257 |
) |
| 258 |
|
| 259 |
all_targets = set(codegen_targets) |
| 260 |
|
| 261 |
if test_standalone: |
| 262 |
if not isinstance(test_standalone, str): |
| 263 |
raise ValueError( |
| 264 |
"test_standalone argument has to be the name of a " |
| 265 |
"standalone device (e.g. 'cpp_standalone')" |
| 266 |
) |
| 267 |
if test_standalone not in all_devices: |
| 268 |
known_devices = ", ".join(repr(d) for d in all_devices) |
| 269 |
raise ValueError( |
| 270 |
"test_standalone argument 'test_standalone' is not a known " |
| 271 |
f"device. Known devices are: {known_devices}." |
| 272 |
) |
| 273 |
print("Testing standalone") |
| 274 |
all_targets.add(test_standalone) |
| 275 |
if test_codegen_independent: |
| 276 |
print("Testing codegen-independent code") |
| 277 |
all_targets.add("codegen_independent") |
| 278 |
|
| 279 |
parallel_tests = all_targets.intersection(set(test_in_parallel)) |
| 280 |
if parallel_tests: |
| 281 |
try: |
| 282 |
import xdist |
| 283 |
|
| 284 |
print(f"Testing with multiple processes for {', '.join(parallel_tests)}") |
| 285 |
except ImportError: |
| 286 |
test_in_parallel = [] |
| 287 |
|
| 288 |
if reset_preferences: |
| 289 |
print("Resetting to default preferences") |
| 290 |
stored_prefs = prefs.as_file |
| 291 |
prefs.reset_to_defaults() |
| 292 |
|
| 293 |
# Avoid failures in the tests for user-registered units |
| 294 |
import copy |
| 295 |
|
| 296 |
import brian2.units.fundamentalunits as fundamentalunits |
| 297 |
|
| 298 |
old_unit_registry = copy.copy(fundamentalunits.user_unit_register) |
| 299 |
fundamentalunits.user_unit_register = fundamentalunits.UnitRegistry() |
| 300 |
|
| 301 |
if float_dtype is not None: |
| 302 |
print(f"Setting dtype for floating point variables to: {float_dtype.__name__}") |
| 303 |
|
| 304 |
prefs["core.default_float_dtype"] = float_dtype |
| 305 |
|
| 306 |
print() |
| 307 |
|
| 308 |
# Suppress INFO log messages during testing |
| 309 |
from brian2.utils.logger import LOG_LEVELS, BrianLogger |
| 310 |
|
| 311 |
log_level = BrianLogger.console_handler.level |
| 312 |
BrianLogger.console_handler.setLevel(LOG_LEVELS["WARNING"]) |
| 313 |
|
| 314 |
# Switch off code optimization to get faster compilation times |
| 315 |
prefs["codegen.cpp.extra_compile_args_gcc"].extend(["-w", "-O0"]) |
| 316 |
prefs["codegen.cpp.extra_compile_args_msvc"].extend(["/Od"]) |
| 317 |
|
| 318 |
# Switch off unused object warning |
| 319 |
prefs["logging.warn_for_unused_objects"] = False |
| 320 |
|
| 321 |
pref_plugin = PreferencePlugin(prefs, fail_for_not_implemented) |
| 322 |
try: |
| 323 |
success = [] |
| 324 |
pref_plugin.device = "runtime" |
| 325 |
pref_plugin.device_options = {} |
| 326 |
if test_codegen_independent: |
| 327 |
print("Running doctests") |
| 328 |
# Some doctests do actually use code generation, use numpy for that |
| 329 |
prefs["codegen.target"] = "numpy" |
| 330 |
# Always test doctests with 64 bit, to avoid differences in print output |
| 331 |
if float_dtype is not None: |
| 332 |
prefs["core.default_float_dtype"] = np.float64 |
| 333 |
if sphinx_dir is None: |
| 334 |
sphinx_dir = os.path.abspath( |
| 335 |
os.path.join(os.path.dirname(__file__), "..", "..", "docs_sphinx") |
| 336 |
) |
| 337 |
if os.path.exists(sphinx_dir): |
| 338 |
sphinx_doc_dir = [sphinx_dir] |
| 339 |
else: |
| 340 |
# When running on travis, the source directory is in the SRCDIR |
| 341 |
# environment variable |
| 342 |
if "SRCDIR" in os.environ: |
| 343 |
sphinx_dir = os.path.abspath( |
| 344 |
os.path.join(os.environ["SRCDIR"], "docs_sphinx") |
| 345 |
) |
| 346 |
if os.path.exists(sphinx_dir): |
| 347 |
sphinx_doc_dir = [sphinx_dir] |
| 348 |
else: |
| 349 |
sphinx_doc_dir = [] |
| 350 |
else: |
| 351 |
sphinx_doc_dir = [] |
| 352 |
argv = make_argv(dirnames + sphinx_doc_dir, doctests=True) |
| 353 |
if "codegen_independent" in test_in_parallel: |
| 354 |
argv.extend(multiprocess_arguments) |
| 355 |
success.append( |
| 356 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) == 0 |
| 357 |
) |
| 358 |
# Set float_dtype back again if necessary |
| 359 |
if float_dtype is not None: |
| 360 |
prefs["core.default_float_dtype"] = float_dtype |
| 361 |
|
| 362 |
print("Running tests that do not use code generation") |
| 363 |
argv = make_argv(dirnames, "codegen_independent", test_GSL=test_GSL) |
| 364 |
if "codegen_independent" in test_in_parallel: |
| 365 |
argv.extend(multiprocess_arguments) |
| 366 |
success.append( |
| 367 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) == 0 |
| 368 |
) |
| 369 |
clear_caches() |
| 370 |
|
| 371 |
for target in codegen_targets: |
| 372 |
print(f"Running tests for target {target}:") |
| 373 |
prefs["codegen.target"] = target |
| 374 |
# Also set the target for string-expressions -- otherwise we'd only |
| 375 |
# ever test numpy for those |
| 376 |
prefs["codegen.string_expression_target"] = target |
| 377 |
|
| 378 |
markers = "not standalone_only and not codegen_independent" |
| 379 |
if not long_tests: |
| 380 |
markers += " and not long" |
| 381 |
# explicitly ignore the brian2.hears file for testing, otherwise the |
| 382 |
# doctest search will import it, failing on Python 3 |
| 383 |
argv = make_argv(dirnames, markers, test_GSL=test_GSL) |
| 384 |
if target in test_in_parallel: |
| 385 |
argv.extend(multiprocess_arguments) |
| 386 |
success.append( |
| 387 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) == 0 |
| 388 |
) |
| 389 |
clear_caches() |
| 390 |
|
| 391 |
pref_plugin.device = test_standalone |
| 392 |
if test_standalone: |
| 393 |
from brian2.devices.device import get_device, set_device |
| 394 |
|
| 395 |
pref_plugin.device_options = {"directory": None, "with_output": False} |
| 396 |
pref_plugin.device_options.update(build_options) |
| 397 |
print(f'Testing standalone device "{test_standalone}"') |
| 398 |
print("Running standalone-compatible standard tests (single run statement)") |
| 399 |
markers = "and not long" if not long_tests else "" |
| 400 |
markers += " and not multiple_runs" |
| 401 |
argv = make_argv( |
| 402 |
dirnames, f"standalone_compatible {markers}", test_GSL=test_GSL |
| 403 |
) |
| 404 |
if test_standalone in test_in_parallel: |
| 405 |
argv.extend(multiprocess_arguments) |
| 406 |
success.append( |
| 407 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) in [0, 5] |
| 408 |
) |
| 409 |
clear_caches() |
| 410 |
|
| 411 |
reset_device() |
| 412 |
|
| 413 |
print( |
| 414 |
"Running standalone-compatible standard tests (multiple run statements)" |
| 415 |
) |
| 416 |
pref_plugin.device_options = { |
| 417 |
"directory": None, |
| 418 |
"with_output": False, |
| 419 |
"build_on_run": False, |
| 420 |
} |
| 421 |
pref_plugin.device_options.update(build_options) |
| 422 |
markers = " and not long" if not long_tests else "" |
| 423 |
markers += " and multiple_runs" |
| 424 |
argv = make_argv( |
| 425 |
dirnames, f"standalone_compatible{markers}", test_GSL=test_GSL |
| 426 |
) |
| 427 |
if test_standalone in test_in_parallel: |
| 428 |
argv.extend(multiprocess_arguments) |
| 429 |
success.append( |
| 430 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) in [0, 5] |
| 431 |
) |
| 432 |
clear_caches() |
| 433 |
reset_device() |
| 434 |
|
| 435 |
if test_openmp and test_standalone == "cpp_standalone": |
| 436 |
# Run all the standalone compatible tests again with 4 threads |
| 437 |
pref_plugin.device_options = {"directory": None, "with_output": False} |
| 438 |
pref_plugin.device_options.update(build_options) |
| 439 |
prefs["devices.cpp_standalone.openmp_threads"] = 4 |
| 440 |
print( |
| 441 |
"Running standalone-compatible standard tests with OpenMP (single" |
| 442 |
" run statements)" |
| 443 |
) |
| 444 |
markers = " and not long" if not long_tests else "" |
| 445 |
markers += " and not multiple_runs" |
| 446 |
argv = make_argv( |
| 447 |
dirnames, f"standalone_compatible{markers}", test_GSL=test_GSL |
| 448 |
) |
| 449 |
success.append( |
| 450 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) in [0, 5] |
| 451 |
) |
| 452 |
clear_caches() |
| 453 |
reset_device() |
| 454 |
|
| 455 |
pref_plugin.device_options = { |
| 456 |
"directory": None, |
| 457 |
"with_output": False, |
| 458 |
"build_on_run": False, |
| 459 |
} |
| 460 |
pref_plugin.device_options.update(build_options) |
| 461 |
print( |
| 462 |
"Running standalone-compatible standard tests with OpenMP (multiple" |
| 463 |
" run statements)" |
| 464 |
) |
| 465 |
markers = " and not long" if not long_tests else "" |
| 466 |
markers += " and multiple_runs" |
| 467 |
argv = make_argv( |
| 468 |
dirnames, f"standalone_compatible{markers}", test_GSL=test_GSL |
| 469 |
) |
| 470 |
success.append( |
| 471 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) in [0, 5] |
| 472 |
) |
| 473 |
clear_caches() |
| 474 |
prefs["devices.cpp_standalone.openmp_threads"] = 0 |
| 475 |
|
| 476 |
reset_device() |
| 477 |
|
| 478 |
print("Running standalone-specific tests") |
| 479 |
exclude_openmp = " and not openmp" if not test_openmp else "" |
| 480 |
argv = make_argv( |
| 481 |
dirnames, test_standalone + exclude_openmp, test_GSL=test_GSL |
| 482 |
) |
| 483 |
if test_standalone in test_in_parallel: |
| 484 |
argv.extend(multiprocess_arguments) |
| 485 |
success.append( |
| 486 |
pytest.main(argv + additional_args, plugins=[pref_plugin]) in [0, 5] |
| 487 |
) |
| 488 |
clear_caches() |
| 489 |
|
| 490 |
all_success = all(success) |
| 491 |
if not all_success: |
| 492 |
print( |
| 493 |
f"ERROR: {len(success) - sum(success)}/{len(success)} test suite(s) " |
| 494 |
"did not complete successfully (see above)." |
| 495 |
) |
| 496 |
else: |
| 497 |
print( |
| 498 |
f"OK: {len(success)}/{len(success)} test suite(s) did complete " |
| 499 |
"successfully." |
| 500 |
) |
| 501 |
return all_success |
| 502 |
|
| 503 |
finally: |
| 504 |
BrianLogger.console_handler.setLevel(log_level) |
| 505 |
|
| 506 |
if reset_preferences: |
| 507 |
# Restore the user preferences |
| 508 |
prefs.read_preference_file(StringIO(stored_prefs)) |
| 509 |
prefs._backup() |
| 510 |
|
| 511 |
fundamentalunits.user_unit_register = old_unit_registry |
| 512 |
|
| 513 |
|
| 514 |
if __name__ == "__main__": |
| 515 |
run() |