How to use run_block_program method in hypothesis

Best Python code snippet using hypothesis

shrinker.py

Source:shrinker.py Github

copy

Full Screen

...1100 if can_replace_with(mid):1101 hi = mid1102 else:1103 lo = mid1104 def run_block_program(self, i, description, original, repeats=1):1105 """Block programs are a mini-DSL for block rewriting, defined as a sequence1106 of commands that can be run at some index into the blocks1107 Commands are:1108 * "-", subtract one from this block.1109 * "X", delete this block1110 If a command does not apply (currently only because it's - on a zero1111 block) the block will be silently skipped over.1112 This method runs the block program in ``description`` at block index1113 ``i`` on the ConjectureData ``original``. If ``repeats > 1`` then it1114 will attempt to approximate the results of running it that many times.1115 Returns True if this successfully changes the underlying shrink target,1116 else False.1117 """1118 if i + len(description) > len(original.blocks) or i < 0:1119 return False1120 attempt = bytearray(original.buffer)1121 for _ in range(repeats):1122 for k, d in reversed(list(enumerate(description))):1123 j = i + k1124 u, v = original.blocks[j].bounds1125 if v > len(attempt):1126 return False1127 if d == "-":1128 value = int_from_bytes(attempt[u:v])1129 if value == 0:1130 return False1131 else:1132 attempt[u:v] = int_to_bytes(value - 1, v - u)1133 elif d == "X":1134 del attempt[u:v]1135 else: # pragma: no cover1136 raise AssertionError("Unrecognised command %r" % (d,))1137 return self.incorporate_new_buffer(attempt)1138def block_program(description):1139 """Mini-DSL for block rewriting. A sequence of commands that will be run1140 over all contiguous sequences of blocks of the description length in order.1141 Commands are:1142 * ".", keep this block unchanged1143 * "-", subtract one from this block.1144 * "0", replace this block with zero1145 * "X", delete this block1146 If a command does not apply (currently only because it's - on a zero1147 block) the block will be silently skipped over. As a side effect of1148 running a block program its score will be updated.1149 """1150 name = "block_program(%r)" % (description,)1151 if name not in SHRINK_PASS_DEFINITIONS:1152 """Defines a shrink pass that runs the block program ``description``1153 at every block index."""1154 n = len(description)1155 def run(self, chooser):1156 """Adaptively attempt to run the block program at the current1157 index. If this successfully applies the block program ``k`` times1158 then this runs in ``O(log(k))`` test function calls."""1159 i = chooser.choose(range(len(self.shrink_target.blocks) - n))1160 # First, run the block program at the chosen index. If this fails,1161 # don't do any extra work, so that failure is as cheap as possible.1162 if not self.run_block_program(i, description, original=self.shrink_target):1163 return1164 # Because we run in a random order we will often find ourselves in the middle1165 # of a region where we could run the block program. We thus start by moving1166 # left to the beginning of that region if possible in order to to start from1167 # the beginning of that region.1168 def offset_left(k):1169 return i - k * n1170 i = offset_left(1171 find_integer(1172 lambda k: self.run_block_program(1173 offset_left(k), description, original=self.shrink_target1174 )1175 )1176 )1177 original = self.shrink_target1178 # Now try to run the block program multiple times here.1179 find_integer(1180 lambda k: self.run_block_program(1181 i, description, original=original, repeats=k1182 )1183 )1184 run.__name__ = name1185 defines_shrink_pass()(run)1186 assert name in SHRINK_PASS_DEFINITIONS1187 return name1188@attr.s(slots=True, eq=False)1189class ShrinkPass:1190 run_with_chooser = attr.ib()1191 index = attr.ib()1192 shrinker = attr.ib()1193 next_prefix = attr.ib(default=())1194 fixed_point_at = attr.ib(default=None)...

Full Screen

Full Screen

test_conjecture_engine.py

Source:test_conjecture_engine.py Github

copy

Full Screen

