shared.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. from hypothesis.searchstrategy import SearchStrategy
  19. SHARED_STRATEGY_ATTRIBUTE = '_hypothesis_shared_strategies'
  20. class SharedStrategy(SearchStrategy):
  21. def __init__(self, base, key=None):
  22. self.key = key
  23. self.base = base
  24. @property
  25. def supports_find(self):
  26. return self.base.supports_find
  27. def __repr__(self):
  28. if self.key is not None:
  29. return 'shared(%r, key=%r)' % (self.base, self.key)
  30. else:
  31. return 'shared(%r)' % (self.base,)
  32. def do_draw(self, data):
  33. if not hasattr(data, SHARED_STRATEGY_ATTRIBUTE):
  34. setattr(data, SHARED_STRATEGY_ATTRIBUTE, {})
  35. sharing = getattr(data, SHARED_STRATEGY_ATTRIBUTE)
  36. key = self.key or self
  37. if key not in sharing:
  38. sharing[key] = data.draw(self.base)
  39. return sharing[key]