Best Python code snippet using hypothesis
stateful.py
Source:stateful.py  
...45class TestCaseProperty(object):  # pragma: no cover46    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')54def find_breaking_runner(state_machine_factory, settings=None):55    def is_breaking_run(runner):56        try:57            runner.run(state_machine_factory())58            return False59        except HypothesisException:60            raise61        except Exception:62            verbose_report(traceback.format_exc)63            return True64    if settings is None:65        try:66            settings = state_machine_factory.TestCase.settings67        except AttributeError:68            settings = Settings.default69    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    )76def run_state_machine_as_test(state_machine_factory, settings=None):77    """Run a state machine definition as a test, either silently doing nothing78    or printing a minimal breaking program and raising an exception.79    state_machine_factory is anything which returns an instance of80    GenericStateMachine when called with no arguments - it can be a class or a81    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        return87    try:88        with BuildContext(None, is_final=True):89            breaker.run(state_machine_factory(), print_steps=True)90    except StopTest:91        pass92    raise Flaky(93        u'Run failed initially but succeeded on a second try'94    )95class GenericStateMachine(object):96    """A GenericStateMachine is the basic entry point into Hypothesis's97    approach to stateful testing.98    The intent is for it to be subclassed to provide state machine descriptions99    The way this is used is that Hypothesis will repeatedly execute something100    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 small110    sequence of example choices demonstrating that.111    """112    def steps(self):113        """Return a SearchStrategy instance the defines the available next114        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) + 1124        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 necessary127        state.128        Does nothing by default129        """130        pass131    def check_invariants(self):132        """Called after initializing and after executing each step."""133        pass134    _test_case_cache = {}135    TestCase = TestCaseProperty()136    @classmethod137    def _to_test_case(state_machine_class):138        try:139            return state_machine_class._test_case_cache[state_machine_class]140        except KeyError:141            pass142        class StateMachineTestCase(TestCase):143            settings = Settings(144                min_satisfying_examples=1145            )146        # We define this outside of the class and assign it because you can't147        # assign attributes to instance method values in Python 2148        def runTest(self):149            run_state_machine_as_test(state_machine_class)150        runTest.is_hypothesis_test = True151        StateMachineTestCase.runTest = runTest...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