1# This file is part of Hypothesis, which may be found at2# https://github.com/HypothesisWorks/hypothesis/3#4# Most of this work is copyright (C) 2013-2020 David R. MacIver5# (david@drmaciver.com), but it contains contributions by others. See6# CONTRIBUTING.rst for a full list of people who may hold copyright, and7# consult the git log if you need to determine who owns an individual8# contribution.9#10# This Source Code Form is subject to the terms of the Mozilla Public License,11# v. 2.0. If a copy of the MPL was not distributed with this file, You can12# obtain one at https://mozilla.org/MPL/2.0/.13#14# END HEADER15from hypothesis import given, settings, strategies as st16from hypothesis.database import InMemoryExampleDatabase17from hypothesis.internal.compat import int_from_bytes18from hypothesis.internal.conjecture.data import ConjectureData19from hypothesis.internal.conjecture.engine import ConjectureRunner20from hypothesis.internal.conjecture.shrinker import Shrinker, block_program21from tests.common.utils import counts_calls, non_covering_examples22from tests.conjecture.common import run_to_buffer, shrinking_from23def test_lot_of_dead_nodes():24 @run_to_buffer25 def x(data):26 for i in range(4):27 if data.draw_bytes(1)[0] != i:28 data.mark_invalid()29 data.mark_interesting()30 assert x == bytes([0, 1, 2, 3])31def test_saves_data_while_shrinking(monkeypatch):32 key = b"hi there"33 n = 534 db = InMemoryExampleDatabase()35 assert list(db.fetch(key)) == []36 seen = set()37 monkeypatch.setattr(38 ConjectureRunner,39 "generate_new_examples",40 lambda runner: runner.cached_test_function([255] * 10),41 )42 def f(data):43 x = data.draw_bytes(10)44 if sum(x) >= 2000 and len(seen) < n:45 seen.add(x)46 if x in seen:47 data.mark_interesting()48 runner = ConjectureRunner(f, settings=settings(database=db), database_key=key)49 runner.run()50 assert runner.interesting_examples51 assert len(seen) == n52 in_db = non_covering_examples(db)53 assert in_db.issubset(seen)54 assert in_db == seen55def test_can_discard(monkeypatch):56 n = 857 monkeypatch.setattr(58 ConjectureRunner,59 "generate_new_examples",60 lambda runner: runner.cached_test_function(61 [v for i in range(n) for v in [i, i]]62 ),63 )64 @run_to_buffer65 def x(data):66 seen = set()67 while len(seen) < n:68 seen.add(bytes(data.draw_bytes(1)))69 data.mark_interesting()70 assert len(x) == n71def test_regression_1():72 # This is a really hard to reproduce bug that previously triggered a very73 # specific exception inside one of the shrink passes. It's unclear how74 # useful this regression test really is, but nothing else caught the75 # problem.76 @run_to_buffer77 def x(data):78 data.write(b"\x01\x02")79 data.write(b"\x01\x00")80 v = data.draw_bits(41)81 if v >= 512 or v == 254:82 data.mark_interesting()83 assert list(x)[:-2] == [1, 2, 1, 0, 0, 0, 0, 0]84 assert int_from_bytes(x[-2:]) in (254, 512)85@given(st.integers(0, 255), st.integers(0, 255))86def test_cached_with_masked_byte_agrees_with_results(byte_a, byte_b):87 def f(data):88 data.draw_bits(2)89 runner = ConjectureRunner(f)90 cached_a = runner.cached_test_function(bytes([byte_a]))91 cached_b = runner.cached_test_function(bytes([byte_b]))92 data_b = ConjectureData.for_buffer(93 bytes([byte_b]), observer=runner.tree.new_observer()94 )95 runner.test_function(data_b)96 # If the cache found an old result, then it should match the real result.97 # If it did not, then it must be because A and B were different.98 assert (cached_a is cached_b) == (cached_a.buffer == data_b.buffer)99def test_block_programs_fail_efficiently(monkeypatch):100 # Create 256 byte-sized blocks. None of the blocks can be deleted, and101 # every deletion attempt produces a different buffer.102 @shrinking_from(bytes(range(256)))103 def shrinker(data):104 values = set()105 for _ in range(256):106 v = data.draw_bits(8)107 values.add(v)108 if len(values) == 256:109 data.mark_interesting()110 monkeypatch.setattr(111 Shrinker, "run_block_program", counts_calls(Shrinker.run_block_program)112 )113 shrinker.max_stall = 500114 shrinker.fixate_shrink_passes([block_program("XX")])115 assert shrinker.shrinks == 0116 assert 250 <= shrinker.calls <= 260117 # The block program should have been run roughly 255 times, with a little118 # bit of wiggle room for implementation details.119 # - Too many calls mean that failing steps are doing too much work.120 # - Too few calls mean that this test is probably miscounting and buggy....

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful