executors.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # coding=utf-8
  2. #
  3. # This file is part of Hypothesis, which may be found at
  4. # https://github.com/HypothesisWorks/hypothesis-python
  5. #
  6. # Most of this work is copyright (C) 2013-2018 David R. MacIver
  7. # (david@drmaciver.com), but it contains contributions by others. See
  8. # CONTRIBUTING.rst for a full list of people who may hold copyright, and
  9. # consult the git log if you need to determine who owns an individual
  10. # contribution.
  11. #
  12. # This Source Code Form is subject to the terms of the Mozilla Public License,
  13. # v. 2.0. If a copy of the MPL was not distributed with this file, You can
  14. # obtain one at http://mozilla.org/MPL/2.0/.
  15. #
  16. # END HEADER
  17. from __future__ import division, print_function, absolute_import
  18. def default_executor(function): # pragma: nocover
  19. raise NotImplementedError() # We don't actually use this any more
  20. def setup_teardown_executor(setup, teardown):
  21. setup = setup or (lambda: None)
  22. teardown = teardown or (lambda ex: None)
  23. def execute(function):
  24. token = None
  25. try:
  26. token = setup()
  27. return function()
  28. finally:
  29. teardown(token)
  30. return execute
  31. def executor(runner):
  32. try:
  33. return runner.execute_example
  34. except AttributeError:
  35. pass
  36. if (
  37. hasattr(runner, 'setup_example') or
  38. hasattr(runner, 'teardown_example')
  39. ):
  40. return setup_teardown_executor(
  41. getattr(runner, 'setup_example', None),
  42. getattr(runner, 'teardown_example', None),
  43. )
  44. return default_executor
  45. def default_new_style_executor(data, function):
  46. return function(data)
  47. class ConjectureRunner(object):
  48. def hypothesis_execute_example_with_data(self, data, function):
  49. return function(data)
  50. def new_style_executor(runner):
  51. if runner is None:
  52. return default_new_style_executor
  53. if isinstance(runner, ConjectureRunner):
  54. return runner.hypothesis_execute_example_with_data
  55. old_school = executor(runner)
  56. if old_school is default_executor:
  57. return default_new_style_executor
  58. else:
  59. return lambda data, function: old_school(
  60. lambda: function(data)
  61. )