Best Python code snippet using hypothesis
datatree.py
Source:datatree.py  
...127        self.transition = Branch(bit_length=self.bit_lengths[i], children={key: child})128        if self.__forced is not None:129            child.__forced = {j - i - 1 for j in self.__forced if j > i}130            self.__forced = {j for j in self.__forced if j < i}131        child.check_exhausted()132        del self.values[i:]133        del self.bit_lengths[i:]134        assert len(self.values) == len(self.bit_lengths) == i135    def check_exhausted(self):136        """Recalculates ``self.is_exhausted`` if necessary then returns137        it."""138        if (139            not self.is_exhausted140            and len(self.forced) == len(self.values)141            and self.transition is not None142        ):143            if isinstance(self.transition, Conclusion):144                self.is_exhausted = True145            elif len(self.transition.children) == self.transition.max_children:146                self.is_exhausted = all(147                    v.is_exhausted for v in self.transition.children.values()148                )149        return self.is_exhausted150class DataTree(object):151    """Tracks the tree structure of a collection of ConjectureData152    objects, for use in ConjectureRunner."""153    def __init__(self):154        self.root = TreeNode()155    @property156    def is_exhausted(self):157        """Returns True if every possible node is dead and thus the language158        described must have been fully explored."""159        return self.root.is_exhausted160    def generate_novel_prefix(self, random):161        """Generate a short random string that (after rewriting) is not162        a prefix of any buffer previously added to the tree.163        The resulting prefix is essentially arbitrary - it would be nice164        for it to be uniform at random, but previous attempts to do that165        have proven too expensive.166        """167        assert not self.is_exhausted168        novel_prefix = bytearray()169        def append_int(n_bits, value):170            novel_prefix.extend(int_to_bytes(value, bits_to_bytes(n_bits)))171        current_node = self.root172        while True:173            assert not current_node.is_exhausted174            for i, (n_bits, value) in enumerate(175                zip(current_node.bit_lengths, current_node.values)176            ):177                if i in current_node.forced:178                    append_int(n_bits, value)179                else:180                    while True:181                        k = random.getrandbits(n_bits)182                        if k != value:183                            append_int(n_bits, k)184                            break185                    # We've now found a value that is allowed to186                    # vary, so what follows is not fixed.187                    return hbytes(novel_prefix)188            else:189                assert not isinstance(current_node.transition, Conclusion)190                if current_node.transition is None:191                    return hbytes(novel_prefix)192                branch = current_node.transition193                assert isinstance(branch, Branch)194                n_bits = branch.bit_length195                while True:196                    k = random.getrandbits(n_bits)197                    try:198                        child = branch.children[k]199                    except KeyError:200                        append_int(n_bits, k)201                        return hbytes(novel_prefix)202                    if not child.is_exhausted:203                        append_int(n_bits, k)204                        current_node = child205                        break206    def rewrite(self, buffer):207        """Use previously seen ConjectureData objects to return a tuple of208        the rewritten buffer and the status we would get from running that209        buffer with the test function. If the status cannot be predicted210        from the existing values it will be None."""211        buffer = hbytes(buffer)212        data = ConjectureData.for_buffer(buffer)213        try:214            self.simulate_test_function(data)215            return (data.buffer, data.status)216        except PreviouslyUnseenBehaviour:217            return (buffer, None)218    def simulate_test_function(self, data):219        """Run a simulated version of the test function recorded by220        this tree. Note that this does not currently call ``stop_example``221        or ``start_example`` as these are not currently recorded in the222        tree. This will likely change in future."""223        node = self.root224        try:225            while True:226                for i, (n_bits, previous) in enumerate(227                    zip(node.bit_lengths, node.values)228                ):229                    v = data.draw_bits(230                        n_bits, forced=node.values[i] if i in node.forced else None231                    )232                    if v != previous:233                        raise PreviouslyUnseenBehaviour()234                if isinstance(node.transition, Conclusion):235                    t = node.transition236                    data.conclude_test(t.status, t.interesting_origin)237                elif node.transition is None:238                    raise PreviouslyUnseenBehaviour()239                else:240                    v = data.draw_bits(node.transition.bit_length)241                    try:242                        node = node.transition.children[v]243                    except KeyError:244                        raise PreviouslyUnseenBehaviour()245        except StopTest:246            pass247    def new_observer(self):248        return TreeRecordingObserver(self)249class TreeRecordingObserver(DataObserver):250    def __init__(self, tree):251        self.__current_node = tree.root252        self.__index_in_current_node = 0253        self.__trail = [self.__current_node]254    def draw_bits(self, n_bits, forced, value):255        i = self.__index_in_current_node256        self.__index_in_current_node += 1257        node = self.__current_node258        assert len(node.bit_lengths) == len(node.values)259        if i < len(node.bit_lengths):260            if n_bits != node.bit_lengths[i]:261                inconsistent_generation()262            # Note that we don't check whether a previously263            # forced value is now free. That will be caught264            # if we ever split the node there, but otherwise265            # may pass silently. This is acceptable because it266            # means we skip a hash set lookup on every267            # draw and that's a pretty niche failure mode.268            if forced and i not in node.forced:269                inconsistent_generation()270            if value != node.values[i]:271                node.split_at(i)272                assert i == len(node.values)273                new_node = TreeNode()274                branch = node.transition275                branch.children[value] = new_node276                self.__current_node = new_node277                self.__index_in_current_node = 0278        else:279            trans = node.transition280            if trans is None:281                node.bit_lengths.append(n_bits)282                node.values.append(value)283                if forced:284                    node.mark_forced(i)285            elif isinstance(trans, Conclusion):286                assert trans.status != Status.OVERRUN287                # We tried to draw where history says we should have288                # stopped289                inconsistent_generation()290            else:291                assert isinstance(trans, Branch)292                if n_bits != trans.bit_length:293                    inconsistent_generation()294                try:295                    self.__current_node = trans.children[value]296                except KeyError:297                    self.__current_node = trans.children.setdefault(value, TreeNode())298                self.__index_in_current_node = 0299        if self.__trail[-1] is not self.__current_node:300            self.__trail.append(self.__current_node)301    def conclude_test(self, status, interesting_origin):302        """Says that ``status`` occurred at node ``node``. This updates the303        node if necessary and checks for consistency."""304        if status == Status.OVERRUN:305            return306        i = self.__index_in_current_node307        node = self.__current_node308        if i < len(node.values) or isinstance(node.transition, Branch):309            inconsistent_generation()310        new_transition = conclusion(status, interesting_origin)311        if node.transition is not None and node.transition != new_transition:312            # As an, I'm afraid, horrible bodge, we deliberately ignore flakiness313            # where tests go from interesting to valid, because it's much easier314            # to produce good error messages for these further up the stack.315            if (316                node.transition.status != Status.INTERESTING317                or new_transition.status != Status.VALID318            ):319                raise Flaky(320                    "Inconsistent test results! Test case was %r on first run but %r on second"321                    % (node.transition, new_transition)322                )323        else:324            node.transition = new_transition325        assert node is self.__trail[-1]326        node.check_exhausted()327        assert len(node.values) > 0 or node.check_exhausted()328        for t in reversed(self.__trail):329            # Any node we've traversed might have now become exhausted.330            # We check from the right. As soon as we hit a node that331            # isn't exhausted, this automatically implies that all of332            # its parents are not exhausted, so we stop.333            if not t.check_exhausted():...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!!
