stateful.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. """This module provides support for a stateful style of testing, where tests
  18. attempt to find a sequence of operations that cause a breakage rather than just
  19. a single value.
  20. Notably, the set of steps available at any point may depend on the
  21. execution to date.
  22. """
  23. from __future__ import division, print_function, absolute_import
  24. import inspect
  25. import traceback
  26. from unittest import TestCase
  27. import attr
  28. import hypothesis.internal.conjecture.utils as cu
  29. from hypothesis.core import find
  30. from hypothesis.errors import Flaky, NoSuchExample, InvalidDefinition, \
  31. HypothesisException
  32. from hypothesis.control import BuildContext
  33. from hypothesis._settings import settings as Settings
  34. from hypothesis._settings import Verbosity
  35. from hypothesis.reporting import report, verbose_report, current_verbosity
  36. from hypothesis.strategies import just, lists, builds, one_of, runner, \
  37. integers
  38. from hypothesis.vendor.pretty import CUnicodeIO, RepresentationPrinter
  39. from hypothesis.internal.reflection import proxies, nicerepr
  40. from hypothesis.internal.conjecture.data import StopTest
  41. from hypothesis.internal.conjecture.utils import integer_range
  42. from hypothesis.searchstrategy.strategies import SearchStrategy
  43. from hypothesis.searchstrategy.collections import TupleStrategy, \
  44. FixedKeysDictStrategy
  45. class TestCaseProperty(object): # pragma: no cover
  46. def __get__(self, obj, typ=None):
  47. if obj is not None:
  48. typ = type(obj)
  49. return typ._to_test_case()
  50. def __set__(self, obj, value):
  51. raise AttributeError(u'Cannot set TestCase')
  52. def __delete__(self, obj):
  53. raise AttributeError(u'Cannot delete TestCase')
  54. def find_breaking_runner(state_machine_factory, settings=None):
  55. def is_breaking_run(runner):
  56. try:
  57. runner.run(state_machine_factory())
  58. return False
  59. except HypothesisException:
  60. raise
  61. except Exception:
  62. verbose_report(traceback.format_exc)
  63. return True
  64. if settings is None:
  65. try:
  66. settings = state_machine_factory.TestCase.settings
  67. except AttributeError:
  68. settings = Settings.default
  69. search_strategy = StateMachineSearchStrategy(settings)
  70. return find(
  71. search_strategy,
  72. is_breaking_run,
  73. settings=settings,
  74. database_key=state_machine_factory.__name__.encode('utf-8')
  75. )
  76. def run_state_machine_as_test(state_machine_factory, settings=None):
  77. """Run a state machine definition as a test, either silently doing nothing
  78. or printing a minimal breaking program and raising an exception.
  79. state_machine_factory is anything which returns an instance of
  80. GenericStateMachine when called with no arguments - it can be a class or a
  81. function. settings will be used to control the execution of the test.
  82. """
  83. try:
  84. breaker = find_breaking_runner(state_machine_factory, settings)
  85. except NoSuchExample:
  86. return
  87. try:
  88. with BuildContext(None, is_final=True):
  89. breaker.run(state_machine_factory(), print_steps=True)
  90. except StopTest:
  91. pass
  92. raise Flaky(
  93. u'Run failed initially but succeeded on a second try'
  94. )
  95. class GenericStateMachine(object):
  96. """A GenericStateMachine is the basic entry point into Hypothesis's
  97. approach to stateful testing.
  98. The intent is for it to be subclassed to provide state machine descriptions
  99. The way this is used is that Hypothesis will repeatedly execute something
  100. that looks something like::
  101. x = MyStatemachineSubclass()
  102. x.check_invariants()
  103. try:
  104. for _ in range(n_steps):
  105. x.execute_step(x.steps().example())
  106. x.check_invariants()
  107. finally:
  108. x.teardown()
  109. And if this ever produces an error it will shrink it down to a small
  110. sequence of example choices demonstrating that.
  111. """
  112. def steps(self):
  113. """Return a SearchStrategy instance the defines the available next
  114. steps."""
  115. raise NotImplementedError(u'%r.steps()' % (self,))
  116. def execute_step(self, step):
  117. """Execute a step that has been previously drawn from self.steps()"""
  118. raise NotImplementedError(u'%r.execute_step()' % (self,))
  119. def print_step(self, step):
  120. """Print a step to the current reporter.
  121. This is called right before a step is executed.
  122. """
  123. self.step_count = getattr(self, u'step_count', 0) + 1
  124. report(u'Step #%d: %s' % (self.step_count, nicerepr(step)))
  125. def teardown(self):
  126. """Called after a run has finished executing to clean up any necessary
  127. state.
  128. Does nothing by default
  129. """
  130. pass
  131. def check_invariants(self):
  132. """Called after initializing and after executing each step."""
  133. pass
  134. _test_case_cache = {}
  135. TestCase = TestCaseProperty()
  136. @classmethod
  137. def _to_test_case(state_machine_class):
  138. try:
  139. return state_machine_class._test_case_cache[state_machine_class]
  140. except KeyError:
  141. pass
  142. class StateMachineTestCase(TestCase):
  143. settings = Settings(
  144. min_satisfying_examples=1
  145. )
  146. # We define this outside of the class and assign it because you can't
  147. # assign attributes to instance method values in Python 2
  148. def runTest(self):
  149. run_state_machine_as_test(state_machine_class)
  150. runTest.is_hypothesis_test = True
  151. StateMachineTestCase.runTest = runTest
  152. base_name = state_machine_class.__name__
  153. StateMachineTestCase.__name__ = str(
  154. base_name + u'.TestCase'
  155. )
  156. StateMachineTestCase.__qualname__ = str(
  157. getattr(state_machine_class, u'__qualname__', base_name) +
  158. u'.TestCase'
  159. )
  160. state_machine_class._test_case_cache[state_machine_class] = (
  161. StateMachineTestCase
  162. )
  163. return StateMachineTestCase
  164. GenericStateMachine.find_breaking_runner = classmethod(find_breaking_runner)
  165. class StateMachineRunner(object):
  166. """A StateMachineRunner is a description of how to run a state machine.
  167. It contains values that it will use to shape the examples.
  168. """
  169. def __init__(self, data, n_steps):
  170. self.data = data
  171. self.data.is_find = False
  172. self.n_steps = n_steps
  173. def run(self, state_machine, print_steps=None):
  174. if print_steps is None:
  175. print_steps = current_verbosity() >= Verbosity.debug
  176. self.data.hypothesis_runner = state_machine
  177. stopping_value = 1 - 1.0 / (1 + self.n_steps * 0.5)
  178. try:
  179. state_machine.check_invariants()
  180. steps = 0
  181. while True:
  182. if steps >= self.n_steps:
  183. stopping_value = 0
  184. self.data.start_example()
  185. if not cu.biased_coin(self.data, stopping_value):
  186. self.data.stop_example()
  187. break
  188. assert steps < self.n_steps
  189. value = self.data.draw(state_machine.steps())
  190. steps += 1
  191. if print_steps:
  192. state_machine.print_step(value)
  193. state_machine.execute_step(value)
  194. self.data.stop_example()
  195. state_machine.check_invariants()
  196. finally:
  197. state_machine.teardown()
  198. class StateMachineSearchStrategy(SearchStrategy):
  199. def __init__(self, settings=None):
  200. self.program_size = (settings or Settings.default).stateful_step_count
  201. def do_draw(self, data):
  202. return StateMachineRunner(data, self.program_size)
  203. @attr.s()
  204. class Rule(object):
  205. targets = attr.ib()
  206. function = attr.ib()
  207. arguments = attr.ib()
  208. precondition = attr.ib()
  209. self_strategy = runner()
  210. class Bundle(SearchStrategy):
  211. def __init__(self, name):
  212. self.name = name
  213. def do_draw(self, data):
  214. machine = data.draw(self_strategy)
  215. bundle = machine.bundle(self.name)
  216. if not bundle:
  217. data.mark_invalid()
  218. reference = bundle.pop()
  219. bundle.insert(integer_range(data, 0, len(bundle)), reference)
  220. return machine.names_to_values[reference.name]
  221. RULE_MARKER = u'hypothesis_stateful_rule'
  222. PRECONDITION_MARKER = u'hypothesis_stateful_precondition'
  223. INVARIANT_MARKER = u'hypothesis_stateful_invariant'
  224. def rule(targets=(), target=None, **kwargs):
  225. """Decorator for RuleBasedStateMachine. Any name present in target or
  226. targets will define where the end result of this function should go. If
  227. both are empty then the end result will be discarded.
  228. targets may either be a Bundle or the name of a Bundle.
  229. kwargs then define the arguments that will be passed to the function
  230. invocation. If their value is a Bundle then values that have previously
  231. been produced for that bundle will be provided, if they are anything else
  232. it will be turned into a strategy and values from that will be provided.
  233. """
  234. if target is not None:
  235. targets += (target,)
  236. converted_targets = []
  237. for t in targets:
  238. while isinstance(t, Bundle):
  239. t = t.name
  240. converted_targets.append(t)
  241. def accept(f):
  242. existing_rule = getattr(f, RULE_MARKER, None)
  243. if existing_rule is not None:
  244. raise InvalidDefinition(
  245. 'A function cannot be used for two distinct rules. ',
  246. Settings.default,
  247. )
  248. precondition = getattr(f, PRECONDITION_MARKER, None)
  249. rule = Rule(targets=tuple(converted_targets), arguments=kwargs,
  250. function=f, precondition=precondition)
  251. @proxies(f)
  252. def rule_wrapper(*args, **kwargs):
  253. return f(*args, **kwargs)
  254. setattr(rule_wrapper, RULE_MARKER, rule)
  255. return rule_wrapper
  256. return accept
  257. @attr.s()
  258. class VarReference(object):
  259. name = attr.ib()
  260. def precondition(precond):
  261. """Decorator to apply a precondition for rules in a RuleBasedStateMachine.
  262. Specifies a precondition for a rule to be considered as a valid step in the
  263. state machine. The given function will be called with the instance of
  264. RuleBasedStateMachine and should return True or False. Usually it will need
  265. to look at attributes on that instance.
  266. For example::
  267. class MyTestMachine(RuleBasedStateMachine):
  268. state = 1
  269. @precondition(lambda self: self.state != 0)
  270. @rule(numerator=integers())
  271. def divide_with(self, numerator):
  272. self.state = numerator / self.state
  273. This is better than using assume in your rule since more valid rules
  274. should be able to be run.
  275. """
  276. def decorator(f):
  277. @proxies(f)
  278. def precondition_wrapper(*args, **kwargs):
  279. return f(*args, **kwargs)
  280. rule = getattr(f, RULE_MARKER, None)
  281. if rule is None:
  282. setattr(precondition_wrapper, PRECONDITION_MARKER, precond)
  283. else:
  284. new_rule = Rule(targets=rule.targets, arguments=rule.arguments,
  285. function=rule.function, precondition=precond)
  286. setattr(precondition_wrapper, RULE_MARKER, new_rule)
  287. invariant = getattr(f, INVARIANT_MARKER, None)
  288. if invariant is not None:
  289. new_invariant = Invariant(function=invariant.function,
  290. precondition=precond)
  291. setattr(precondition_wrapper, INVARIANT_MARKER, new_invariant)
  292. return precondition_wrapper
  293. return decorator
  294. @attr.s()
  295. class Invariant(object):
  296. function = attr.ib()
  297. precondition = attr.ib()
  298. def invariant():
  299. """Decorator to apply an invariant for rules in a RuleBasedStateMachine.
  300. The decorated function will be run after every rule and can raise an
  301. exception to indicate failed invariants.
  302. For example::
  303. class MyTestMachine(RuleBasedStateMachine):
  304. state = 1
  305. @invariant()
  306. def is_nonzero(self):
  307. assert self.state != 0
  308. """
  309. def accept(f):
  310. existing_invariant = getattr(f, INVARIANT_MARKER, None)
  311. if existing_invariant is not None:
  312. raise InvalidDefinition(
  313. 'A function cannot be used for two distinct invariants.',
  314. Settings.default,
  315. )
  316. precondition = getattr(f, PRECONDITION_MARKER, None)
  317. rule = Invariant(function=f, precondition=precondition)
  318. @proxies(f)
  319. def invariant_wrapper(*args, **kwargs):
  320. return f(*args, **kwargs)
  321. setattr(invariant_wrapper, INVARIANT_MARKER, rule)
  322. return invariant_wrapper
  323. return accept
  324. @attr.s()
  325. class ShuffleBundle(object):
  326. bundle = attr.ib()
  327. swaps = attr.ib()
  328. class RuleBasedStateMachine(GenericStateMachine):
  329. """A RuleBasedStateMachine gives you a more structured way to define state
  330. machines.
  331. The idea is that a state machine carries a bunch of types of data
  332. divided into Bundles, and has a set of rules which may read data
  333. from bundles (or just from normal strategies) and push data onto
  334. bundles. At any given point a random applicable rule will be
  335. executed.
  336. """
  337. _rules_per_class = {}
  338. _invariants_per_class = {}
  339. _base_rules_per_class = {}
  340. def __init__(self):
  341. if not self.rules():
  342. raise InvalidDefinition(u'Type %s defines no rules' % (
  343. type(self).__name__,
  344. ))
  345. self.bundles = {}
  346. self.name_counter = 1
  347. self.names_to_values = {}
  348. self.__stream = CUnicodeIO()
  349. self.__printer = RepresentationPrinter(self.__stream)
  350. def __pretty(self, value):
  351. self.__stream.seek(0)
  352. self.__stream.truncate(0)
  353. self.__printer.output_width = 0
  354. self.__printer.buffer_width = 0
  355. self.__printer.buffer.clear()
  356. self.__printer.pretty(value)
  357. self.__printer.flush()
  358. return self.__stream.getvalue()
  359. def __repr__(self):
  360. return u'%s(%s)' % (
  361. type(self).__name__,
  362. nicerepr(self.bundles),
  363. )
  364. def upcoming_name(self):
  365. return u'v%d' % (self.name_counter,)
  366. def new_name(self):
  367. result = self.upcoming_name()
  368. self.name_counter += 1
  369. return result
  370. def bundle(self, name):
  371. return self.bundles.setdefault(name, [])
  372. @classmethod
  373. def rules(cls):
  374. try:
  375. return cls._rules_per_class[cls]
  376. except KeyError:
  377. pass
  378. for k, v in inspect.getmembers(cls):
  379. r = getattr(v, RULE_MARKER, None)
  380. if r is not None:
  381. cls.define_rule(
  382. r.targets, r.function, r.arguments, r.precondition,
  383. )
  384. cls._rules_per_class[cls] = cls._base_rules_per_class.pop(cls, [])
  385. return cls._rules_per_class[cls]
  386. @classmethod
  387. def invariants(cls):
  388. try:
  389. return cls._invariants_per_class[cls]
  390. except KeyError:
  391. pass
  392. target = []
  393. for k, v in inspect.getmembers(cls):
  394. i = getattr(v, INVARIANT_MARKER, None)
  395. if i is not None:
  396. target.append(i)
  397. cls._invariants_per_class[cls] = target
  398. return cls._invariants_per_class[cls]
  399. @classmethod
  400. def define_rule(cls, targets, function, arguments, precondition=None):
  401. converted_arguments = {}
  402. for k, v in arguments.items():
  403. converted_arguments[k] = v
  404. if cls in cls._rules_per_class:
  405. target = cls._rules_per_class[cls]
  406. else:
  407. target = cls._base_rules_per_class.setdefault(cls, [])
  408. return target.append(
  409. Rule(
  410. targets, function, converted_arguments, precondition,
  411. )
  412. )
  413. def steps(self):
  414. strategies = []
  415. for rule in self.rules():
  416. converted_arguments = {}
  417. valid = True
  418. if rule.precondition and not rule.precondition(self):
  419. continue
  420. for k, v in sorted(rule.arguments.items()):
  421. if isinstance(v, Bundle):
  422. bundle = self.bundle(v.name)
  423. if not bundle:
  424. valid = False
  425. break
  426. converted_arguments[k] = v
  427. if valid:
  428. strategies.append(TupleStrategy((
  429. just(rule),
  430. FixedKeysDictStrategy(converted_arguments)
  431. ), tuple))
  432. if not strategies:
  433. raise InvalidDefinition(
  434. u'No progress can be made from state %r' % (self,)
  435. )
  436. for name, bundle in self.bundles.items():
  437. if len(bundle) > 1:
  438. strategies.append(
  439. builds(
  440. ShuffleBundle, just(name),
  441. lists(integers(0, len(bundle) - 1))))
  442. return one_of(strategies)
  443. def print_step(self, step):
  444. if isinstance(step, ShuffleBundle):
  445. return
  446. rule, data = step
  447. data_repr = {}
  448. for k, v in data.items():
  449. data_repr[k] = self.__pretty(v)
  450. self.step_count = getattr(self, u'step_count', 0) + 1
  451. report(u'Step #%d: %s%s(%s)' % (
  452. self.step_count,
  453. u'%s = ' % (self.upcoming_name(),) if rule.targets else u'',
  454. rule.function.__name__,
  455. u', '.join(u'%s=%s' % kv for kv in data_repr.items())
  456. ))
  457. def execute_step(self, step):
  458. if isinstance(step, ShuffleBundle):
  459. bundle = self.bundle(step.bundle)
  460. for i in step.swaps:
  461. bundle.insert(i, bundle.pop())
  462. return
  463. rule, data = step
  464. data = dict(data)
  465. result = rule.function(self, **data)
  466. if rule.targets:
  467. name = self.new_name()
  468. self.names_to_values[name] = result
  469. self.__printer.singleton_pprinters.setdefault(
  470. id(result), lambda obj, p, cycle: p.text(name),
  471. )
  472. for target in rule.targets:
  473. self.bundle(target).append(VarReference(name))
  474. def check_invariants(self):
  475. for invar in self.invariants():
  476. if invar.precondition and not invar.precondition(self):
  477. continue
  478. invar.function(self)